Skip to content

Instantly share code, notes, and snippets.

@IkarosKappler
Last active December 17, 2021 19:03
Show Gist options
  • Save IkarosKappler/b39c3aac124329e65ee4d510147624d5 to your computer and use it in GitHub Desktop.
Save IkarosKappler/b39c3aac124329e65ee4d510147624d5 to your computer and use it in GitHub Desktop.
Evenly distribute n vertices along a path or polygon.
/**
* The main function.
*
* @param {Polygon} polygon
* @param {number} pointCount - Must not be negative.
*/
var ep = function (polygon, pointCount) {
if (pointCount <= 0) {
throw new Error("pointCount must be larger than zero; is " + pointCount + ".");
}
var result = new Polygon([], polygon.isOpen);
if (polygon.vertices.length === 0) {
return result;
}
// Fetch and add the start point from the source polygon
var polygonPoint = new Vertex(polygon.vertices[0]);
result.vertices.push(polygonPoint);
if (polygon.vertices.length === 1) {
return result;
}
var perimeter = polygon.perimeter();
var stepSize = perimeter / (pointCount + 0);
var segmentLength = 0;
var n = polygon.vertices.length;
var polygonIndex = 1;
var nextPolygonPoint = new Vertex(polygon.vertices[1]);
var loopMax = polygon.isOpen ? n : n + 1;
var curSegmentU = stepSize;
var i = 1;
while (i < pointCount && polygonIndex < loopMax) {
var segmentLength = polygonPoint.distance(nextPolygonPoint);
// Check if next eq point is inside this segment
if (curSegmentU < segmentLength) {
var newPoint = lerpAbs(polygonPoint, curSegmentU, nextPolygonPoint);
result.vertices.push(newPoint);
curSegmentU += stepSize;
i++;
} else {
polygonIndex++;
polygonPoint = nextPolygonPoint;
nextPolygonPoint = new Vertex(polygon.vertices[polygonIndex % n]);
curSegmentU = curSegmentU - segmentLength;
}
}
return result;
};
var lerpAbs = function (vert, u, target) {
var dist = vert.distance(target);
var diff = vert.difference(target);
var step = { x: diff.x / dist, y: diff.y / dist };
return new Vertex(vert.x + step.x * u, vert.y + step.y * u);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment