@anandommi/fields2cover 0.0.0-stage → 0.1.1

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,741 @@
1
+ // Fields2Cover-style coverage planner, ported to JS (turf + local-metre
2
+ // geometry). Same pipeline and stage boundaries as F2C v2:
3
+ //
4
+ // hg headland.js constant-width headland around boundary and obstacles
5
+ // decomp decomposition.js boustrophedon cells, so rows never straddle an obstacle
6
+ // sg swaths.js parallel swaths along the reference line, per column
7
+ // hg headlandLaps.js headland swaths: laps that mow the headland band itself
8
+ // rp routeOrder.js leapfrog row order inside each cell + greedy cell order
9
+ // pp pathPlanner.js min-radius, loop-free Dubins turns, transit around obstacles
10
+ //
11
+ // Differences from F2C: the swath angle comes from the user's reference line
12
+ // (no brute-force angle search), cells are ordered greedily by reachable
13
+ // connection length instead of OR-tools, and every turn/transit is validated
14
+ // against the real drive area — rows whose connection cannot fit are retried
15
+ // later from elsewhere and only reported as skipped if nothing reaches them.
16
+
17
+ const { createLocalFrame, createSwathFrame } = require('./frame');
18
+ const { areaFromGeoJSON } = require('./geometry');
19
+ const { fieldArea, generateMainland } = require('./headland');
20
+ const { generateSwathColumns } = require('./swaths');
21
+ const { decomposeIntoCells } = require('./decomposition');
22
+ const { generateCustomOrder } = require('./routeOrder');
23
+ const { PathPlanner, pose, smoothWords, hasCircle } = require('./pathPlanner');
24
+ const { generateHeadlandLaps } = require('./headlandLaps');
25
+
26
+ const CONNECTOR_BOUNDARY_CLEARANCE_M = 0.3; // just enough to not sit exactly on the true boundary
27
+ const CONNECTOR_OBSTACLE_CLEARANCE_M = 1.0; // minimum physical safety gap from an obstacle during a turn
28
+ // Rows shorter than one turning radius (slivers where an obstacle's headland
29
+ // nearly meets the boundary's) each cost a full turn for almost no coverage.
30
+ const MIN_SWATH_LENGTH_M = 1;
31
+ const ROW_LOOKAHEAD = 4; // rows further along the order tried when the next one's turn does not fit
32
+ // A row end also counts as escapable when one turn gets 2-3 turning radii
33
+ // out: in a mainland narrower than a U-turn, a middle row ends with only the
34
+ // headland ahead (no single turn gets 4R away), yet the vehicle can still
35
+ // turn onto a headland lap and leave. Laps keep the stricter default.
36
+ const ROW_EXIT_ESCAPE_RADII = [2, 3, 4, 5];
37
+ const CELL_DIRECT_CANDIDATES = 12; // best-ranked cell entries tried with a single Dubins turn
38
+ const CELL_TRANSIT_CANDIDATES = 4; // nearest cell entries compared when a transit is needed
39
+ const CIRCLE_RUNUP_RADII = 7.5; // route before a new lap stretch included in its circle check (a loop's length)
40
+ const LAP_CLEARANCE_MARGIN_M = 0.1; // keeps the outermost laps off the drive area's own edge
41
+ const LAP_ENTRY_STEP_M = 3; // spacing of candidate entry points along a lap
42
+ const LAP_ENTRY_MAX_CURVATURE_FACTOR = 0.8; // laps are entered only where they bend gentler than this × 1/R
43
+ const LAP_ENTRY_CLEARANCE_M = 3; // ...for at least this far either side of the entry point
44
+ const LAP_ENTRY_DENSIFY_M = 1;
45
+ const LAP_DIRECT_CANDIDATES = 40;
46
+ const LAP_TRANSIT_CANDIDATES = 4;
47
+ const MAX_ROW_UNWIND = 6; // rows that may be un-driven when no lap is reachable from where the rows ended
48
+ const MAX_ROW_UNWIND_TOTAL = 60; // ...and in all, per pass, so un-driving and re-driving cannot go on forever
49
+ const MAX_LAP_BACKTRACKS = 60; // undo budget when the lap router paints itself into a corner
50
+ const NEXT_RING_DIRECT_CANDIDATES = 12; // entries on the neighbouring ring tried first, with a single turn
51
+ // ...only within this × R: a lane change onto the next ring, not a hop across
52
+ // the field that leaves the vehicle in a pocket between obstacles.
53
+ const NEXT_RING_REACH_FACTOR = 1;
54
+ const MAX_LAP_TRANSIT_FAILURES = 3; // a lap entry transits failed to this often (from different places) is not tried again
55
+ const TRIM_STEP_M = 2; // how far an open lap end is pulled back per escape check
56
+ const RANKED_ENTRY_POOL = 400; // nearest entries (straight-line) re-ranked by smooth turn length
57
+ const VIA_LAP_ON_CANDIDATES = 12; // lap entries tried for hopping onto a lap in a via-lap transit
58
+ const VIA_LAP_REACH_M = 30; // targets tried from points along that lap within this distance
59
+ const VIA_LAP_MAX_TURN_RAD = Math.PI + 0.35; // same no-loop limit as the path planner's turns
60
+ const VIA_LAP_STRAIGHT_BREAK_M = 0.5; // a straight this long ends one continuous turn
61
+
62
+ const statusError = (message, status = 400) => Object.assign(new Error(message), { status });
63
+ const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
64
+
65
+ // Longest continuous same-direction turn along a polyline: a hop's arc, the
66
+ // lap's own bend and the next hop's arc chained together must not add up to
67
+ // a loop.
68
+ function longestPolylineTurn(points) {
69
+ let longest = 0;
70
+ let run = 0;
71
+ let straight = 0;
72
+ for (let i = 1; i + 1 < points.length; i += 1) {
73
+ const a = points[i - 1];
74
+ const b = points[i];
75
+ const c = points[i + 1];
76
+ const length = distance(b, c);
77
+ if (length < 1e-6 || distance(a, b) < 1e-6) continue;
78
+ let turn = Math.atan2(c[1] - b[1], c[0] - b[0]) - Math.atan2(b[1] - a[1], b[0] - a[0]);
79
+ turn = Math.atan2(Math.sin(turn), Math.cos(turn));
80
+ if (Math.abs(turn) < 2e-3) {
81
+ straight += length;
82
+ if (straight >= VIA_LAP_STRAIGHT_BREAK_M) run = 0;
83
+ continue;
84
+ }
85
+ straight = 0;
86
+ run = Math.sign(run) === Math.sign(turn) ? run + turn : turn;
87
+ longest = Math.max(longest, Math.abs(run));
88
+ }
89
+ return longest;
90
+ }
91
+
92
+ const rowStart = (row, dir) => (dir > 0 ? row.a : row.b);
93
+ const rowEnd = (row, dir) => (dir > 0 ? row.b : row.a);
94
+ const rowHeading = (row, dir) => (dir > 0 ? row.heading : row.heading + Math.PI);
95
+ const entryPose = (row, dir) => pose(...rowStart(row, dir), rowHeading(row, dir));
96
+ const exitPose = (row, dir) => pose(...rowEnd(row, dir), rowHeading(row, dir));
97
+
98
+ // Adds points every LAP_ENTRY_DENSIFY_M along segments longer than that.
99
+ function densifyPath(points, closed) {
100
+ const out = [];
101
+ const n = points.length;
102
+ for (let i = 0; i < n; i += 1) {
103
+ const a = points[i];
104
+ out.push(a);
105
+ if (!closed && i === n - 1) break;
106
+ const b = points[(i + 1) % n];
107
+ const count = Math.floor(distance(a, b) / LAP_ENTRY_DENSIFY_M);
108
+ for (let k = 1; k < count; k += 1) {
109
+ out.push([a[0] + ((b[0] - a[0]) * k) / count, a[1] + ((b[1] - a[1]) * k) / count]);
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+
115
+ // Orders candidate entries by the length of the shortest loop-free turn into
116
+ // them (ignoring obstacles — that is checked afterwards). Straight-line
117
+ // distance alone puts targets right beside the vehicle first, and those are
118
+ // exactly the ones only a loop can reach.
119
+ function rankBySmoothTurn(from, radius, entries) {
120
+ return entries
121
+ .map((entry) => ({ entry, d: Math.hypot(entry.target.x - from.x, entry.target.y - from.y) }))
122
+ .sort((a, b) => a.d - b.d)
123
+ .slice(0, RANKED_ENTRY_POOL)
124
+ .map(({ entry, d }) => {
125
+ const word = smoothWords(from, entry.target, radius)[0];
126
+ return { entry, cost: word ? word.length : Infinity, d };
127
+ })
128
+ .sort((a, b) => a.cost - b.cost || a.d - b.d)
129
+ .map(({ entry }) => entry);
130
+ }
131
+
132
+ function buildCells(mainland, direction, spacing, turningRadius, pass) {
133
+ const swathFrame = createSwathFrame(direction);
134
+ const columns = generateSwathColumns(mainland, swathFrame, spacing, Math.max(MIN_SWATH_LENGTH_M, turningRadius));
135
+ return decomposeIntoCells(columns).map(({ rows }) => ({
136
+ pass,
137
+ rows: rows.map(({ u, v0, v1 }) => ({
138
+ u,
139
+ v0,
140
+ a: swathFrame.fromUV([u, v0]),
141
+ b: swathFrame.fromUV([u, v1]),
142
+ heading: swathFrame.heading
143
+ })),
144
+ order: generateCustomOrder(rows.length, spacing, turningRadius)
145
+ }));
146
+ }
147
+
148
+ class CoverageRoute {
149
+ constructor(planner, roads = []) {
150
+ this.planner = planner;
151
+ this.points = [];
152
+ this.pose = null;
153
+ this.escapable = new Map(); // row -> { f, r }: exit pose can still turn away
154
+ this.roads = roads; // headland laps, also usable as smooth roads for transits
155
+ this.roadStops = null;
156
+ this.transitFailures = new Map(); // lap entry target -> failed transits to it
157
+ }
158
+
159
+ // Last-resort transit for targets in a cul-de-sac that a direct turn or
160
+ // the visibility-graph transit cannot reach at the right heading: hop onto
161
+ // a headland lap, follow it, and hop off onto the target. Laps are already
162
+ // smooth, drivable curves, entered and left only where they bend gently;
163
+ // the whole chain is still checked so hop, lap bend and hop never add up
164
+ // to a loop.
165
+ viaLapsNoLoop(targets) {
166
+ const best = this.viaLaps(targets);
167
+ return best && !this.loopsWith(best.connection) ? best : null;
168
+ }
169
+
170
+ viaLaps(targets) {
171
+ if (!this.roads.length || !targets.length) return null;
172
+ if (!this.roadStops) {
173
+ this.roadStops = new Map(); // pts -> entries along that lap direction, by index
174
+ this.roads.flatMap((lap) => this.lapEntries(lap)).forEach((stop) => {
175
+ if (!this.roadStops.has(stop.pts)) this.roadStops.set(stop.pts, []);
176
+ this.roadStops.get(stop.pts).push(stop);
177
+ });
178
+ }
179
+ const allStops = [...this.roadStops.values()].flat();
180
+ const ons = rankBySmoothTurn(this.pose, this.planner.radius, allStops).slice(0, VIA_LAP_ON_CANDIDATES);
181
+ let best = null;
182
+ for (const on of ons) {
183
+ const hopOn = this.planner.direct(this.pose, on.target);
184
+ if (!hopOn) continue;
185
+ const { pts, lap } = on;
186
+ const n = pts.length;
187
+ const ahead = (k) => (lap.closed ? (k - on.index + n) % n : k - on.index);
188
+ const stops = this.roadStops.get(pts)
189
+ .filter((stop) => ahead(stop.index) > 0)
190
+ .sort((a, b) => ahead(a.index) - ahead(b.index));
191
+ let along = 0;
192
+ let k = on.index;
193
+ for (const stop of stops) {
194
+ while (k !== stop.index) {
195
+ const next = (k + 1) % n;
196
+ along += distance(pts[k], pts[next]);
197
+ k = next;
198
+ }
199
+ const sofar = hopOn.length + along;
200
+ if (best && sofar >= best.connection.length) break;
201
+ let found = false;
202
+ for (const entry of targets) {
203
+ if (distance([stop.target.x, stop.target.y], [entry.target.x, entry.target.y]) > VIA_LAP_REACH_M) continue;
204
+ const hopOff = this.planner.direct(stop.target, entry.target);
205
+ if (!hopOff || (best && sofar + hopOff.length >= best.connection.length)) continue;
206
+ const road = [];
207
+ for (let j = on.index; j !== stop.index; j = (j + 1) % n) road.push(pts[(j + 1) % n]);
208
+ const points = [...hopOn.points, ...road.slice(0, -1), ...hopOff.points];
209
+ if (longestPolylineTurn(points) > VIA_LAP_MAX_TURN_RAD) continue;
210
+ best = { ...entry, connection: { points, length: sofar + hopOff.length } };
211
+ found = true;
212
+ }
213
+ if (found) break;
214
+ }
215
+ }
216
+ return best;
217
+ }
218
+
219
+ // True when the vehicle can still drive away smoothly after mowing `row`
220
+ // in direction `dir`. A row ending in a pocket too tight to turn in leaves
221
+ // the route stuck there, and every row after it becomes unreachable.
222
+ exitEscapable(row, dir) {
223
+ const key = dir > 0 ? 'f' : 'r';
224
+ let known = this.escapable.get(row);
225
+ if (!known) this.escapable.set(row, (known = {}));
226
+ if (!(key in known)) known[key] = this.planner.canEscape(exitPose(row, dir), ROW_EXIT_ESCAPE_RADII);
227
+ return known[key];
228
+ }
229
+
230
+ // Tries `connect` on each candidate entry and keeps the shortest result
231
+ // (or the first one, when stopAtFirst).
232
+ pick(candidates, connect, stopAtFirst) {
233
+ let best = null;
234
+ for (const entry of candidates) {
235
+ const connection = connect(this.pose, entry.target);
236
+ if (connection && this.loopsWith(connection)) continue;
237
+ if (connection && (!best || connection.length < best.connection.length)) {
238
+ best = { ...entry, connection };
239
+ if (stopAtFirst) break;
240
+ }
241
+ }
242
+ return best;
243
+ }
244
+
245
+ driveRow(row, dir, connection) {
246
+ (this.rowEnds = this.rowEnds || []).push({ pointsLength: this.points.length, pose: this.pose, row });
247
+ if (connection) this.points.push(...connection.points.slice(1));
248
+ else this.points.push(rowStart(row, dir));
249
+ this.points.push(rowEnd(row, dir));
250
+ this.pose = exitPose(row, dir);
251
+ }
252
+
253
+ // Cheapest valid connection into `row`, either direction (the U-turn
254
+ // direction wins on length whenever it fits). Within a cell no obstacle
255
+ // lies between rows, so the fallback is only the two-hop turnaround — the
256
+ // full obstacle transit is left to the cell-level router.
257
+ connectRow(row, allowTurnaround) {
258
+ const tryWith = (connect) => {
259
+ let best = null;
260
+ for (const dir of [1, -1]) {
261
+ if (!this.exitEscapable(row, dir)) continue;
262
+ const connection = connect(this.pose, entryPose(row, dir));
263
+ if (connection && this.loopsWith(connection)) continue;
264
+ if (connection && (!best || connection.length < best.connection.length)) best = { dir, connection };
265
+ }
266
+ return best;
267
+ };
268
+ return tryWith((a, b) => this.planner.direct(a, b))
269
+ || (allowTurnaround ? tryWith((a, b) => this.planner.twoHop(a, b)) : null);
270
+ }
271
+
272
+ // Drives one cell along its leapfrog sequence. A row whose turn does not
273
+ // fit is passed over for the next few in order and retried afterwards;
274
+ // rows still unreachable from inside the cell are returned as orphans for
275
+ // the cell-level router to reach from somewhere else.
276
+ runCell(cell, entry) {
277
+ const pending = entry.sequence.map((i) => cell.rows[i]);
278
+ this.driveRow(pending.shift(), entry.dir, entry.connection);
279
+ const orphans = [];
280
+ while (pending.length) {
281
+ let taken = -1;
282
+ let best = null;
283
+ for (let i = 0; i < Math.min(ROW_LOOKAHEAD, pending.length); i += 1) {
284
+ best = this.connectRow(pending[i], false);
285
+ if (best) {
286
+ taken = i;
287
+ break;
288
+ }
289
+ }
290
+ if (taken < 0) {
291
+ best = this.connectRow(pending[0], true);
292
+ if (best) taken = 0;
293
+ }
294
+ if (taken < 0) {
295
+ orphans.push(pending.shift());
296
+ continue;
297
+ }
298
+ const [row] = pending.splice(taken, 1);
299
+ this.driveRow(row, best.dir, best.connection);
300
+ }
301
+ return orphans;
302
+ }
303
+
304
+ // Each cell can be entered from either end of its sweep, on either row
305
+ // direction. Picks the cheapest entry a single smooth turn reaches; falls
306
+ // back to transiting when none does.
307
+ chooseNextCell(pool) {
308
+ const here = [this.pose.x, this.pose.y];
309
+ const entries = pool.flatMap((cell) => [false, true].flatMap((mirrored) => {
310
+ const n = cell.rows.length;
311
+ const sequence = mirrored ? cell.order.map((i) => n - 1 - i) : cell.order;
312
+ const first = cell.rows[sequence[0]];
313
+ return [1, -1].filter((dir) => this.exitEscapable(first, dir))
314
+ .map((dir) => ({ cell, sequence, dir, target: entryPose(first, dir) }));
315
+ }));
316
+ const ranked = rankBySmoothTurn(this.pose, this.planner.radius, entries);
317
+ entries.sort((a, b) => distance(here, [a.target.x, a.target.y]) - distance(here, [b.target.x, b.target.y]));
318
+ return this.pick(ranked.slice(0, CELL_DIRECT_CANDIDATES), (a, b) => this.planner.direct(a, b), false)
319
+ || this.pick(entries.slice(0, CELL_TRANSIT_CANDIDATES), (a, b) => this.planner.transit(a, b), false)
320
+ || this.pick(entries.slice(CELL_TRANSIT_CANDIDATES), (a, b) => this.planner.transit(a, b), true)
321
+ || this.viaLapsNoLoop(entries);
322
+ }
323
+
324
+ // Covers every cell of one pass. Returns the number of rows that could
325
+ // not be reached at all.
326
+ // Covers every cell of one pass. Returns the number of rows that could
327
+ // not be reached at all.
328
+ coverPass(cells) {
329
+ const pool = cells.filter((cell) => cell.rows.length > 0);
330
+ if (pool.length === 0) return 0;
331
+ let unwound = 0;
332
+
333
+ if (!this.pose) {
334
+ // Start in the biggest cell, on its leftmost row (relative to the
335
+ // reference direction), driving along the reference line. Starting in
336
+ // a small side cell cut off by obstacles can strand the whole route
337
+ // there; from the main cell, side cells are reached afterwards or at
338
+ // worst skipped on their own. If the first row ends in a pocket the
339
+ // vehicle cannot turn out of, take the next start (other cell end,
340
+ // other direction, next cell) whose first row can be left again.
341
+ const sorted = [...pool].sort((a, b) => b.rows.length - a.rows.length
342
+ || a.rows[0].u - b.rows[0].u || a.rows[0].v0 - b.rows[0].v0);
343
+ const starts = sorted.flatMap((cell) => [false, true].flatMap((mirrored) => [1, -1].map((dir) => {
344
+ const n = cell.rows.length;
345
+ return { cell, dir, sequence: mirrored ? cell.order.map((i) => n - 1 - i) : cell.order };
346
+ })));
347
+ const start = starts.find(({ cell, sequence, dir }) => this.exitEscapable(cell.rows[sequence[0]], dir)) || starts[0];
348
+ pool.splice(pool.indexOf(start.cell), 1);
349
+ this.runCell(start.cell, { sequence: start.sequence, dir: start.dir, connection: null })
350
+ .forEach((row) => pool.push({ pass: start.cell.pass, rows: [row], order: [0] }));
351
+ }
352
+
353
+ // Dead ends: when nothing left is reachable from where the last row
354
+ // ended (a pocket), un-drive rows and try from an earlier row end. The
355
+ // un-driven rows go back into the pool but stay held — not picked again
356
+ // — until the route gets past that dead end with fewer rows left;
357
+ // otherwise the cheapest pick from the earlier row end is the same rows
358
+ // again, in the same order, straight back into the pocket. If un-driving
359
+ // never gets further, the dead end with the fewest rows left is kept.
360
+ const rowsLeft = () => pool.reduce((sum, cell) => sum + cell.rows.length, 0);
361
+ const held = new Set();
362
+ let unwoundHere = 0;
363
+ let best = null; // dead end with the fewest rows left: route state to fall back to
364
+ while (pool.length) {
365
+ const free = pool.filter((cell) => !held.has(cell));
366
+ const next = this.chooseNextCell(free.length ? free : pool);
367
+ if (!next) {
368
+ const left = rowsLeft();
369
+ if (unwoundHere === 0 && (!best || left < best.left)) {
370
+ best = { left, points: this.points.slice(), rowEnds: (this.rowEnds || []).slice(), pose: this.pose, pool: pool.slice() };
371
+ }
372
+ if (this.rowEnds && this.rowEnds.length > 1 && unwoundHere < MAX_ROW_UNWIND && unwound < MAX_ROW_UNWIND_TOTAL) {
373
+ const last = this.rowEnds.pop();
374
+ this.points.length = last.pointsLength;
375
+ this.pose = last.pose;
376
+ if (last.row) {
377
+ const cell = { rows: [last.row], order: [0] };
378
+ pool.push(cell);
379
+ held.add(cell);
380
+ }
381
+ unwound += 1;
382
+ unwoundHere += 1;
383
+ continue;
384
+ }
385
+ // Nothing left is reachable, from here or from earlier row ends.
386
+ if (best && best.left <= left) {
387
+ this.points = best.points;
388
+ this.rowEnds = best.rowEnds;
389
+ this.pose = best.pose;
390
+ return best.left;
391
+ }
392
+ return left;
393
+ }
394
+ unwoundHere = 0;
395
+ pool.splice(pool.indexOf(next.cell), 1);
396
+ this.runCell(next.cell, next)
397
+ .forEach((row) => pool.push({ pass: next.cell.pass, rows: [row], order: [0] }));
398
+ if (best && rowsLeft() < best.left) {
399
+ held.clear();
400
+ best = null;
401
+ }
402
+ }
403
+ return 0;
404
+ }
405
+
406
+ // Entry options along a lap (sampled), in both driving directions. A
407
+ // closed lap is driven fully round from its entry; an open piece from its
408
+ // entry to its end — the part behind the entry goes back in the pool.
409
+ lapEntries(lap) {
410
+ const out = [];
411
+ [false, true].forEach((reversed) => {
412
+ // Densified copy, so long straight sides (stored as just their two end
413
+ // points) get candidate entry points along them.
414
+ const pts = densifyPath(reversed ? [...lap.points].reverse() : lap.points, lap.closed);
415
+ const n = pts.length;
416
+ const headingAt = (k) => {
417
+ const a = pts[k];
418
+ const b = lap.closed ? pts[(k + 1) % n] : pts[Math.min(k + 1, n - 1)];
419
+ return Math.atan2(b[1] - a[1], b[0] - a[0]);
420
+ };
421
+ // Only where the lap bends gently over LAP_ENTRY_CLEARANCE_M either
422
+ // side (straights, wide orbits round an obstacle): entering — and, for
423
+ // a closed lap, leaving — at a tight corner manoeuvre would chain that
424
+ // arc with the connecting turn into a semicircle. Averaged over the
425
+ // window, so a wide orbit built from short straights and corner arcs
426
+ // still counts as the wide curve it is.
427
+ const pointAlong = (k, step) => {
428
+ let along = 0;
429
+ let j = k;
430
+ while (along < LAP_ENTRY_CLEARANCE_M) {
431
+ const next = j + step;
432
+ if (!lap.closed && (next < 0 || next >= n)) return null;
433
+ along += distance(pts[(j + n) % n], pts[(next + n) % n]);
434
+ j = next;
435
+ if (Math.abs(j - k) >= n) return null;
436
+ }
437
+ return { index: (j + n) % n, along };
438
+ };
439
+ const clearAround = (k) => {
440
+ if (!lap.closed && (k === 0 || k === n - 1)) return true;
441
+ const back = pointAlong(k, -1);
442
+ const ahead = pointAlong(k, 1);
443
+ if (!back || !ahead) return !lap.closed;
444
+ const hBack = Math.atan2(pts[(back.index + 1) % n][1] - pts[back.index][1], pts[(back.index + 1) % n][0] - pts[back.index][0]);
445
+ const hAhead = Math.atan2(pts[ahead.index][1] - pts[(ahead.index - 1 + n) % n][1], pts[ahead.index][0] - pts[(ahead.index - 1 + n) % n][0]);
446
+ let turn = hAhead - hBack;
447
+ turn = Math.abs(Math.atan2(Math.sin(turn), Math.cos(turn)));
448
+ return turn / (back.along + ahead.along) < LAP_ENTRY_MAX_CURVATURE_FACTOR / this.planner.radius;
449
+ };
450
+ let travelled = Infinity;
451
+ for (let k = 0; k < (lap.closed ? n : n - 1); k += 1) {
452
+ if (k > 0) travelled += distance(pts[k - 1], pts[k]);
453
+ if (travelled >= LAP_ENTRY_STEP_M && clearAround(k)) {
454
+ out.push({ lap, pts, index: k, target: pose(pts[k][0], pts[k][1], headingAt(k)) });
455
+ travelled = 0;
456
+ }
457
+ }
458
+ });
459
+ return out;
460
+ }
461
+
462
+ // Whether driving `connection` next would close a tight loop together with
463
+ // the end of the route so far (each connection is loop-free on its own,
464
+ // but a turn into it can complete one).
465
+ loopsWith(connection) {
466
+ if (!this.points.length) return false;
467
+ const runUp = CIRCLE_RUNUP_RADII * this.planner.radius;
468
+ let start = this.points.length - 1;
469
+ let along = 0;
470
+ while (start > 0 && along < runUp) {
471
+ along += distance(this.points[start - 1], this.points[start]);
472
+ start -= 1;
473
+ }
474
+ return hasCircle([...this.points.slice(start), ...connection.points.slice(1)], this.planner.radius, this.planner.onFreeGround);
475
+ }
476
+
477
+ // Whether the points added since `from` (with up to CIRCLE_RUNUP_RADII × R
478
+ // of the route before them) drive round in a full circle.
479
+ closesCircle(from) {
480
+ const runUp = CIRCLE_RUNUP_RADII * this.planner.radius;
481
+ let start = from;
482
+ let along = 0;
483
+ while (start > 0 && along < runUp) {
484
+ along += distance(this.points[start - 1], this.points[start]);
485
+ start -= 1;
486
+ }
487
+ return hasCircle(this.points.slice(start), this.planner.radius, this.planner.onFreeGround);
488
+ }
489
+
490
+ // Drives a lap from the chosen entry. For an open piece entered part way
491
+ // along, returns the part behind the entry as a new open piece (or null).
492
+ driveLap({ lap, pts, index, connection }) {
493
+ const sequence = lap.closed ? [...pts.slice(index), ...pts.slice(0, index + 1)] : pts.slice(index);
494
+ const behind = lap.closed ? [] : pts.slice(0, index + 1);
495
+ if (connection) this.points.push(...connection.points.slice(1));
496
+ else this.points.push(sequence[0]);
497
+ this.points.push(...sequence.slice(1));
498
+ const a = sequence[sequence.length - 2];
499
+ const b = sequence[sequence.length - 1];
500
+ this.pose = pose(b[0], b[1], Math.atan2(b[1] - a[1], b[0] - a[0]));
501
+ const behindLength = behind.reduce((sum, p, i) => (i ? sum + distance(behind[i - 1], p) : 0), 0);
502
+ return behindLength >= this.planner.radius ? { closed: false, points: behind, depth: lap.depth } : null;
503
+ }
504
+
505
+ // Shortens an open piece from its end until the vehicle can still drive
506
+ // away smoothly from there; null when nothing of it is escapable.
507
+ trimToEscapableEnd(points) {
508
+ const pts = points.slice();
509
+ while (pts.length >= 2) {
510
+ const a = pts[pts.length - 2];
511
+ const b = pts[pts.length - 1];
512
+ if (this.planner.canEscape(pose(b[0], b[1], Math.atan2(b[1] - a[1], b[0] - a[0])))) return pts;
513
+ let removed = 0;
514
+ while (pts.length >= 2 && removed < TRIM_STEP_M) {
515
+ removed += distance(pts[pts.length - 2], pts[pts.length - 1]);
516
+ pts.pop();
517
+ }
518
+ }
519
+ return null;
520
+ }
521
+
522
+ // Open pieces end where a ring got too tight to follow — often a pocket
523
+ // the vehicle could drive into but not out of. Trim both ends back to
524
+ // where it can still leave smoothly.
525
+ escapablePiece(lap) {
526
+ if (lap.closed) return lap;
527
+ const forward = this.trimToEscapableEnd(lap.points);
528
+ const both = forward && this.trimToEscapableEnd([...forward].reverse());
529
+ if (!both) return null;
530
+ const length = both.reduce((sum, p, i) => (i ? sum + distance(both[i - 1], p) : 0), 0);
531
+ return length >= this.planner.radius ? { closed: false, points: both.reverse(), depth: lap.depth } : null;
532
+ }
533
+
534
+ // Mows the headland laps after the rows. From the end of each lap the
535
+ // cheapest reachable entry is usually the neighbouring lap one coverage
536
+ // width away, reached with a short lane-change S-curve. Returns the number
537
+ // of laps (or lap pieces) that could not be reached.
538
+ coverLaps(laps) {
539
+ const pool = laps.map((lap) => this.escapablePiece(lap)).filter(Boolean);
540
+ const dropped = laps.length - pool.length;
541
+ if (pool.length === 0) return dropped;
542
+ if (!this.pose) {
543
+ const first = pool.shift();
544
+ const remainder = this.driveLap({ lap: first, pts: first.points, index: 0, connection: null });
545
+ if (remainder) pool.push(remainder);
546
+ this.lapDepth = first.depth;
547
+ }
548
+ const entriesOf = new Map(pool.map((lap) => [lap, this.lapEntries(lap)]));
549
+
550
+ // Greedy, with bounded backtracking: when nothing left is reachable from
551
+ // where the last lap ended (a corridor too narrow to turn in, say), undo
552
+ // the last choices and try a different lap or entry instead of giving up
553
+ // on everything still in the pool.
554
+ const ids = new WeakMap(); // WeakMap has no size, so ids come from a counter
555
+ let nextId = 1;
556
+ const idOf = (obj) => {
557
+ if (!ids.has(obj)) ids.set(obj, nextId++);
558
+ return ids.get(obj);
559
+ };
560
+ const history = [];
561
+ const banned = new Set();
562
+ const stateKey = () => history.map((step) => step.key).join('>');
563
+ const entryKey = (entry) => `${idOf(entry.pts)}:${entry.index}`;
564
+ let backtracks = 0;
565
+ let rowsUnwound = 0;
566
+
567
+ while (pool.length) {
568
+ const prefix = stateKey();
569
+ const allowed = (entry) => !banned.has(`${prefix}|${entryKey(entry)}`);
570
+ const next = this.chooseNextLap(pool, entriesOf, allowed);
571
+ if (!next && !history.length && this.rowEnds && this.rowEnds.length > 1 && rowsUnwound < MAX_ROW_UNWIND) {
572
+ // The rows ended where no lap can be reached (a row end in a pocket):
573
+ // un-drive the last row and start the laps from the row end before
574
+ // it — a row or two left out instead of every lap.
575
+ const last = this.rowEnds.pop();
576
+ this.points.length = last.pointsLength;
577
+ this.pose = last.pose;
578
+ rowsUnwound += 1;
579
+ continue;
580
+ }
581
+ if (!next) {
582
+ if (!history.length || backtracks >= MAX_LAP_BACKTRACKS) return dropped + pool.length;
583
+ backtracks += 1;
584
+ const step = history.pop();
585
+ this.points.length = step.pointsLength;
586
+ this.pose = step.pose;
587
+ this.lapDepth = step.depth;
588
+ if (step.remainder) {
589
+ pool.splice(pool.indexOf(step.remainder), 1);
590
+ entriesOf.delete(step.remainder);
591
+ }
592
+ pool.push(step.lap);
593
+ banned.add(`${stateKey()}|${step.key}`);
594
+ continue;
595
+ }
596
+ const step = { key: entryKey(next), lap: next.lap, pointsLength: this.points.length, pose: this.pose, depth: this.lapDepth, remainder: null };
597
+ pool.splice(pool.indexOf(next.lap), 1);
598
+ const remainder = this.driveLap(next);
599
+ // Every connection is loop-free on its own, but a turn-heavy transit,
600
+ // a short lap piece and the turn before it can still close a full
601
+ // circle together. Check the stretch just driven (plus the run-up to
602
+ // it); if it loops, undo this choice and ban it like a dead end.
603
+ if (this.closesCircle(step.pointsLength)) {
604
+ this.points.length = step.pointsLength;
605
+ this.pose = step.pose;
606
+ pool.push(next.lap);
607
+ banned.add(`${prefix}|${step.key}`);
608
+ continue;
609
+ }
610
+ if (remainder) {
611
+ pool.push(remainder);
612
+ entriesOf.set(remainder, this.lapEntries(remainder));
613
+ step.remainder = remainder;
614
+ }
615
+ this.lapDepth = next.lap.depth;
616
+ history.push(step);
617
+ }
618
+ return dropped;
619
+ }
620
+
621
+ // Best reachable lap entry from the current pose, among `allowed` ones.
622
+ // The ring nearest in depth to the one just mowed comes first (the deeper
623
+ // one on a tie, and the innermost ring, bordering the rows, when starting),
624
+ // so the laps are mowed ring by ring, each hop a short lane change of one
625
+ // coverage width, instead of hopping across rings the nearest turn happens
626
+ // to reach. Otherwise the cheapest smooth turn first, then transits.
627
+ chooseNextLap(pool, entriesOf, allowed) {
628
+ const depths = [...new Set(pool.map((lap) => lap.depth))];
629
+ const from = this.lapDepth == null ? Infinity : this.lapDepth;
630
+ const nextDepth = depths.reduce((best, d) => {
631
+ const gap = Math.abs(d - from);
632
+ const bestGap = Math.abs(best - from);
633
+ return gap < bestGap || (gap === bestGap && d > best) ? d : best;
634
+ });
635
+ const reach = NEXT_RING_REACH_FACTOR * this.planner.radius;
636
+ const nextRing = pool.filter((lap) => lap.depth === nextDepth).flatMap((lap) => entriesOf.get(lap)).filter(allowed)
637
+ .filter((entry) => Math.hypot(entry.target.x - this.pose.x, entry.target.y - this.pose.y) <= reach);
638
+ const onNextRing = this.pick(
639
+ rankBySmoothTurn(this.pose, this.planner.radius, nextRing).slice(0, NEXT_RING_DIRECT_CANDIDATES),
640
+ (a, b) => this.planner.direct(a, b),
641
+ false
642
+ );
643
+ if (onNextRing) return onNextRing;
644
+
645
+ const { x, y } = this.pose;
646
+ const entries = pool
647
+ .flatMap((lap) => entriesOf.get(lap))
648
+ .filter(allowed)
649
+ .map((entry) => ({ entry, d: Math.hypot(entry.target.x - x, entry.target.y - y) }))
650
+ .sort((a, b) => a.d - b.d)
651
+ .map(({ entry }) => entry);
652
+ const ranked = rankBySmoothTurn(this.pose, this.planner.radius, entries);
653
+ // Transit fallback over the rest tries just one (nearest) entry per lap.
654
+ const seen = new Set();
655
+ const onePerLap = entries.slice(LAP_TRANSIT_CANDIDATES).filter((e) => !seen.has(e.lap) && seen.add(e.lap));
656
+ return this.pick(ranked.slice(0, LAP_DIRECT_CANDIDATES), (a, b) => this.planner.direct(a, b), false)
657
+ || this.pick(entries.slice(0, LAP_TRANSIT_CANDIDATES).filter((e) => this.transitWorthTrying(e)), (a, b) => this.lapTransit(a, b), false)
658
+ || this.pick(onePerLap.filter((e) => this.transitWorthTrying(e)), (a, b) => this.lapTransit(a, b), true)
659
+ || this.viaLapsNoLoop(entries);
660
+ }
661
+
662
+ // Lap entries no transit reaches (a ring round a small obstacle in a
663
+ // pocket, say) would otherwise be retried from every new position, each a
664
+ // full visibility-graph search that fails — most of the planning time with
665
+ // many obstacles. After a few failures from different places, give up on
666
+ // them; they stay reachable by direct turns and via other laps.
667
+ transitWorthTrying(entry) {
668
+ return (this.transitFailures.get(entry.target) || 0) < MAX_LAP_TRANSIT_FAILURES;
669
+ }
670
+
671
+ lapTransit(from, target) {
672
+ const connection = this.planner.transit(from, target);
673
+ if (!connection) this.transitFailures.set(target, (this.transitFailures.get(target) || 0) + 1);
674
+ return connection;
675
+ }
676
+ }
677
+
678
+ function planCoverage({ polygonCoords, obstacleRings, referenceLineCoords, headlandWidth, spacing, turningRadius, crissCross }) {
679
+ if (!Number.isFinite(turningRadius) || turningRadius <= 0) {
680
+ throw statusError("A positive turning radius is required to generate the mower path.");
681
+ }
682
+ if (!Number.isFinite(spacing) || spacing <= 0) {
683
+ throw statusError("Spacing must be a positive number of metres.");
684
+ }
685
+
686
+ const frame = createLocalFrame(referenceLineCoords[0]);
687
+ const refStart = frame.toLocal(referenceLineCoords[0]);
688
+ const refEnd = frame.toLocal(referenceLineCoords[referenceLineCoords.length - 1]);
689
+ const refLength = distance(refStart, refEnd);
690
+ if (!(refLength > 1e-6)) throw statusError("The reference line needs two distinct end points.");
691
+ const direction = [(refEnd[0] - refStart[0]) / refLength, (refEnd[1] - refStart[1]) / refLength];
692
+
693
+ const mainlandFeature = generateMainland(polygonCoords, obstacleRings, headlandWidth);
694
+ const driveFeature = fieldArea(
695
+ polygonCoords,
696
+ obstacleRings,
697
+ Math.min(headlandWidth, CONNECTOR_BOUNDARY_CLEARANCE_M),
698
+ Math.min(headlandWidth, CONNECTOR_OBSTACLE_CLEARANCE_M)
699
+ );
700
+ const mainland = areaFromGeoJSON(mainlandFeature, frame.toLocal);
701
+ const driveArea = areaFromGeoJSON(driveFeature, frame.toLocal);
702
+ const planner = new PathPlanner({ driveArea, driveFeature, toLocal: frame.toLocal, radius: turningRadius });
703
+
704
+ // Criss-cross: the full primary grid first, then a second grid at 90°.
705
+ const directions = crissCross ? [direction, [direction[1], -direction[0]]] : [direction];
706
+ const passes = directions.map((dir, pass) => buildCells(mainland, dir, spacing, turningRadius, pass));
707
+
708
+ // Headland laps fill the band the rows leave for turning, so everything
709
+ // but the obstacles (and their clearance) is mowed.
710
+ const laps = generateHeadlandLaps({
711
+ polygonCoords,
712
+ obstacleRings,
713
+ headlandWidth,
714
+ spacing,
715
+ boundaryStart: Math.max(spacing / 2, CONNECTOR_BOUNDARY_CLEARANCE_M + LAP_CLEARANCE_MARGIN_M),
716
+ obstacleStart: Math.max(spacing / 2, CONNECTOR_OBSTACLE_CLEARANCE_M + LAP_CLEARANCE_MARGIN_M),
717
+ toLocal: frame.toLocal,
718
+ turningRadius,
719
+ configuredRadius: turningRadius,
720
+ driveArea
721
+ });
722
+
723
+ const route = new CoverageRoute(planner, laps);
724
+ let skipped = 0;
725
+ passes.forEach((cells) => {
726
+ skipped += route.coverPass(cells);
727
+ });
728
+ const skippedLaps = route.coverLaps(laps);
729
+
730
+ return {
731
+ coordinates: route.points.map(frame.toLonLat),
732
+ driveFeature,
733
+ rowCounts: passes.map((cells) => cells.reduce((sum, cell) => sum + cell.rows.length, 0)),
734
+ cellCount: passes.reduce((sum, cells) => sum + cells.length, 0),
735
+ skippedRows: skipped,
736
+ lapCount: laps.length,
737
+ skippedLaps
738
+ };
739
+ }
740
+
741
+ module.exports = { planCoverage, CONNECTOR_BOUNDARY_CLEARANCE_M, CONNECTOR_OBSTACLE_CLEARANCE_M };