@anandommi/fields2cover 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,219 @@
1
+ const turf = require('@turf/turf');
2
+ const { closeMowerPath } = require('./mowerLoopPath');
3
+ const { closeMowerPathFallback } = require('./mowerLoopFallback');
4
+ const { planCoverage, CONNECTOR_BOUNDARY_CLEARANCE_M, CONNECTOR_OBSTACLE_CLEARANCE_M } = require('./coverage');
5
+ const { fieldArea } = require('./headland');
6
+ const { createLocalFrame } = require('./frame');
7
+
8
+ // Request handling for the Fields2Cover-style planner (POST
9
+ // /api/generateF2cMowerPath). Same request body and response shape as the
10
+ // existing /api/generateMowerPath, which is left untouched — this is a
11
+ // separate generator alongside it.
12
+
13
+ // Keep the join connector's endpoint under 50 cm from the first mowing point,
14
+ // same as the existing generator.
15
+ const LOOP_GAP_M = 0.3;
16
+
17
+ // Turns, connections and laps are sampled every 0.1 m while planning, which
18
+ // left ~130k points (7 MB+) on a 2 ha field — mostly on straight stretches.
19
+ // The output keeps only the points needed to stay within this distance of
20
+ // the planned path: a straight is just its two end points, an R = 6 m arc
21
+ // keeps a point about every 0.5 m.
22
+ const OUTPUT_TOLERANCE_M = 0.005;
23
+
24
+ // Douglas–Peucker in local metres (iterative, so long paths cannot overflow
25
+ // the stack). First and last points are always kept.
26
+ function simplifyPath(coordinates, tolerance) {
27
+ if (coordinates.length < 3) return coordinates;
28
+ const frame = createLocalFrame(coordinates[0]);
29
+ const pts = coordinates.map(frame.toLocal);
30
+ const keep = new Uint8Array(pts.length);
31
+ keep[0] = 1;
32
+ keep[pts.length - 1] = 1;
33
+ const stack = [[0, pts.length - 1]];
34
+ while (stack.length) {
35
+ const [first, last] = stack.pop();
36
+ const [ax, ay] = pts[first];
37
+ const dx = pts[last][0] - ax;
38
+ const dy = pts[last][1] - ay;
39
+ const len = Math.hypot(dx, dy);
40
+ let worst = -1;
41
+ let worstDist = tolerance;
42
+ for (let i = first + 1; i < last; i += 1) {
43
+ const px = pts[i][0] - ax;
44
+ const py = pts[i][1] - ay;
45
+ // Distance to the segment (to the end point when they coincide, e.g.
46
+ // a closed lap that starts and ends at the same spot).
47
+ let dist;
48
+ if (len < 1e-9) {
49
+ dist = Math.hypot(px, py);
50
+ } else {
51
+ const t = Math.max(0, Math.min(1, (px * dx + py * dy) / (len * len)));
52
+ dist = Math.hypot(px - t * dx, py - t * dy);
53
+ }
54
+ if (dist > worstDist) {
55
+ worstDist = dist;
56
+ worst = i;
57
+ }
58
+ }
59
+ if (worst >= 0) {
60
+ keep[worst] = 1;
61
+ stack.push([first, worst], [worst, last]);
62
+ }
63
+ }
64
+ return coordinates.filter((_, i) => keep[i]);
65
+ }
66
+
67
+ // Join start and end, with the same template-then-fallback strategy and the
68
+ // same strict safety check as the existing generator's applyLoopClosure.
69
+ function applyLoopClosure(result, { joinStartAndEnd, turningRadius, safeArea }) {
70
+ if (!joinStartAndEnd) return result;
71
+
72
+ if (!Number.isFinite(turningRadius) || turningRadius <= 0) {
73
+ const error = new Error('A positive turning radius is required to close the mower path.');
74
+ error.status = 422;
75
+ throw error;
76
+ }
77
+
78
+ const pathFeature = result.features.find((feature) => feature.geometry?.type === 'LineString');
79
+ if (!pathFeature) throw new Error('Generated mower path has no LineString to close.');
80
+
81
+ const isSafe = (connector) => {
82
+ if (!safeArea || connector.length < 2) return false;
83
+ if (!connector.every((point) => turf.booleanPointInPolygon(turf.point(point), safeArea))) return false;
84
+ return turf.booleanWithin(turf.lineString(connector), safeArea);
85
+ };
86
+
87
+ let loop = null;
88
+ try {
89
+ const template = closeMowerPath(pathFeature.geometry.coordinates, { turningRadius, gap: LOOP_GAP_M });
90
+ if (isSafe(template.connector)) loop = template;
91
+ } catch (templateError) {
92
+ console.warn("Loop template unavailable, using fallback planner:", templateError.message);
93
+ }
94
+ if (!loop) {
95
+ loop = closeMowerPathFallback(pathFeature.geometry.coordinates, { turningRadius, gap: LOOP_GAP_M, safeArea });
96
+ if (loop && !isSafe(loop.connector)) loop = null;
97
+ }
98
+ if (!loop) {
99
+ const error = new Error(
100
+ "Unable to join the mower path: no route at the configured turning radius from the end point back to the start stays inside the boundary and clear of obstacles. Try a smaller turning radius or a larger boundary offset."
101
+ );
102
+ error.code = "LOOP_CONNECTOR_OUTSIDE_SAFE_AREA";
103
+ error.status = 422;
104
+ throw error;
105
+ }
106
+ const totalLength = turf.length(turf.lineString(loop.coordinates), { units: 'meters' });
107
+ pathFeature.geometry.coordinates = loop.coordinates;
108
+ pathFeature.properties = {
109
+ ...(pathFeature.properties || {}),
110
+ ...loop.properties,
111
+ total_length_meters: Math.round(totalLength * 100) / 100,
112
+ is_closed_loop: false
113
+ };
114
+ return result;
115
+ }
116
+
117
+ // Pure — no req/res. Returns { status, result, contentDisposition } on
118
+ // success or { status, error, message? } on failure.
119
+ function computeF2cMowerPath(body) {
120
+ try {
121
+ if (!body) {
122
+ return { status: 400, error: "Missing request body" };
123
+ }
124
+ const {
125
+ polygonCoords,
126
+ referenceLineCoords,
127
+ offsetDistance,
128
+ spacing,
129
+ turningRadius,
130
+ crissCross,
131
+ obstacleAvoid,
132
+ obstaclePolygons
133
+ } = body;
134
+
135
+ if (!polygonCoords || !referenceLineCoords || offsetDistance == null || offsetDistance === "" || !spacing) {
136
+ return { status: 400, error: "Missing required parameters" };
137
+ }
138
+ // The headland is where every turn happens, so it must be a real width.
139
+ const headlandWidth = Number(offsetDistance);
140
+ if (!Number.isFinite(headlandWidth) || headlandWidth <= 0) {
141
+ return { status: 400, error: "offsetDistance must be a number greater than 0." };
142
+ }
143
+ if (!Array.isArray(polygonCoords) || polygonCoords.length < 4) {
144
+ return { status: 400, error: "polygonCoords must be an array of at least 4 [lng, lat] positions." };
145
+ }
146
+ if (!Array.isArray(referenceLineCoords) || referenceLineCoords.length < 2) {
147
+ return { status: 400, error: "referenceLineCoords must be an array of at least 2 [lng, lat] positions." };
148
+ }
149
+
150
+ // Obstacles only shape the rows and turns when obstacle-avoid is on.
151
+ const obstacles = Array.isArray(obstaclePolygons) ? obstaclePolygons : [];
152
+ const obstacleAware = !!obstacleAvoid && obstacles.length > 0;
153
+
154
+ const plan = planCoverage({
155
+ polygonCoords,
156
+ obstacleRings: obstacleAware ? obstacles : [],
157
+ referenceLineCoords,
158
+ headlandWidth,
159
+ spacing: Number(spacing),
160
+ turningRadius: Number(turningRadius),
161
+ crissCross: !!crissCross
162
+ });
163
+
164
+ if (plan.coordinates.length < 2) {
165
+ return { status: 400, error: "No swath lines could be generated. Offset/obstacles may be too large for this polygon." };
166
+ }
167
+
168
+ const totalLength = turf.length(turf.lineString(plan.coordinates), { units: "meters" });
169
+ const result = {
170
+ type: "FeatureCollection",
171
+ features: [
172
+ {
173
+ type: "Feature",
174
+ properties: {
175
+ type: "complete_mower_path",
176
+ total_length_meters: Math.round(totalLength * 100) / 100,
177
+ is_computer_generated: true,
178
+ planner: "fields2cover",
179
+ criss_cross: !!crissCross,
180
+ obstacle_aware: obstacleAware,
181
+ obstacle_count: obstacleAware ? obstacles.length : 0
182
+ },
183
+ geometry: { type: "LineString", coordinates: plan.coordinates }
184
+ }
185
+ ]
186
+ };
187
+
188
+ // The join connector must stay inside the boundary and clear of obstacles
189
+ // even when obstacle-avoid is off for the mowing rows themselves.
190
+ let loopSafeArea = plan.driveFeature;
191
+ if (body.joinStartAndEnd && !obstacleAware && obstacles.length) {
192
+ loopSafeArea = fieldArea(
193
+ polygonCoords,
194
+ obstacles,
195
+ Math.min(headlandWidth, CONNECTOR_BOUNDARY_CLEARANCE_M),
196
+ Math.min(headlandWidth, CONNECTOR_OBSTACLE_CLEARANCE_M)
197
+ );
198
+ }
199
+ applyLoopClosure(result, { joinStartAndEnd: !!body.joinStartAndEnd, turningRadius, safeArea: loopSafeArea });
200
+ const pathGeometry = result.features[0].geometry;
201
+ pathGeometry.coordinates = simplifyPath(pathGeometry.coordinates, OUTPUT_TOLERANCE_M);
202
+ return {
203
+ status: 200,
204
+ result,
205
+ contentDisposition: obstacleAware
206
+ ? "attachment; filename=mower_path_f2c_obstacle_aware.geojson"
207
+ : "attachment; filename=mower_path_f2c.geojson"
208
+ };
209
+ } catch (error) {
210
+ console.error("Error generating F2C mower path:", error);
211
+ return {
212
+ status: error.status || 500,
213
+ error: error.status ? error.message : "Failed to generate mower path",
214
+ ...(error.status ? {} : { message: error.message })
215
+ };
216
+ }
217
+ }
218
+
219
+ module.exports = { computeF2cMowerPath };
@@ -0,0 +1,362 @@
1
+ const turf = require('@turf/turf');
2
+ const { dubinsCandidates, sampleDubins } = require('./mowerLoopFallback');
3
+ const { areaFromGeoJSON, freeSpaceReflexVertices } = require('./geometry');
4
+ const { bufferMeters } = require('./headland');
5
+
6
+ // Port of Fields2Cover's pp::PathPlanning plus the v2 route planner's
7
+ // headland transit. Every connection is a minimum-radius Dubins path that
8
+ // must stay inside the drive area (boundary and obstacle clearance already
9
+ // applied), and never loops. When no single Dubins word fits, the vehicle
10
+ // either swings out wide and comes back (two smooth turns), or transits
11
+ // through the free space: shortest path over a visibility graph of
12
+ // free-space corners, then a chain of Dubins hops along it.
13
+
14
+ const CHECK_STEP_M = 0.25;
15
+ const OUTPUT_STEP_M = 0.1; // same point density the vehicle already gets on turns
16
+ const NODE_SIMPLIFY_TOLERANCE_DEG = 0.000004; // ~0.4m, keeps the graph small
17
+ const TWO_HOP_RADII = [1.5, 2.5, 4, 5]; // intermediate poses this many turning radii out
18
+ const TWO_HOP_BEARINGS = 12;
19
+ const TWO_HOP_HEADINGS = 8;
20
+ const TWO_HOP_CHECKS = 60;
21
+ const ESCAPE_RADII = [4, 5]; // far enough that reaching it means actually leaving a pocket
22
+ const ESCAPE_CHECKS = 40;
23
+
24
+ const pose = (x, y, th) => ({ x, y, th });
25
+
26
+ // No loops: a single manoeuvre may turn at most a U-turn plus a little
27
+ // (enough for a U-turn between rows whose ends are not level). Anything more
28
+ // is a circle/loop, which the operator does not want.
29
+ const MAX_TURN_RAD = Math.PI + 0.35;
30
+ const L_SEG = 0;
31
+ const S_SEG = 1;
32
+ const turnOf = (word) => word.params.reduce((sum, value, i) => (word.types[i] === S_SEG ? sum : sum + value), 0);
33
+
34
+ // No semicircles either: a U-turn must be quarter arc, straight, quarter
35
+ // arc. A single arc this long only appears in a bare semicircle U-turn
36
+ // (rows exactly one turn diameter apart) or a near-loop.
37
+ const MAX_SINGLE_ARC_RAD = (150 * Math.PI) / 180;
38
+ // Two same-way arcs read as one arc (a semicircle) unless a straight of at
39
+ // least this × R separates them — the same flat U-turn the row order plans.
40
+ const UTURN_STRAIGHT_FACTOR = 0.5;
41
+ // Longest same-way arc across one or more consecutive words (hops of one
42
+ // connection chain their arcs just like segments of one word do).
43
+ function longestArc(words) {
44
+ let longest = 0;
45
+ let run = 0;
46
+ let runType = null;
47
+ [].concat(words).forEach((word) => word.types.forEach((type, i) => {
48
+ const amount = word.params[i];
49
+ if (amount < 1e-9) return;
50
+ if (type === S_SEG) {
51
+ if (amount >= UTURN_STRAIGHT_FACTOR - 1e-6) {
52
+ run = 0;
53
+ runType = null;
54
+ }
55
+ return;
56
+ }
57
+ run = type === runType ? run + amount : amount;
58
+ runType = type;
59
+ longest = Math.max(longest, run);
60
+ }));
61
+ return longest;
62
+ }
63
+
64
+ // Number of U-turn sized turns in a chain: turning (either way) between
65
+ // straights of at least the flat-U-turn straight, totalling over 120°.
66
+ function uTurnCount(words) {
67
+ let count = 0;
68
+ let group = 0;
69
+ const close = () => {
70
+ if (group > U_TURN_SIZED_RAD) count += 1;
71
+ group = 0;
72
+ };
73
+ [].concat(words).forEach((word) => word.types.forEach((type, i) => {
74
+ const amount = word.params[i];
75
+ if (type === S_SEG) {
76
+ if (amount >= UTURN_STRAIGHT_FACTOR - 1e-6) close();
77
+ return;
78
+ }
79
+ group += amount;
80
+ }));
81
+ close();
82
+ return count;
83
+ }
84
+
85
+ // A chain of hops is acceptable when, taken as one manoeuvre, it neither
86
+ // loops, nor bends through a semicircle, nor swings out and back with two
87
+ // U-turns.
88
+ //
89
+ // `wrapping`: a lap going round an obstacle corner, where one long arc is the
90
+ // ring itself rather than a U-turn — only the no-loop limit applies.
91
+ const chainIsSmooth = (words, { wrapping = false } = {}) => longestTurn(words) <= MAX_TURN_RAD
92
+ && (wrapping || (longestArc(words) <= MAX_SINGLE_ARC_RAD && uTurnCount(words) <= 1));
93
+
94
+ // Dubins words between two poses, shortest first, without loops or (unless
95
+ // `wrapping`, see chainIsSmooth) semicircles.
96
+ function smoothWords(from, to, radius, { wrapping = false } = {}) {
97
+ return dubinsCandidates(from, to, radius)
98
+ .filter((word) => turnOf(word) <= MAX_TURN_RAD && (wrapping || longestArc(word) <= MAX_SINGLE_ARC_RAD));
99
+ }
100
+
101
+ // A turn this big counts as a U-turn; two in one connection is a swing out
102
+ // and back, which the operator does not want.
103
+ const U_TURN_SIZED_RAD = (120 * Math.PI) / 180;
104
+
105
+ // Longest continuous same-direction turn across consecutive words (a hop
106
+ // ending in a left arc followed by one starting with a left arc is one turn).
107
+ // Two loop-free U-turns back to back the same way are still a full circle.
108
+ function longestTurn(words) {
109
+ let longest = 0;
110
+ let run = 0;
111
+ words.forEach((word) => word.types.forEach((type, i) => {
112
+ const amount = word.params[i];
113
+ if (amount < 1e-9) return;
114
+ if (type === S_SEG) {
115
+ run = 0;
116
+ return;
117
+ }
118
+ const signed = type === L_SEG ? amount : -amount;
119
+ run = Math.sign(run) === Math.sign(signed) ? run + signed : signed;
120
+ longest = Math.max(longest, Math.abs(run));
121
+ }));
122
+ return longest;
123
+ }
124
+
125
+ class PathPlanner {
126
+ constructor({ driveArea, driveFeature, toLocal, radius }) {
127
+ this.driveArea = driveArea;
128
+ this.driveFeature = driveFeature;
129
+ this.toLocal = toLocal;
130
+ this.radius = radius;
131
+ this.graphs = new Map();
132
+ // Larger margins first: waypoints further from obstacles leave the Dubins
133
+ // hops room to turn; smaller ones still get through narrow passages.
134
+ this.margins = [...new Set([radius, radius / 2, 2, 1].map((m) => Math.max(0.5, m)))];
135
+ }
136
+
137
+ // Shortest loop-free Dubins word that stays inside the drive area, or null.
138
+ direct(from, to) {
139
+ for (const word of smoothWords(from, to, this.radius)) {
140
+ if (this.driveArea.containsAll(sampleDubins(word, CHECK_STEP_M))) {
141
+ return { points: sampleDubins(word, OUTPUT_STEP_M), length: word.length, words: [word] };
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ connect(from, to) {
148
+ return this.direct(from, to) || this.transit(from, to);
149
+ }
150
+
151
+ transit(from, to) {
152
+ const turnaround = this.twoHop(from, to);
153
+ if (turnaround) return turnaround;
154
+ for (const margin of this.margins) {
155
+ const graph = this.graph(margin);
156
+ if (!graph) continue;
157
+ const waypoints = this.shortestPath(graph, [from.x, from.y], [to.x, to.y]);
158
+ if (!waypoints || waypoints.length === 0) continue;
159
+ const result = this.followWaypoints(from, waypoints, to);
160
+ if (result) return result;
161
+ }
162
+ return null;
163
+ }
164
+
165
+ // Target the shortest smooth turn cannot reach (it would leave the drive
166
+ // area, or needs more than one manoeuvre's worth of turning — e.g. onto
167
+ // the perpendicular rows of a criss-cross pass): detour through an
168
+ // intermediate pose. At most one of the two hops may be a U-turn — no
169
+ // swinging out with a U-turn and back with another. Candidates are ranked
170
+ // by unchecked length and only the best few are validated.
171
+ twoHop(from, to) {
172
+ const candidates = [];
173
+ const centres = [[from.x, from.y], [(from.x + to.x) / 2, (from.y + to.y) / 2], [to.x, to.y]];
174
+ centres.forEach(([cx, cy]) => {
175
+ TWO_HOP_RADII.forEach((k) => {
176
+ for (let b = 0; b < TWO_HOP_BEARINGS; b += 1) {
177
+ const angle = (2 * Math.PI * b) / TWO_HOP_BEARINGS;
178
+ const x = cx + k * this.radius * Math.cos(angle);
179
+ const y = cy + k * this.radius * Math.sin(angle);
180
+ if (!this.driveArea.contains(x, y)) continue;
181
+ for (let h = 0; h < TWO_HOP_HEADINGS; h += 1) {
182
+ const mid = pose(x, y, (2 * Math.PI * h) / TWO_HOP_HEADINGS);
183
+ const first = smoothWords(from, mid, this.radius)[0];
184
+ if (!first) continue;
185
+ const second = smoothWords(mid, to, this.radius)[0];
186
+ if (!second || !chainIsSmooth([first, second])) continue;
187
+ candidates.push({ mid, length: first.length + second.length });
188
+ }
189
+ }
190
+ });
191
+ });
192
+ candidates.sort((a, b) => a.length - b.length);
193
+ for (const { mid } of candidates.slice(0, TWO_HOP_CHECKS)) {
194
+ const first = this.direct(from, mid);
195
+ if (!first) continue;
196
+ const second = this.direct(mid, to);
197
+ if (!second || !chainIsSmooth([...first.words, ...second.words])) continue;
198
+ return { points: [...first.points, ...second.points.slice(1)], length: first.length + second.length, words: [...first.words, ...second.words] };
199
+ }
200
+ return null;
201
+ }
202
+
203
+ // True when some smooth, valid manoeuvre leads away from `from` — i.e. the
204
+ // vehicle is not stuck facing a wall in a pocket too narrow to turn in.
205
+ // `radii`: how far out (in turning radii) the manoeuvre must get.
206
+ canEscape(from, radii = ESCAPE_RADII) {
207
+ const candidates = [];
208
+ radii.forEach((k) => {
209
+ for (let b = 0; b < TWO_HOP_BEARINGS; b += 1) {
210
+ const angle = (2 * Math.PI * b) / TWO_HOP_BEARINGS;
211
+ const x = from.x + k * this.radius * Math.cos(angle);
212
+ const y = from.y + k * this.radius * Math.sin(angle);
213
+ if (!this.driveArea.contains(x, y)) continue;
214
+ for (let h = 0; h < TWO_HOP_HEADINGS; h += 1) {
215
+ const target = pose(x, y, (2 * Math.PI * h) / TWO_HOP_HEADINGS);
216
+ const word = smoothWords(from, target, this.radius)[0];
217
+ if (word) candidates.push({ target, length: word.length });
218
+ }
219
+ }
220
+ });
221
+ candidates.sort((a, b) => a.length - b.length);
222
+ return candidates.slice(0, ESCAPE_CHECKS).some(({ target }) => this.direct(from, target));
223
+ }
224
+
225
+ graph(margin) {
226
+ if (this.graphs.has(margin)) return this.graphs.get(margin);
227
+ let graph = null;
228
+ try {
229
+ const shrunk = bufferMeters(this.driveFeature, -margin);
230
+ if (shrunk) {
231
+ const simplified = turf.simplify(shrunk, { tolerance: NODE_SIMPLIFY_TOLERANCE_DEG });
232
+ const nodes = freeSpaceReflexVertices(areaFromGeoJSON(simplified, this.toLocal))
233
+ .filter(([x, y]) => this.driveArea.contains(x, y));
234
+ graph = { nodes, adjacency: new Map() };
235
+ }
236
+ } catch (err) {
237
+ console.warn(`Transit graph unavailable at ${margin} m margin:`, err.message);
238
+ }
239
+ this.graphs.set(margin, graph);
240
+ return graph;
241
+ }
242
+
243
+ neighbours(graph, index) {
244
+ if (!graph.adjacency.has(index)) {
245
+ const a = graph.nodes[index];
246
+ const list = [];
247
+ graph.nodes.forEach((b, j) => {
248
+ if (j !== index && this.driveArea.segmentClear(a, b)) list.push(j);
249
+ });
250
+ graph.adjacency.set(index, list);
251
+ }
252
+ return graph.adjacency.get(index);
253
+ }
254
+
255
+ // A* over the visibility graph; returns the intermediate corner points
256
+ // (start and goal excluded), or null when the goal is unreachable.
257
+ shortestPath(graph, start, goal) {
258
+ const { nodes } = graph;
259
+ const START = nodes.length;
260
+ const GOAL = nodes.length + 1;
261
+ const point = (i) => (i === START ? start : i === GOAL ? goal : nodes[i]);
262
+ const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
263
+
264
+ // Checked only for the nodes the search actually expands.
265
+ const goalVisible = new Map();
266
+ const seesGoal = (j) => {
267
+ if (!goalVisible.has(j)) goalVisible.set(j, this.driveArea.segmentClear(nodes[j], goal));
268
+ return goalVisible.get(j);
269
+ };
270
+ const edgesOf = (i) => {
271
+ if (i === START) {
272
+ const list = [];
273
+ nodes.forEach((n, j) => {
274
+ if (this.driveArea.segmentClear(start, n)) list.push(j);
275
+ });
276
+ if (this.driveArea.segmentClear(start, goal)) list.push(GOAL);
277
+ return list;
278
+ }
279
+ const list = this.neighbours(graph, i);
280
+ return seesGoal(i) ? [...list, GOAL] : list;
281
+ };
282
+
283
+ const g = new Map([[START, 0]]);
284
+ const parent = new Map();
285
+ const open = new Set([START]);
286
+ const closed = new Set();
287
+ while (open.size) {
288
+ let current = null;
289
+ let best = Infinity;
290
+ open.forEach((i) => {
291
+ const f = g.get(i) + dist(point(i), goal);
292
+ if (f < best) {
293
+ best = f;
294
+ current = i;
295
+ }
296
+ });
297
+ if (current === GOAL) {
298
+ const path = [];
299
+ for (let i = parent.get(GOAL); i !== START; i = parent.get(i)) path.unshift(nodes[i]);
300
+ return path;
301
+ }
302
+ open.delete(current);
303
+ closed.add(current);
304
+ for (const j of edgesOf(current)) {
305
+ if (closed.has(j)) continue;
306
+ const cost = g.get(current) + dist(point(current), point(j));
307
+ if (cost < (g.has(j) ? g.get(j) : Infinity)) {
308
+ g.set(j, cost);
309
+ parent.set(j, current);
310
+ open.add(j);
311
+ }
312
+ }
313
+ }
314
+ return null;
315
+ }
316
+
317
+ // Dubins hops along the waypoints, each waypoint passed with the heading
318
+ // bisecting its incoming and outgoing legs. Greedily skips ahead to the
319
+ // furthest pose a single valid hop can reach, so the result is as smooth
320
+ // as the free space allows.
321
+ followWaypoints(from, waypoints, to) {
322
+ const chain = [[from.x, from.y], ...waypoints, [to.x, to.y]];
323
+ const targets = waypoints.map((w, i) => {
324
+ const prev = chain[i];
325
+ const next = chain[i + 2];
326
+ const inA = Math.atan2(w[1] - prev[1], w[0] - prev[0]);
327
+ const outA = Math.atan2(next[1] - w[1], next[0] - w[0]);
328
+ const sx = Math.cos(inA) + Math.cos(outA);
329
+ const sy = Math.sin(inA) + Math.sin(outA);
330
+ const th = Math.hypot(sx, sy) < 1e-6 ? inA : Math.atan2(sy, sx);
331
+ return pose(w[0], w[1], th);
332
+ });
333
+ targets.push(to);
334
+
335
+ const points = [[from.x, from.y]];
336
+ const words = [];
337
+ let length = 0;
338
+ let current = from;
339
+ let index = 0;
340
+ while (index < targets.length) {
341
+ let hop = null;
342
+ let reached = -1;
343
+ for (let j = targets.length - 1; j >= index; j -= 1) {
344
+ const candidate = this.direct(current, targets[j]);
345
+ if (candidate && chainIsSmooth([...words, ...candidate.words])) {
346
+ hop = candidate;
347
+ reached = j;
348
+ break;
349
+ }
350
+ }
351
+ if (!hop) return null;
352
+ points.push(...hop.points.slice(1));
353
+ words.push(...hop.words);
354
+ length += hop.length;
355
+ current = targets[reached];
356
+ index = reached + 1;
357
+ }
358
+ return { points, length, words };
359
+ }
360
+ }
361
+
362
+ module.exports = { PathPlanner, pose, smoothWords, chainIsSmooth, UTURN_STRAIGHT_FACTOR };
@@ -0,0 +1,56 @@
1
+ // Swath order inside one cell — the F2C rp::CustomOrder slot, filled with a
2
+ // leapfrog skip pattern.
3
+ //
4
+ // k is the smallest jump whose *backward* step (k-1 rows) still leaves room
5
+ // for a flat U-turn: quarter arc, a straight of UTURN_STRAIGHT_FACTOR × R,
6
+ // quarter arc — never a bare semicircle, and never a loop. (With
7
+ // k = floor(2R/spacing) the backward step was narrower than 2R and every
8
+ // second turn became a loop.)
9
+ const { UTURN_STRAIGHT_FACTOR } = require('./pathPlanner'); // R=6: 3 m straight across the U-turn
10
+
11
+ function rowSkip(spacing, minTurnRadius) {
12
+ const turnWidth = (2 + UTURN_STRAIGHT_FACTOR) * minTurnRadius;
13
+ return Math.max(1, Math.ceil(turnWidth / spacing - 1e-9) + 1);
14
+ }
15
+
16
+ const generateCustomOrder = (totalSwaths, spacing, minTurnRadius) => {
17
+ if (totalSwaths <= 0) return [];
18
+ const k = rowSkip(spacing, minTurnRadius);
19
+ const customOrder = [];
20
+ const swathsPerCircuit = 2 * k;
21
+ const numCircuits = Math.floor(totalSwaths / swathsPerCircuit);
22
+ const remainingSwaths = totalSwaths % swathsPerCircuit;
23
+ const circuits = [];
24
+ for (let i = 0; i < numCircuits; i++) {
25
+ circuits.push(i === 0 ? swathsPerCircuit + remainingSwaths : swathsPerCircuit);
26
+ }
27
+ if (circuits.length === 0) circuits.push(totalSwaths);
28
+
29
+ let swathCounter = 1; // 1-based start index of the current circuit
30
+ for (let c = 0; c < circuits.length; c++) {
31
+ const circuitSwaths = circuits[c];
32
+ if (c === 0) {
33
+ // First circuit (absorbs the remainder): pair row i with row i+skip.
34
+ const skip = circuitSwaths % 2 === 0 ? circuitSwaths / 2 : Math.floor(circuitSwaths / 2) + 1;
35
+ for (let i = 1; i <= skip; i++) {
36
+ const a = i;
37
+ const b = i + skip;
38
+ if (a <= circuitSwaths) customOrder.push(swathCounter + a - 1);
39
+ if (b <= circuitSwaths) customOrder.push(swathCounter + b - 1);
40
+ }
41
+ } else {
42
+ // Later circuits: start on the high half, then interleave.
43
+ const skip = Math.floor(circuitSwaths / 2);
44
+ for (let i = 0; i < skip; i++) {
45
+ const high = skip + i;
46
+ const low = i;
47
+ if (high < circuitSwaths) customOrder.push(swathCounter + high);
48
+ if (low < circuitSwaths) customOrder.push(swathCounter + low);
49
+ }
50
+ }
51
+ swathCounter += circuitSwaths;
52
+ }
53
+ return customOrder.map((v) => v - 1); // 0-based
54
+ };
55
+
56
+ module.exports = { generateCustomOrder, rowSkip };
package/lib/swaths.js ADDED
@@ -0,0 +1,46 @@
1
+ // Port of Fields2Cover's sg (swath generator) for a fixed angle: parallel
2
+ // swaths one coverage width apart, clipped to the mainland. The angle comes
3
+ // from the user's reference line rather than F2C's brute-force angle search,
4
+ // so the operator keeps control of the mowing direction.
5
+ //
6
+ // Output is per column (one column per swath line u = const), each with the
7
+ // inside intervals [v0, v1] where that line crosses the mainland — a column
8
+ // has several intervals wherever an obstacle or a concave notch cuts it.
9
+ function generateSwathColumns(area, swathFrame, spacing, minLength) {
10
+ const rings = area.polygons.flat().map((ring) => ring.map(swathFrame.toUV));
11
+ let uMin = Infinity;
12
+ let uMax = -Infinity;
13
+ rings.forEach((ring) => ring.forEach(([u]) => {
14
+ if (u < uMin) uMin = u;
15
+ if (u > uMax) uMax = u;
16
+ }));
17
+ const width = uMax - uMin;
18
+ if (!Number.isFinite(width) || width <= 0) return [];
19
+
20
+ // Centre the swaths across the mainland so both outer swaths sit the same
21
+ // distance inside its edges (at most half a coverage width).
22
+ const count = Math.max(1, Math.ceil(width / spacing - 1e-9));
23
+ const first = uMin + (width - (count - 1) * spacing) / 2;
24
+
25
+ const columns = [];
26
+ for (let c = 0; c < count; c += 1) {
27
+ const u = first + c * spacing;
28
+ const crossings = [];
29
+ rings.forEach((ring) => {
30
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
31
+ const [ua, va] = ring[j];
32
+ const [ub, vb] = ring[i];
33
+ if ((ua <= u) !== (ub <= u)) crossings.push(va + ((u - ua) * (vb - va)) / (ub - ua));
34
+ }
35
+ });
36
+ crossings.sort((a, b) => a - b);
37
+ const intervals = [];
38
+ for (let k = 0; k + 1 < crossings.length; k += 2) {
39
+ if (crossings[k + 1] - crossings[k] >= minLength) intervals.push([crossings[k], crossings[k + 1]]);
40
+ }
41
+ columns.push({ u, intervals });
42
+ }
43
+ return columns;
44
+ }
45
+
46
+ module.exports = { generateSwathColumns };