function generateFlightPath(polygon, spacing, angle = 0) {
console.log('ops',polygon,spacing,angle)
const bounds = getRotatedBounds(polygon, angle);
const lines = generateScanLines(bounds, spacing);
const rotatedPoints = [];
const cosAngle = Math.cos(-angle);
const sinAngle = Math.sin(-angle);
lines.forEach(y => {
const intersections = getPolygonIntersections(polygon, y, angle);
intersections.sort((a, b) => a.x - b.x);
for (let i = 0; i < intersections.length; i += 2) {
if (i + 1 < intersections.length) {
const start = intersections[i];
const end = intersections[i + 1];
const distance = Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2));
const pointsCount = Math.floor(distance / spacing);
for (let j = 0; j <= pointsCount; j++) {
const t = j / pointsCount;
const x = start.x + t * (end.x - start.x);
const y = start.y + t * (end.y - start.y);
rotatedPoints.push({x, y});
}
}
}
});
return rotatedPoints.map(p => ({
x: p.x * cosAngle - p.y * sinAngle,
y: p.x * sinAngle + p.y * cosAngle
}));
}
function getRotatedBounds(polygon, angle) {
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
polygon.forEach(p => {
const x = p.x * cosAngle + p.y * sinAngle;
const y = -p.x * sinAngle + p.y * cosAngle;
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
});
return {minX, maxX, minY, maxY};
}
function generateScanLines(bounds, spacing) {
const lines = [];
for (let y = bounds.minY; y <= bounds.maxY; y += spacing) {
lines.push(y);
}
return lines;
}
function getPolygonIntersections(polygon, y, angle) {
const intersections = [];
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
const rotatedPolygon = polygon.map(p => ({
x: p.x * cosAngle + p.y * sinAngle,
y: -p.x * sinAngle + p.y * cosAngle
}));
for (let i = 0; i < rotatedPolygon.length; i++) {
const p1 = rotatedPolygon[i];
const p2 = rotatedPolygon[(i + 1) % rotatedPolygon.length];
if (Math.abs(p1.y - p2.y) < 1e-6) continue;
if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
const t = (y - p1.y) / (p2.y - p1.y);
const x = p1.x + t * (p2.x - p1.x);
intersections.push({
x: x * cosAngle - y * sinAngle,
y: x * sinAngle + y * cosAngle
});
}
}
return intersections;
}
const polygon = [
{x: 0, y: 0},
{x: 100, y: 0},
{x: 100, y: 50},
{x: 50, y: 100},
{x: 0, y: 50}
];
const spacing = 10;
const angle = Math.PI / 4;
const flightPath = generateFlightPath(polygon, spacing, angle);
console.log(flightPath);
console