@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,576 @@
1
+ const turf = require('@turf/turf');
2
+ const { sampleDubins } = require('./mowerLoopFallback');
3
+ const { smoothWords, chainIsSmooth } = require('./pathPlanner');
4
+ const { areaFromGeoJSON } = require('./geometry');
5
+ const { fieldArea } = require('./headland');
6
+
7
+ // Port of Fields2Cover's hg::ConstHL::generateHeadlandSwaths: the headland
8
+ // band the rows leave for turning (around the boundary and around every
9
+ // obstacle) is mowed as laps, one coverage width apart, so only the
10
+ // obstacles themselves stay uncut.
11
+ //
12
+ // A lap follows an offset ring, but a ring can bend tighter than the vehicle
13
+ // can turn: sharp field corners, inward notches, and the corners of any
14
+ // obstacle closer than one turning radius. Those stretches are replaced by a
15
+ // validated, loop-free Dubins manoeuvre (a rounded corner). A stretch with no
16
+ // such manoeuvre cuts the lap there; the pieces are then driven as open
17
+ // paths.
18
+
19
+ const TIGHT_CURVATURE_FACTOR = 1; // ring vertices bending tighter than 1/R need a manoeuvre
20
+ // ...and so do stretches this long bending tighter than 1/R overall: a ring
21
+ // sampled at ~0.3-0.5 m can pass the per-vertex test at every vertex and
22
+ // still bend at ~0.9 R over a few metres (bonham_cell_1: 5.4 m on 6 m).
23
+ const TIGHT_SPAN_M = 2;
24
+ const MAX_PLAIN_VERTEX_TURN_RAD = 0.2; // ~11.5°: any sharper polyline kink gets a manoeuvre too, however long its sides
25
+ const CHECK_STEP_M = 0.25;
26
+ const OUTPUT_STEP_M = 0.1;
27
+ const RING_DENSIFY_STEP_M = 1; // so a long straight side has easy vertices between its corners
28
+ const RING_SMOOTHING_PASSES = 3;
29
+ const RING_SAMPLE_STEP_M = 0.5;
30
+ const MAX_MANOEUVRE_CHECKS = 80;
31
+ const MERGE_ATTEMPTS = 5;
32
+ const WIDE_CORNER_OFFSETS = [0.25, 0.5, 0.75, 1, 1.5]; // apex pulled out by this × R from the corner's middle
33
+ const MAX_LAP_ARC_RAD = (150 * Math.PI) / 180; // same no-semicircle limit as the path planner
34
+ const STRAIGHT_BREAK_FACTOR = 0.5; // a straight this × R separates two arcs (the flat-U-turn straight)
35
+ const OPENING_STEPS = 32; // buffer arc steps per quarter circle, so rounded corners stay smooth polylines
36
+
37
+ const headingOf = (a, b) => Math.atan2(b[1] - a[1], b[0] - a[0]);
38
+ const wrapAngle = (a) => Math.atan2(Math.sin(a), Math.cos(a));
39
+
40
+ function cleanRing(ring) {
41
+ const out = [];
42
+ ring.forEach((p) => {
43
+ const last = out[out.length - 1];
44
+ if (!last || Math.hypot(p[0] - last[0], p[1] - last[1]) > 1e-3) out.push(p);
45
+ });
46
+ while (out.length > 1 && Math.hypot(out[0][0] - out[out.length - 1][0], out[0][1] - out[out.length - 1][1]) <= 1e-3) out.pop();
47
+ const dense = [];
48
+ out.forEach((a, i) => {
49
+ const b = out[(i + 1) % out.length];
50
+ const count = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / RING_DENSIFY_STEP_M));
51
+ for (let k = 0; k < count; k += 1) dense.push([a[0] + ((b[0] - a[0]) * k) / count, a[1] + ((b[1] - a[1]) * k) / count]);
52
+ });
53
+ return dense;
54
+ }
55
+
56
+ // Morphological opening (shrink by R, grow back by R): rounds every convex
57
+ // corner of the offset area to at least the turning radius, so the lap can
58
+ // follow its ring there instead of swapping the corner for a manoeuvre that
59
+ // leaves the ring and runs over the neighbouring laps. Openings of nested
60
+ // areas stay nested, so rounded laps never cross each other. An opening that
61
+ // changes the area's shape — a corridor narrower than 2R between an obstacle
62
+ // and the boundary pinched shut, an area too thin to open at all — would
63
+ // drop those laps, so the plain area is kept there instead.
64
+ const ringCounts = (area) => {
65
+ const { type, coordinates } = area.geometry;
66
+ const polygons = type === "MultiPolygon" ? coordinates : [coordinates];
67
+ return `${polygons.length}:${polygons.reduce((sum, rings) => sum + rings.length, 0)}`;
68
+ };
69
+ function openArea(area, radius) {
70
+ try {
71
+ const shrunk = turf.buffer(area, -radius / 1000, { units: "kilometers", steps: OPENING_STEPS });
72
+ const opened = shrunk && turf.buffer(shrunk, radius / 1000, { units: "kilometers", steps: OPENING_STEPS });
73
+ return opened && ringCounts(opened) === ringCounts(area) ? opened : area;
74
+ } catch {
75
+ return area;
76
+ }
77
+ }
78
+
79
+ // Offset rings for every lap, one coverage width apart. Boundary laps start
80
+ // half a coverage width in from the boundary; obstacle laps start at the
81
+ // obstacle clearance. Each lap's rings are the outer ring and hole rings of
82
+ // that offset area, so an obstacle close to the boundary merges into it
83
+ // naturally.
84
+ function generateLapRings({ polygonCoords, obstacleRings, headlandWidth, spacing, boundaryStart, obstacleStart, toLocal, configuredRadius }) {
85
+ const rings = [];
86
+ const count = Math.ceil(headlandWidth / spacing - 1e-9);
87
+ for (let j = 0; j < count; j += 1) {
88
+ let area;
89
+ try {
90
+ area = fieldArea(polygonCoords, obstacleRings, boundaryStart + j * spacing, obstacleStart + j * spacing);
91
+ } catch {
92
+ break; // offset has consumed the whole field
93
+ }
94
+ // Opening only removes slivers: a strip narrower than a turn is still
95
+ // mowed with passes along it (the lap splitter cuts off the hairpin ends
96
+ // the vehicle cannot turn), so it must not be deleted.
97
+ areaFromGeoJSON(openArea(area, LAP_OPENING_M), toLocal).polygons
98
+ .filter((polygon) => !isSmallEmptyIsland(polygon, configuredRadius))
99
+ .forEach((polygon) => polygon.forEach((ring) => rings.push({ depth: j, points: cleanRing(ring) })));
100
+ }
101
+ return rings.filter((ring) => ring.points.length >= 3);
102
+ }
103
+
104
+ // As the offset grows, a pocket of free ground between obstacles shrinks into
105
+ // a small island with nothing inside it (no hole = no obstacle to go round).
106
+ // Its lap is a closed ring only a few turning radii across, which the vehicle
107
+ // drives as a circle, so such islands get no laps.
108
+ const MIN_EMPTY_ISLAND_SPAN_RADII = 4;
109
+ const LAP_OPENING_M = 0.5;
110
+ function isSmallEmptyIsland(polygon, turningRadius) {
111
+ if (polygon.length !== 1) return false; // has holes: laps go round an obstacle
112
+ const ring = polygon[0];
113
+ const step = Math.max(1, Math.floor(ring.length / 200));
114
+ let span = 0;
115
+ for (let a = 0; a < ring.length; a += step) {
116
+ for (let b = a + step; b < ring.length; b += step) {
117
+ span = Math.max(span, Math.hypot(ring[a][0] - ring[b][0], ring[a][1] - ring[b][1]));
118
+ }
119
+ }
120
+ return span < MIN_EMPTY_ISLAND_SPAN_RADII * turningRadius;
121
+ }
122
+
123
+ // Closed polyline with arc-length lookup.
124
+ function ringGeometry(points) {
125
+ const n = points.length;
126
+ const starts = new Array(n);
127
+ let total = 0;
128
+ for (let i = 0; i < n; i += 1) {
129
+ starts[i] = total;
130
+ const a = points[i];
131
+ const b = points[(i + 1) % n];
132
+ total += Math.hypot(b[0] - a[0], b[1] - a[1]);
133
+ }
134
+ const segmentAt = (s) => {
135
+ let lo = 0;
136
+ let hi = n - 1;
137
+ while (lo < hi) {
138
+ const mid = (lo + hi + 1) >> 1;
139
+ if (starts[mid] <= s) lo = mid;
140
+ else hi = mid - 1;
141
+ }
142
+ return lo;
143
+ };
144
+ return {
145
+ n,
146
+ total,
147
+ starts,
148
+ // Point and travel heading at arc length s (wrapped onto the ring).
149
+ at(s) {
150
+ const t = ((s % total) + total) % total;
151
+ const i = segmentAt(t);
152
+ const a = points[i];
153
+ const b = points[(i + 1) % n];
154
+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
155
+ const f = (t - starts[i]) / len;
156
+ return { p: [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f], th: headingOf(a, b) };
157
+ },
158
+ // Ring vertices strictly between arc lengths from < to (to may exceed total).
159
+ verticesBetween(from, to) {
160
+ const out = [];
161
+ for (let lap = 0; lap <= 1; lap += 1) {
162
+ for (let i = 0; i < n; i += 1) {
163
+ const s = starts[i] + lap * total;
164
+ if (s > from + 1e-6 && s < to - 1e-6) out.push(points[i]);
165
+ }
166
+ }
167
+ return out;
168
+ }
169
+ };
170
+ }
171
+
172
+ // Removes the in-line points densification added on straight sides (Dubins
173
+ // samples on arcs are kept — they are never collinear).
174
+ function dropCollinear(points, closed) {
175
+ const n = points.length;
176
+ if (n < 3) return points;
177
+ return points.filter((v, i) => {
178
+ if (!closed && (i === 0 || i === n - 1)) return true;
179
+ const p = points[(i - 1 + n) % n];
180
+ const q = points[(i + 1) % n];
181
+ const cross = (v[0] - p[0]) * (q[1] - v[1]) - (v[1] - p[1]) * (q[0] - v[0]);
182
+ const dot = (v[0] - p[0]) * (q[0] - v[0]) + (v[1] - p[1]) * (q[1] - v[1]);
183
+ return dot <= 0 || Math.abs(cross) > 1e-6 * Math.max(dot, 1e-9) * 10;
184
+ });
185
+ }
186
+
187
+ function straight(a, b, step) {
188
+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]);
189
+ const count = Math.max(1, Math.ceil(len / step));
190
+ return Array.from({ length: count + 1 }, (_, i) => [a[0] + ((b[0] - a[0]) * i) / count, a[1] + ((b[1] - a[1]) * i) / count]);
191
+ }
192
+
193
+ // Best drivable replacement for the ring between arc lengths a..b (both tight
194
+ // vertices). Entry is either on the ring up to roomBack before a, or an
195
+ // overshoot straight past a; exit is on the ring up to roomFwd after b, or a
196
+ // straight run-in onto b. Candidates are checked shortest/closest-first.
197
+ function bestManoeuvre(ring, a, b, roomBack, roomFwd, radius, driveArea) {
198
+ const offsets = [0, radius / 2, radius, 1.5 * radius, 2 * radius];
199
+ const pa = ring.at(a).p;
200
+ const pb = ring.at(b).p;
201
+ const tIn = ring.at(a - 1e-3).th;
202
+ const tOut = ring.at(b + 1e-3).th;
203
+
204
+ const entries = [];
205
+ offsets.forEach((s) => {
206
+ if (s > roomBack + 1e-9) return;
207
+ const { p, th } = s === 0 ? { p: pa, th: tIn } : ring.at(a - s);
208
+ entries.push({ arc: a - s, pose: { x: p[0], y: p[1], th }, lead: null, penalty: s });
209
+ });
210
+ offsets.slice(1).forEach((e) => {
211
+ const p = [pa[0] + e * Math.cos(tIn), pa[1] + e * Math.sin(tIn)];
212
+ entries.push({ arc: a, pose: { x: p[0], y: p[1], th: tIn }, lead: [pa, p], penalty: e });
213
+ });
214
+
215
+ const exits = [];
216
+ offsets.forEach((s) => {
217
+ if (s > roomFwd + 1e-9) return;
218
+ const { p, th } = s === 0 ? { p: pb, th: tOut } : ring.at(b + s);
219
+ exits.push({ arc: b + s, pose: { x: p[0], y: p[1], th }, tail: null, penalty: s });
220
+ });
221
+ offsets.slice(1).forEach((f) => {
222
+ const p = [pb[0] - f * Math.cos(tOut), pb[1] - f * Math.sin(tOut)];
223
+ exits.push({ arc: b, pose: { x: p[0], y: p[1], th: tOut }, tail: [p, pb], penalty: f });
224
+ });
225
+
226
+ const candidates = [];
227
+ entries.forEach((entry) => exits.forEach((exit) => {
228
+ smoothWords(entry.pose, exit.pose, radius).forEach((word) => {
229
+ const extra = (entry.lead ? entry.penalty : 0) + (exit.tail ? exit.penalty : 0);
230
+ candidates.push({ entry, exit, word, score: word.length + extra + 0.5 * (entry.penalty + exit.penalty) });
231
+ });
232
+ }));
233
+ candidates.sort((x, y) => x.score - y.score);
234
+
235
+ for (const { entry, exit, word } of candidates.slice(0, MAX_MANOEUVRE_CHECKS)) {
236
+ const check = [
237
+ ...(entry.lead ? straight(entry.lead[0], entry.lead[1], CHECK_STEP_M) : []),
238
+ ...sampleDubins(word, CHECK_STEP_M),
239
+ ...(exit.tail ? straight(exit.tail[0], exit.tail[1], CHECK_STEP_M) : [])
240
+ ];
241
+ if (!driveArea.containsAll(check)) continue;
242
+ const points = [];
243
+ if (entry.lead) points.push(entry.lead[1]);
244
+ points.push(...sampleDubins(word, OUTPUT_STEP_M).slice(1));
245
+ if (exit.tail) points.push(exit.tail[1]);
246
+ return { entryArc: entry.arc, exitArc: exit.arc, points };
247
+ }
248
+ return wideCorner(ring, a, b, entries, exits, radius, driveArea);
249
+ }
250
+
251
+ // A corner the lap wraps round (an obstacle corner on the inside of the
252
+ // turn) closer than one turning radius cannot be followed: any smooth turn
253
+ // tangent to both sides cuts into the obstacle, and the only one-manoeuvre
254
+ // alternative is a loop. Swing wide instead — through an apex pose pulled
255
+ // out from the corner, so the turn there has its full radius — as two hops.
256
+ // Going round the corner may take one long arc (it is the ring round the
257
+ // obstacle, not a U-turn), but never a loop.
258
+ function wideCorner(ring, a, b, entries, exits, radius, driveArea) {
259
+ const mid = ring.at((a + b) / 2);
260
+ const tIn = ring.at(a - 1e-3).th;
261
+ const tOut = ring.at(b + 1e-3).th;
262
+ const turnSign = Math.sign(wrapAngle(tOut - tIn)) || 1;
263
+ const outward = mid.th - turnSign * Math.PI / 2; // away from the inside of the turn
264
+ const plainEntries = entries.filter((entry) => !entry.lead && entry.penalty > 0);
265
+ const plainExits = exits.filter((exit) => !exit.tail && exit.penalty > 0);
266
+
267
+ const candidates = [];
268
+ WIDE_CORNER_OFFSETS.forEach((k) => {
269
+ const apex = {
270
+ x: mid.p[0] + k * radius * Math.cos(outward),
271
+ y: mid.p[1] + k * radius * Math.sin(outward),
272
+ th: mid.th
273
+ };
274
+ if (!driveArea.contains(apex.x, apex.y)) return;
275
+ plainEntries.forEach((entry) => {
276
+ const first = smoothWords(entry.pose, apex, radius, { wrapping: true })[0];
277
+ if (!first) return;
278
+ plainExits.forEach((exit) => {
279
+ const second = smoothWords(apex, exit.pose, radius, { wrapping: true })[0];
280
+ if (!second || !chainIsSmooth([first, second], { wrapping: true })) return;
281
+ candidates.push({ entry, exit, first, second, score: first.length + second.length + 0.5 * (entry.penalty + exit.penalty) });
282
+ });
283
+ });
284
+ });
285
+ candidates.sort((x, y) => x.score - y.score);
286
+
287
+ for (const { entry, exit, first, second } of candidates.slice(0, MAX_MANOEUVRE_CHECKS)) {
288
+ if (!driveArea.containsAll(sampleDubins(first, CHECK_STEP_M)) || !driveArea.containsAll(sampleDubins(second, CHECK_STEP_M))) continue;
289
+ const points = [...sampleDubins(first, OUTPUT_STEP_M).slice(1), ...sampleDubins(second, OUTPUT_STEP_M).slice(1)];
290
+ return { entryArc: entry.arc, exitArc: exit.arc, points };
291
+ }
292
+ return null;
293
+ }
294
+
295
+ // Net heading change over about TIGHT_SPAN_M either side of ring vertex i,
296
+ // against the turn a 1/R arc makes over the same length.
297
+ function spanTooTight(ring, i, radius) {
298
+ const n = ring.length;
299
+ const seg = (k) => Math.hypot(ring[(k + 1) % n][0] - ring[k % n][0], ring[(k + 1) % n][1] - ring[k % n][1]);
300
+ let back = 0;
301
+ let a = i;
302
+ for (let s = 0; s < n && back < TIGHT_SPAN_M; s += 1) { a = (a - 1 + n) % n; back += seg(a); }
303
+ let fwd = 0;
304
+ let b = i;
305
+ for (let s = 0; s < n && fwd < TIGHT_SPAN_M; s += 1) { fwd += seg(b); b = (b + 1) % n; }
306
+ const pa = ring[a], pa1 = ring[(a + 1) % n], pb0 = ring[(b - 1 + n) % n], pb = ring[b];
307
+ const turn = Math.abs(wrapAngle(headingOf(pb0, pb) - headingOf(pa, pa1)));
308
+ const length = back + fwd;
309
+ return length > 0 && turn / length > TIGHT_CURVATURE_FACTOR / radius;
310
+ }
311
+
312
+ // Turns one offset ring into drivable lap paths: [{ closed, points }].
313
+ function smoothLap(rawRing, radius, driveArea) {
314
+ if (rawRing.length < 3) return [];
315
+ const n0 = rawRing.length;
316
+ // Rings arrive resampled at an even RING_SAMPLE_STEP_M (see smoothRing),
317
+ // so the per-vertex turn is a fair curvature measure: GPS-scale wiggles
318
+ // stay below it, any bend the vehicle cannot follow exceeds it.
319
+ const bends = rawRing.map((v, i) => {
320
+ const p = rawRing[(i - 1 + n0) % n0];
321
+ const q = rawRing[(i + 1) % n0];
322
+ const turn = Math.abs(wrapAngle(headingOf(v, q) - headingOf(p, v)));
323
+ const meanLen = (Math.hypot(v[0] - p[0], v[1] - p[1]) + Math.hypot(q[0] - v[0], q[1] - v[1])) / 2;
324
+ return turn > MAX_PLAIN_VERTEX_TURN_RAD || turn / Math.max(meanLen, 1e-6) > TIGHT_CURVATURE_FACTOR / radius
325
+ || spanTooTight(rawRing, i, radius);
326
+ });
327
+ // Widen each tight run by a vertex either side: the vertex where an arc
328
+ // meets a straight side still carries part of the bend, and the manoeuvre
329
+ // must start from a straight heading, not from that kink.
330
+ const tight0 = bends.map((b, i) => b || bends[(i - 1 + n0) % n0] || bends[(i + 1) % n0]);
331
+ if (tight0.every(Boolean)) return []; // e.g. a circle smaller than the turning circle
332
+ if (!tight0.some(Boolean)) return [{ closed: true, points: dropCollinear(rawRing, true) }];
333
+
334
+ // Start the ring in the middle of its longest easy stretch, so no tight
335
+ // stretch wraps across the start.
336
+ let bestStart = 0;
337
+ let bestLen = -1;
338
+ for (let i = 0; i < n0; i += 1) {
339
+ if (tight0[i] || !tight0[(i - 1 + n0) % n0]) continue;
340
+ let j = i;
341
+ let len = 0;
342
+ while (!tight0[j % n0] && j < i + n0) {
343
+ const a = rawRing[j % n0];
344
+ const b = rawRing[(j + 1) % n0];
345
+ len += Math.hypot(b[0] - a[0], b[1] - a[1]);
346
+ j += 1;
347
+ }
348
+ if (len > bestLen) {
349
+ bestLen = len;
350
+ bestStart = (i + Math.floor((j - i) / 2)) % n0;
351
+ }
352
+ }
353
+ const points = [...rawRing.slice(bestStart), ...rawRing.slice(0, bestStart)];
354
+ const tight = [...tight0.slice(bestStart), ...tight0.slice(0, bestStart)];
355
+ const ring = ringGeometry(points);
356
+
357
+ // Runs of consecutive tight vertices, as [startArc, endArc].
358
+ const stretches = [];
359
+ for (let i = 0; i < ring.n; i += 1) {
360
+ if (!tight[i]) continue;
361
+ if (i > 0 && tight[i - 1]) stretches[stretches.length - 1][1] = ring.starts[i];
362
+ else stretches.push([ring.starts[i], ring.starts[i]]);
363
+ }
364
+
365
+ // Manoeuvre for stretches k..m (merged), entering after `from`. It may use
366
+ // only half the easy ring before the next stretch, leaving the rest for
367
+ // that stretch's own run-up — unless `m` is the last stretch.
368
+ const attempt = (k, from) => {
369
+ const a = stretches[k][0];
370
+ for (let m = k; m < Math.min(stretches.length, k + 1 + MERGE_ATTEMPTS); m += 1) {
371
+ const b = stretches[m][1];
372
+ const roomFwd = m + 1 < stretches.length ? (stretches[m + 1][0] - b) / 2 : ring.total - b;
373
+ const found = bestManoeuvre(ring, a, b, a - from, roomFwd, radius, driveArea);
374
+ if (found) return { found, last: m };
375
+ }
376
+ return null;
377
+ };
378
+
379
+ const pieces = [];
380
+ let current = [ring.at(0).p];
381
+ let cursor = 0;
382
+ let previous = null; // last manoeuvre, kept so a failing next stretch can merge back into it
383
+ let k = 0;
384
+ while (k < stretches.length) {
385
+ let done = attempt(k, cursor);
386
+ if (!done && previous && previous.last === k - 1) {
387
+ // The previous manoeuvre left too little run-up: redo it merged with
388
+ // this stretch as one manoeuvre.
389
+ const merged = attempt(previous.first, previous.from);
390
+ if (merged && merged.last >= k) {
391
+ current.length = previous.length;
392
+ cursor = previous.from;
393
+ done = merged;
394
+ k = previous.first;
395
+ }
396
+ }
397
+ if (done) {
398
+ previous = { first: k, last: done.last, from: cursor, length: current.length };
399
+ current.push(...ring.verticesBetween(cursor, done.found.entryArc), ring.at(done.found.entryArc).p, ...done.found.points);
400
+ cursor = done.found.exitArc;
401
+ k = done.last + 1;
402
+ continue;
403
+ }
404
+ // Nothing drivable gets round this stretch: end the piece before it and
405
+ // start a new one after it.
406
+ const a = stretches[k][0];
407
+ current.push(...ring.verticesBetween(cursor, a), ring.at(a).p);
408
+ pieces.push(current);
409
+ cursor = stretches[k][1];
410
+ current = [ring.at(cursor).p];
411
+ previous = null;
412
+ k += 1;
413
+ }
414
+ current.push(...ring.verticesBetween(cursor, ring.total), ring.at(0).p);
415
+
416
+ if (pieces.length === 0) {
417
+ current.pop(); // closing duplicate of the start
418
+ return [{ closed: true, points: dropCollinear(current, true) }];
419
+ }
420
+ // The last piece runs through the ring start into the first one.
421
+ pieces[0] = [...current, ...pieces[0].slice(1)];
422
+ const pathLength = (pts) => pts.reduce((sum, p, i) => (i ? sum + Math.hypot(p[0] - pts[i - 1][0], p[1] - pts[i - 1][1]) : 0), 0);
423
+ return pieces
424
+ .filter((pts) => pts.length >= 2 && pathLength(pts) >= radius)
425
+ .map((pts) => ({ closed: false, points: dropCollinear(pts, false) }));
426
+ }
427
+
428
+ // Final guard on a finished lap: back-to-back corner manoeuvres with too
429
+ // little straight between them can still chain into one tight arc of a
430
+ // semicircle or more. Cut each such arc out and split the lap there. Only
431
+ // tight arcs count — a wide orbit round an obstacle is a ring, not a
432
+ // semicircle.
433
+ // Only arcs this tight (× 1/R) are corner manoeuvres; anything gentler is
434
+ // the ring following the boundary or orbiting an obstacle.
435
+ const TIGHT_ARC_CURVATURE_FACTOR = 0.8;
436
+ function splitAtTightArcs(lap, radius) {
437
+ const pts = lap.points;
438
+ const n = pts.length;
439
+ if (n < 3) return [lap];
440
+ const cuts = []; // [startIndex, endIndex] of each offending arc
441
+ let groupStart = -1;
442
+ let group = 0;
443
+ let sign = 0;
444
+ let straight = 0;
445
+ const close = (end) => {
446
+ if (groupStart >= 0 && Math.abs(group) > MAX_LAP_ARC_RAD) cuts.push([groupStart, end]);
447
+ groupStart = -1;
448
+ group = 0;
449
+ sign = 0;
450
+ };
451
+ const last = lap.closed ? n : n - 1;
452
+ for (let i = 1; i < last; i += 1) {
453
+ const a = pts[i - 1];
454
+ const b = pts[i % n];
455
+ const c = pts[(i + 1) % n];
456
+ const len = Math.hypot(c[0] - b[0], c[1] - b[1]);
457
+ const turn = wrapAngle(headingOf(b, c) - headingOf(a, b));
458
+ if (Math.abs(turn) < 1e-4) {
459
+ straight += len;
460
+ if (straight >= STRAIGHT_BREAK_FACTOR * radius) close(i);
461
+ continue;
462
+ }
463
+ straight = 0;
464
+ const prevLen = Math.hypot(b[0] - a[0], b[1] - a[1]);
465
+ const tight = Math.abs(turn) / Math.max((len + prevLen) / 2, 1e-6) >= TIGHT_ARC_CURVATURE_FACTOR / radius;
466
+ if (!tight || (sign !== 0 && Math.sign(turn) !== sign)) close(i);
467
+ if (!tight) continue;
468
+ if (groupStart < 0) groupStart = i - 1;
469
+ group += turn;
470
+ sign = Math.sign(turn);
471
+ }
472
+ close(last);
473
+ if (cuts.length === 0) return [lap];
474
+
475
+ // Keep everything outside the cut arcs, as open pieces (a closed lap's
476
+ // last piece runs on into its first).
477
+ const pieces = [];
478
+ let from = 0;
479
+ cuts.forEach(([start, end]) => {
480
+ pieces.push(pts.slice(from, start + 1));
481
+ from = end;
482
+ });
483
+ const tail = pts.slice(from);
484
+ if (lap.closed && pieces.length) pieces[0] = [...tail, ...pieces[0]];
485
+ else pieces.push(tail);
486
+ const length = (p) => p.reduce((sum, q, i) => (i ? sum + Math.hypot(q[0] - p[i - 1][0], q[1] - p[i - 1][1]) : 0), 0);
487
+ return pieces.filter((p) => p.length >= 2 && length(p) >= radius).map((p) => ({ closed: false, points: p }));
488
+ }
489
+
490
+ // An open piece must start and end on a straight: it was cut where its ring
491
+ // got too tight, so an end can sit part-way round a corner arc, and the turn
492
+ // connecting to it would carry that arc on into a loop. Trims the curved
493
+ // tail off each end.
494
+ function trimCurvedEnds(lap, radius) {
495
+ if (lap.closed) return [lap];
496
+ // Walks back from the end: tight arcs and the short straights between
497
+ // them are dropped until a straight of at least the flat-U-turn length, or
498
+ // a gentle curve, is reached.
499
+ const trimEnd = (pts) => {
500
+ const n = pts.length;
501
+ const seg = (i) => Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]);
502
+ const turnAt = (i) => Math.abs(wrapAngle(headingOf(pts[i], pts[i + 1]) - headingOf(pts[i - 1], pts[i])));
503
+ let cutAt = null;
504
+ let straight = 0;
505
+ for (let i = n - 2; i >= 1; i -= 1) {
506
+ const turn = turnAt(i);
507
+ if (turn < 1e-4) {
508
+ straight += seg(i);
509
+ if (straight >= STRAIGHT_BREAK_FACTOR * radius) break;
510
+ continue;
511
+ }
512
+ if (turn / Math.max((seg(i - 1) + seg(i)) / 2, 1e-6) < TIGHT_ARC_CURVATURE_FACTOR / radius) break; // gentle curve
513
+ cutAt = i;
514
+ straight = 0;
515
+ }
516
+ return cutAt === null ? pts : pts.slice(0, cutAt + 1);
517
+ };
518
+ const trimmed = trimEnd(trimEnd(lap.points).reverse()).reverse();
519
+ const length = trimmed.reduce((sum, q, i) => (i ? sum + Math.hypot(q[0] - trimmed[i - 1][0], q[1] - trimmed[i - 1][1]) : 0), 0);
520
+ return trimmed.length >= 2 && length >= radius ? [{ closed: false, points: trimmed }] : [];
521
+ }
522
+
523
+ // Chaikin corner cutting on a closed ring: rings offset from a recorded
524
+ // (GPS-jittery) boundary are full of small kinks a metre or two apart, each
525
+ // of which would otherwise need its own corner manoeuvre with no room to fit
526
+ // one. Each pass moves the ring only within its own corners; the result is
527
+ // kept only if it stays inside the drive area.
528
+ function chaikin(ring, passes) {
529
+ let pts = ring;
530
+ for (let pass = 0; pass < passes; pass += 1) {
531
+ const out = [];
532
+ pts.forEach((a, i) => {
533
+ const b = pts[(i + 1) % pts.length];
534
+ out.push([0.75 * a[0] + 0.25 * b[0], 0.75 * a[1] + 0.25 * b[1]]);
535
+ out.push([0.25 * a[0] + 0.75 * b[0], 0.25 * a[1] + 0.75 * b[1]]);
536
+ });
537
+ pts = out;
538
+ }
539
+ return pts;
540
+ }
541
+
542
+ // Evenly spaced points along a closed ring.
543
+ function resampleRing(ring, step) {
544
+ const geometry = ringGeometry(ring);
545
+ const count = Math.max(3, Math.round(geometry.total / step));
546
+ return Array.from({ length: count }, (_, i) => geometry.at((i * geometry.total) / count).p);
547
+ }
548
+
549
+ function smoothRing(ring, driveArea) {
550
+ const smoothed = chaikin(ring, RING_SMOOTHING_PASSES);
551
+ return resampleRing(driveArea.containsAll(smoothed) ? smoothed : ring, RING_SAMPLE_STEP_M);
552
+ }
553
+
554
+ // Every lap (or lap piece) carries `depth`, its ring's index counted in from
555
+ // the boundary/obstacle, so the router can mow the laps ring by ring.
556
+ function generateHeadlandLaps(options) {
557
+ const { turningRadius, driveArea } = options;
558
+ return generateLapRings(options).flatMap(({ depth, points }) =>
559
+ smoothLap(smoothRing(points, driveArea), turningRadius, driveArea)
560
+ .flatMap((lap) => splitAtTightArcs(lap, turningRadius))
561
+ .flatMap((lap) => trimCurvedEnds(lap, turningRadius))
562
+ .filter((lap) => lap.closed || lapLength(lap.points) >= MIN_OPEN_LAP_RADII * turningRadius)
563
+ .map((lap) => ({ ...lap, depth })));
564
+ }
565
+
566
+ // Cutting laps at tight bends leaves slivers a metre or two long. They mow
567
+ // almost nothing, and the connection out to one and back is typically a full
568
+ // loop, so open pieces shorter than this many turning radii are not planned.
569
+ const MIN_OPEN_LAP_RADII = 1;
570
+ function lapLength(points) {
571
+ let length = 0;
572
+ for (let i = 1; i < points.length; i += 1) length += Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]);
573
+ return length;
574
+ }
575
+
576
+ module.exports = { generateHeadlandLaps };