smoothenPath function

dynamic smoothenPath(
  1. dynamic grid,
  2. dynamic path
)

Smoothen the give path. The original path will not be modified; a new path will be returned. @param {PF.Grid} grid @param {Array.<Array.

Implementation

smoothenPath(grid, path) {
    var len = path.length,
        x0 = path[0][0],        // path start x
        y0 = path[0][1],        // path start y
        x1 = path[len - 1][0],  // path end x
        y1 = path[len - 1][1],  // path end y
        sx, sy,                 // current start coordinate
        ex, ey,                 // current end coordinate
        lx, ly,                 // last valid end coordinate
        newPath,
        i, j, coord, line, testCoord, blocked;

    sx = x0;
    sy = y0;
    lx = path[1][0];
    ly = path[1][1];
    newPath = [[sx, sy]];

    for (i = 2; i < len; ++i) {
        coord = path[i];
        ex = coord[0];
        ey = coord[1];
        line = getLine(sx, sy, ex, ey);

        blocked = false;
        for (j = 1; j < line.length; ++j) {
            testCoord = line[j];

            if (!grid.isWalkableAt(testCoord[0], testCoord[1])) {
                blocked = true;
                newPath.push([lx, ly]);
                sx = lx;
                sy = ly;
                break;
            }
        }
        if (!blocked) {
            lx = ex;
            ly = ey;
        }
    }
    newPath.add([x1, y1]);

    return newPath;
}