@anandommi/fields2cover 0.1.0 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1 — 2026-11-24
4
+
5
+ ### Fixed
6
+ - Self-intersecting obstacle outlines (e.g. recorded drives around long, thin obstacles) are normalised into valid polygons, so turns and transits no longer cut through them.
7
+ - Removed small loops/circles from the mower path; turns may tighten to 65% of the turning radius where needed.
8
+ - Grid (criss-cross) crash, missing rows, obstacle-tip clipping and a lost half of the field on irregular boundaries.
9
+ - Row spacing measured in metres; dead-end rows turn round instead of being skipped.
10
+ - Faster drive-area checks.
11
+
12
+ ### Changed
13
+ - Grid (criss-cross) pass works with obstacle avoidance.
14
+ - `contentDisposition` filename includes `_grid` for criss-cross paths.
15
+
3
16
  ## 0.1.0 — 2026-11-04
4
17
 
5
18
  First release.
package/lib/coverage.js CHANGED
@@ -20,7 +20,7 @@ const { fieldArea, generateMainland } = require('./headland');
20
20
  const { generateSwathColumns } = require('./swaths');
21
21
  const { decomposeIntoCells } = require('./decomposition');
22
22
  const { generateCustomOrder } = require('./routeOrder');
23
- const { PathPlanner, pose, smoothWords } = require('./pathPlanner');
23
+ const { PathPlanner, pose, smoothWords, hasCircle } = require('./pathPlanner');
24
24
  const { generateHeadlandLaps } = require('./headlandLaps');
25
25
 
26
26
  const CONNECTOR_BOUNDARY_CLEARANCE_M = 0.3; // just enough to not sit exactly on the true boundary
@@ -36,6 +36,7 @@ const ROW_LOOKAHEAD = 4; // rows further along the order tried when the next one
36
36
  const ROW_EXIT_ESCAPE_RADII = [2, 3, 4, 5];
37
37
  const CELL_DIRECT_CANDIDATES = 12; // best-ranked cell entries tried with a single Dubins turn
38
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)
39
40
  const LAP_CLEARANCE_MARGIN_M = 0.1; // keeps the outermost laps off the drive area's own edge
40
41
  const LAP_ENTRY_STEP_M = 3; // spacing of candidate entry points along a lap
41
42
  const LAP_ENTRY_MAX_CURVATURE_FACTOR = 0.8; // laps are entered only where they bend gentler than this × 1/R
@@ -43,6 +44,8 @@ const LAP_ENTRY_CLEARANCE_M = 3; // ...for at least this far either side of the
43
44
  const LAP_ENTRY_DENSIFY_M = 1;
44
45
  const LAP_DIRECT_CANDIDATES = 40;
45
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
46
49
  const MAX_LAP_BACKTRACKS = 60; // undo budget when the lap router paints itself into a corner
47
50
  const NEXT_RING_DIRECT_CANDIDATES = 12; // entries on the neighbouring ring tried first, with a single turn
48
51
  // ...only within this × R: a lane change onto the next ring, not a hop across
@@ -159,6 +162,11 @@ class CoverageRoute {
159
162
  // smooth, drivable curves, entered and left only where they bend gently;
160
163
  // the whole chain is still checked so hop, lap bend and hop never add up
161
164
  // to a loop.
165
+ viaLapsNoLoop(targets) {
166
+ const best = this.viaLaps(targets);
167
+ return best && !this.loopsWith(best.connection) ? best : null;
168
+ }
169
+
162
170
  viaLaps(targets) {
163
171
  if (!this.roads.length || !targets.length) return null;
164
172
  if (!this.roadStops) {
@@ -225,6 +233,7 @@ class CoverageRoute {
225
233
  let best = null;
226
234
  for (const entry of candidates) {
227
235
  const connection = connect(this.pose, entry.target);
236
+ if (connection && this.loopsWith(connection)) continue;
228
237
  if (connection && (!best || connection.length < best.connection.length)) {
229
238
  best = { ...entry, connection };
230
239
  if (stopAtFirst) break;
@@ -234,6 +243,7 @@ class CoverageRoute {
234
243
  }
235
244
 
236
245
  driveRow(row, dir, connection) {
246
+ (this.rowEnds = this.rowEnds || []).push({ pointsLength: this.points.length, pose: this.pose, row });
237
247
  if (connection) this.points.push(...connection.points.slice(1));
238
248
  else this.points.push(rowStart(row, dir));
239
249
  this.points.push(rowEnd(row, dir));
@@ -250,6 +260,7 @@ class CoverageRoute {
250
260
  for (const dir of [1, -1]) {
251
261
  if (!this.exitEscapable(row, dir)) continue;
252
262
  const connection = connect(this.pose, entryPose(row, dir));
263
+ if (connection && this.loopsWith(connection)) continue;
253
264
  if (connection && (!best || connection.length < best.connection.length)) best = { dir, connection };
254
265
  }
255
266
  return best;
@@ -307,7 +318,7 @@ class CoverageRoute {
307
318
  return this.pick(ranked.slice(0, CELL_DIRECT_CANDIDATES), (a, b) => this.planner.direct(a, b), false)
308
319
  || this.pick(entries.slice(0, CELL_TRANSIT_CANDIDATES), (a, b) => this.planner.transit(a, b), false)
309
320
  || this.pick(entries.slice(CELL_TRANSIT_CANDIDATES), (a, b) => this.planner.transit(a, b), true)
310
- || this.viaLaps(entries);
321
+ || this.viaLapsNoLoop(entries);
311
322
  }
312
323
 
313
324
  // Covers every cell of one pass. Returns the number of rows that could
@@ -317,6 +328,7 @@ class CoverageRoute {
317
328
  coverPass(cells) {
318
329
  const pool = cells.filter((cell) => cell.rows.length > 0);
319
330
  if (pool.length === 0) return 0;
331
+ let unwound = 0;
320
332
 
321
333
  if (!this.pose) {
322
334
  // Start in the biggest cell, on its leftmost row (relative to the
@@ -338,15 +350,55 @@ class CoverageRoute {
338
350
  .forEach((row) => pool.push({ pass: start.cell.pass, rows: [row], order: [0] }));
339
351
  }
340
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
341
364
  while (pool.length) {
342
- const next = this.chooseNextCell(pool);
365
+ const free = pool.filter((cell) => !held.has(cell));
366
+ const next = this.chooseNextCell(free.length ? free : pool);
343
367
  if (!next) {
344
- // Nothing left is reachable from here, so nothing left ever will be.
345
- return pool.reduce((sum, cell) => sum + cell.rows.length, 0);
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;
346
393
  }
394
+ unwoundHere = 0;
347
395
  pool.splice(pool.indexOf(next.cell), 1);
348
396
  this.runCell(next.cell, next)
349
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
+ }
350
402
  }
351
403
  return 0;
352
404
  }
@@ -407,6 +459,34 @@ class CoverageRoute {
407
459
  return out;
408
460
  }
409
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
+
410
490
  // Drives a lap from the chosen entry. For an open piece entered part way
411
491
  // along, returns the part behind the entry as a new open piece (or null).
412
492
  driveLap({ lap, pts, index, connection }) {
@@ -482,11 +562,22 @@ class CoverageRoute {
482
562
  const stateKey = () => history.map((step) => step.key).join('>');
483
563
  const entryKey = (entry) => `${idOf(entry.pts)}:${entry.index}`;
484
564
  let backtracks = 0;
565
+ let rowsUnwound = 0;
485
566
 
486
567
  while (pool.length) {
487
568
  const prefix = stateKey();
488
569
  const allowed = (entry) => !banned.has(`${prefix}|${entryKey(entry)}`);
489
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
+ }
490
581
  if (!next) {
491
582
  if (!history.length || backtracks >= MAX_LAP_BACKTRACKS) return dropped + pool.length;
492
583
  backtracks += 1;
@@ -505,6 +596,17 @@ class CoverageRoute {
505
596
  const step = { key: entryKey(next), lap: next.lap, pointsLength: this.points.length, pose: this.pose, depth: this.lapDepth, remainder: null };
506
597
  pool.splice(pool.indexOf(next.lap), 1);
507
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
+ }
508
610
  if (remainder) {
509
611
  pool.push(remainder);
510
612
  entriesOf.set(remainder, this.lapEntries(remainder));
@@ -554,7 +656,7 @@ class CoverageRoute {
554
656
  return this.pick(ranked.slice(0, LAP_DIRECT_CANDIDATES), (a, b) => this.planner.direct(a, b), false)
555
657
  || this.pick(entries.slice(0, LAP_TRANSIT_CANDIDATES).filter((e) => this.transitWorthTrying(e)), (a, b) => this.lapTransit(a, b), false)
556
658
  || this.pick(onePerLap.filter((e) => this.transitWorthTrying(e)), (a, b) => this.lapTransit(a, b), true)
557
- || this.viaLaps(entries);
659
+ || this.viaLapsNoLoop(entries);
558
660
  }
559
661
 
560
662
  // Lap entries no transit reaches (a ring round a small obstacle in a
@@ -614,6 +716,7 @@ function planCoverage({ polygonCoords, obstacleRings, referenceLineCoords, headl
614
716
  obstacleStart: Math.max(spacing / 2, CONNECTOR_OBSTACLE_CLEARANCE_M + LAP_CLEARANCE_MARGIN_M),
615
717
  toLocal: frame.toLocal,
616
718
  turningRadius,
719
+ configuredRadius: turningRadius,
617
720
  driveArea
618
721
  });
619
722
 
@@ -17,6 +17,10 @@ const { fieldArea } = require('./headland');
17
17
  // paths.
18
18
 
19
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;
20
24
  const MAX_PLAIN_VERTEX_TURN_RAD = 0.2; // ~11.5°: any sharper polyline kink gets a manoeuvre too, however long its sides
21
25
  const CHECK_STEP_M = 0.25;
22
26
  const OUTPUT_STEP_M = 0.1;
@@ -77,7 +81,7 @@ function openArea(area, radius) {
77
81
  // obstacle clearance. Each lap's rings are the outer ring and hole rings of
78
82
  // that offset area, so an obstacle close to the boundary merges into it
79
83
  // naturally.
80
- function generateLapRings({ polygonCoords, obstacleRings, headlandWidth, spacing, boundaryStart, obstacleStart, toLocal, turningRadius }) {
84
+ function generateLapRings({ polygonCoords, obstacleRings, headlandWidth, spacing, boundaryStart, obstacleStart, toLocal, configuredRadius }) {
81
85
  const rings = [];
82
86
  const count = Math.ceil(headlandWidth / spacing - 1e-9);
83
87
  for (let j = 0; j < count; j += 1) {
@@ -87,12 +91,35 @@ function generateLapRings({ polygonCoords, obstacleRings, headlandWidth, spacing
87
91
  } catch {
88
92
  break; // offset has consumed the whole field
89
93
  }
90
- areaFromGeoJSON(openArea(area, turningRadius), toLocal).polygons
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))
91
99
  .forEach((polygon) => polygon.forEach((ring) => rings.push({ depth: j, points: cleanRing(ring) })));
92
100
  }
93
101
  return rings.filter((ring) => ring.points.length >= 3);
94
102
  }
95
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
+
96
123
  // Closed polyline with arc-length lookup.
97
124
  function ringGeometry(points) {
98
125
  const n = points.length;
@@ -265,6 +292,23 @@ function wideCorner(ring, a, b, entries, exits, radius, driveArea) {
265
292
  return null;
266
293
  }
267
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
+
268
312
  // Turns one offset ring into drivable lap paths: [{ closed, points }].
269
313
  function smoothLap(rawRing, radius, driveArea) {
270
314
  if (rawRing.length < 3) return [];
@@ -277,7 +321,8 @@ function smoothLap(rawRing, radius, driveArea) {
277
321
  const q = rawRing[(i + 1) % n0];
278
322
  const turn = Math.abs(wrapAngle(headingOf(v, q) - headingOf(p, v)));
279
323
  const meanLen = (Math.hypot(v[0] - p[0], v[1] - p[1]) + Math.hypot(q[0] - v[0], q[1] - v[1])) / 2;
280
- return turn > MAX_PLAIN_VERTEX_TURN_RAD || turn / Math.max(meanLen, 1e-6) > TIGHT_CURVATURE_FACTOR / radius;
324
+ return turn > MAX_PLAIN_VERTEX_TURN_RAD || turn / Math.max(meanLen, 1e-6) > TIGHT_CURVATURE_FACTOR / radius
325
+ || spanTooTight(rawRing, i, radius);
281
326
  });
282
327
  // Widen each tight run by a vertex either side: the vertex where an arc
283
328
  // meets a straight side still carries part of the bend, and the manoeuvre
@@ -514,7 +559,18 @@ function generateHeadlandLaps(options) {
514
559
  smoothLap(smoothRing(points, driveArea), turningRadius, driveArea)
515
560
  .flatMap((lap) => splitAtTightArcs(lap, turningRadius))
516
561
  .flatMap((lap) => trimCurvedEnds(lap, turningRadius))
562
+ .filter((lap) => lap.closed || lapLength(lap.points) >= MIN_OPEN_LAP_RADII * turningRadius)
517
563
  .map((lap) => ({ ...lap, depth })));
518
564
  }
519
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
+
520
576
  module.exports = { generateHeadlandLaps };
package/lib/mowerPath.js CHANGED
@@ -4,6 +4,7 @@ const { closeMowerPathFallback } = require('./mowerLoopFallback');
4
4
  const { planCoverage, CONNECTOR_BOUNDARY_CLEARANCE_M, CONNECTOR_OBSTACLE_CLEARANCE_M } = require('./coverage');
5
5
  const { fieldArea } = require('./headland');
6
6
  const { createLocalFrame } = require('./frame');
7
+ const { normalizeObstacleRings } = require('./obstacleRings');
7
8
 
8
9
  // Request handling for the Fields2Cover-style planner (POST
9
10
  // /api/generateF2cMowerPath). Same request body and response shape as the
@@ -148,7 +149,7 @@ function computeF2cMowerPath(body) {
148
149
  }
149
150
 
150
151
  // Obstacles only shape the rows and turns when obstacle-avoid is on.
151
- const obstacles = Array.isArray(obstaclePolygons) ? obstaclePolygons : [];
152
+ const obstacles = normalizeObstacleRings(obstaclePolygons);
152
153
  const obstacleAware = !!obstacleAvoid && obstacles.length > 0;
153
154
 
154
155
  const plan = planCoverage({
@@ -202,9 +203,7 @@ function computeF2cMowerPath(body) {
202
203
  return {
203
204
  status: 200,
204
205
  result,
205
- contentDisposition: obstacleAware
206
- ? "attachment; filename=mower_path_f2c_obstacle_aware.geojson"
207
- : "attachment; filename=mower_path_f2c.geojson"
206
+ contentDisposition: `attachment; filename=mower_path_f2c${crissCross ? "_grid" : ""}${obstacleAware ? "_obstacle_aware" : ""}.geojson`
208
207
  };
209
208
  } catch (error) {
210
209
  console.error("Error generating F2C mower path:", error);
@@ -0,0 +1,50 @@
1
+ const turf = require('@turf/turf');
2
+
3
+ // Obstacle outlines usually come from a recorded drive around the obstacle
4
+ // (mission file LineStrings closed into Polygons on upload). On a long, thin
5
+ // obstacle the return leg wanders across the outbound leg, so the ring
6
+ // self-intersects. turf.buffer on such an invalid polygon returns garbage: a
7
+ // ~136 m x 5 m strip buffered by 0.5 m came back as 11 m² instead of ~700 m²,
8
+ // so the connector/transit drive area ignored the obstacle and turns were
9
+ // routed straight through it.
10
+ //
11
+ // Normalise every ring into a valid simple polygon covering everything the
12
+ // outline encloses: buffer the outline as a line by a few centimetres (always
13
+ // valid, whatever the self-crossings), union the pieces and keep only the
14
+ // exterior ring(s) so any enclosed pocket is filled rather than left as a hole.
15
+ const OUTLINE_BUFFER_M = 0.05;
16
+
17
+ function closeRing(coords) {
18
+ const first = coords[0];
19
+ const last = coords[coords.length - 1];
20
+ return first[0] === last[0] && first[1] === last[1] ? coords : [...coords, first];
21
+ }
22
+
23
+ function exteriorRings(geometry) {
24
+ if (!geometry) return [];
25
+ if (geometry.type === 'Polygon') return [geometry.coordinates[0]];
26
+ if (geometry.type === 'MultiPolygon') return geometry.coordinates.map((poly) => poly[0]);
27
+ return [];
28
+ }
29
+
30
+ function normalizeObstacleRing(coords) {
31
+ if (!Array.isArray(coords) || coords.length < 3) return [];
32
+ const ring = closeRing(coords);
33
+ if (ring.length < 4) return [];
34
+ try {
35
+ const outline = turf.buffer(turf.lineString(ring), OUTLINE_BUFFER_M / 1000, { units: 'kilometers' });
36
+ const rings = exteriorRings(outline?.geometry).filter((r) => r.length >= 4);
37
+ if (rings.length > 0) return rings;
38
+ } catch (err) {
39
+ // fall through to the raw ring
40
+ }
41
+ return [ring];
42
+ }
43
+
44
+ // Array of [lng, lat] rings in -> array of valid, closed, hole-free rings out.
45
+ function normalizeObstacleRings(rings) {
46
+ if (!Array.isArray(rings)) return [];
47
+ return rings.flatMap(normalizeObstacleRing);
48
+ }
49
+
50
+ module.exports = { normalizeObstacleRings };
@@ -23,6 +23,7 @@ const ESCAPE_CHECKS = 40;
23
23
 
24
24
  const pose = (x, y, th) => ({ x, y, th });
25
25
 
26
+
26
27
  // No loops: a single manoeuvre may turn at most a U-turn plus a little
27
28
  // (enough for a U-turn between rows whose ends are not level). Anything more
28
29
  // is a circle/loop, which the operator does not want.
@@ -122,12 +123,81 @@ function longestTurn(words) {
122
123
  return longest;
123
124
  }
124
125
 
126
+ // At most 65-75% of a circle in one manoeuvre: a U-turn is 180° (50%). A
127
+ // manoeuvre is a stretch of turning with no straight of at least
128
+ // MANOEUVRE_BREAK_RADII × radius in it; turning more than
129
+ // MAX_MANOEUVRE_TURN_FRACTION of a circle one way within a short part of it
130
+ // is a near-full circle, which the vehicle must never drive.
131
+ const MAX_MANOEUVRE_TURN_FRACTION = 0.65; // planner aims at the low end of the allowed 65-75%: margin under the 75% limit for measurement differences
132
+ const MAX_MANOEUVRE_TURN_RAD = MAX_MANOEUVRE_TURN_FRACTION * 2 * Math.PI;
133
+ const TIGHT_LOOP_RADII = 2.5; // stretch checked = max turn at this × turning radius (checker uses 2: margin)
134
+ const MANOEUVRE_SAMPLE_M = 0.5;
135
+ const MANOEUVRE_BREAK_RADII = 1.2; // a straight this × turning radius ends a manoeuvre (checker: 1 ×); shorter flats inside a loop do not
136
+ const STRAIGHT_STEP_RAD = (0.5 * Math.PI) / 180; // per-sample turn that still counts as straight
137
+ const STRAIGHT_RUN_MAX_RAD = (2 * Math.PI) / 180; // total turn allowed along that straight
138
+ function hasCircle(points, radius, onFreeGround = null) {
139
+ if (points.length < 3) return false;
140
+ const rs = [points[0]];
141
+ let carry = 0;
142
+ for (let i = 1; i < points.length; i += 1) {
143
+ const [ax, ay] = points[i - 1];
144
+ const [bx, by] = points[i];
145
+ const d = Math.hypot(bx - ax, by - ay);
146
+ if (d < 1e-9) continue; // duplicate point: 0/0 below would poison every sum with NaN
147
+ let t = MANOEUVRE_SAMPLE_M - carry;
148
+ while (t <= d) {
149
+ rs.push([ax + ((bx - ax) * t) / d, ay + ((by - ay) * t) / d]);
150
+ t += MANOEUVRE_SAMPLE_M;
151
+ }
152
+ carry = d - (t - MANOEUVRE_SAMPLE_M);
153
+ }
154
+ // Within one manoeuvre (no straight of MANOEUVRE_BREAK_RADII × radius), look at every
155
+ // stretch no longer than a MAX turn at TIGHT_LOOP_RADII × radius: turning
156
+ // more than MAX one way inside such a stretch is a near-full circle at
157
+ // about the turning radius. Unlike an average over the whole manoeuvre, a
158
+ // long gentle lead-in cannot hide a tight loop at its end.
159
+ const windowSamples = Math.ceil((MAX_MANOEUVRE_TURN_RAD * TIGHT_LOOP_RADII * radius) / MANOEUVRE_SAMPLE_M);
160
+ const sum = [0]; // running signed heading change since the manoeuvre start
161
+ let manoeuvreStart = 0; // index into sum where the current manoeuvre starts
162
+ let straightRun = 0;
163
+ let straightTurn = 0;
164
+ for (let i = 2; i < rs.length; i += 1) {
165
+ let d = Math.atan2(rs[i][1] - rs[i - 1][1], rs[i][0] - rs[i - 1][0])
166
+ - Math.atan2(rs[i - 1][1] - rs[i - 2][1], rs[i - 1][0] - rs[i - 2][0]);
167
+ while (d > Math.PI) d -= 2 * Math.PI;
168
+ while (d < -Math.PI) d += 2 * Math.PI;
169
+ sum.push(sum[sum.length - 1] + d);
170
+ const k = sum.length - 1;
171
+ if (Math.abs(d) < STRAIGHT_STEP_RAD) {
172
+ straightRun += MANOEUVRE_SAMPLE_M;
173
+ straightTurn += Math.abs(d);
174
+ if (straightRun >= MANOEUVRE_BREAK_RADII * radius && straightTurn < STRAIGHT_RUN_MAX_RAD) manoeuvreStart = k;
175
+ continue;
176
+ }
177
+ straightRun = 0;
178
+ straightTurn = 0;
179
+ for (let j = Math.max(manoeuvreStart, k - windowSamples); j < k; j += 1) {
180
+ if (Math.abs(sum[k] - sum[j]) <= MAX_MANOEUVRE_TURN_RAD) continue;
181
+ // Tight loop from rs[j+1] to rs[k+1]; one round an obstacle is a lap.
182
+ if (!onFreeGround) return true;
183
+ let cx = 0;
184
+ let cy = 0;
185
+ for (let q = j + 1; q <= k + 1; q += 1) { cx += rs[q][0]; cy += rs[q][1]; }
186
+ const n = k - j + 1;
187
+ if (onFreeGround(cx / n, cy / n)) return true;
188
+ break;
189
+ }
190
+ }
191
+ return false;
192
+ }
193
+
125
194
  class PathPlanner {
126
195
  constructor({ driveArea, driveFeature, toLocal, radius }) {
127
196
  this.driveArea = driveArea;
128
197
  this.driveFeature = driveFeature;
129
198
  this.toLocal = toLocal;
130
199
  this.radius = radius;
200
+ this.onFreeGround = (x, y) => this.driveArea.contains(x, y);
131
201
  this.graphs = new Map();
132
202
  // Larger margins first: waypoints further from obstacles leave the Dubins
133
203
  // hops room to turn; smaller ones still get through narrow passages.
@@ -136,7 +206,11 @@ class PathPlanner {
136
206
 
137
207
  // Shortest loop-free Dubins word that stays inside the drive area, or null.
138
208
  direct(from, to) {
139
- for (const word of smoothWords(from, to, this.radius)) {
209
+ return this.directAt(from, to, this.radius);
210
+ }
211
+
212
+ directAt(from, to, radius) {
213
+ for (const word of smoothWords(from, to, radius)) {
140
214
  if (this.driveArea.containsAll(sampleDubins(word, CHECK_STEP_M))) {
141
215
  return { points: sampleDubins(word, OUTPUT_STEP_M), length: word.length, words: [word] };
142
216
  }
@@ -150,14 +224,17 @@ class PathPlanner {
150
224
 
151
225
  transit(from, to) {
152
226
  const turnaround = this.twoHop(from, to);
153
- if (turnaround) return turnaround;
227
+ if (turnaround && !hasCircle(turnaround.points, this.radius, this.onFreeGround)) return turnaround;
154
228
  for (const margin of this.margins) {
155
229
  const graph = this.graph(margin);
156
230
  if (!graph) continue;
157
231
  const waypoints = this.shortestPath(graph, [from.x, from.y], [to.x, to.y]);
158
232
  if (!waypoints || waypoints.length === 0) continue;
159
233
  const result = this.followWaypoints(from, waypoints, to);
160
- if (result) return result;
234
+ // Each hop is loop-free, but a chain of hops round nearby waypoints
235
+ // can still close a full circle (seen reaching the last metres of an
236
+ // open lap) — never take one.
237
+ if (result && !hasCircle(result.points, this.radius, this.onFreeGround)) return result;
161
238
  }
162
239
  return null;
163
240
  }
@@ -191,9 +268,9 @@ class PathPlanner {
191
268
  });
192
269
  candidates.sort((a, b) => a.length - b.length);
193
270
  for (const { mid } of candidates.slice(0, TWO_HOP_CHECKS)) {
194
- const first = this.direct(from, mid);
271
+ const first = this.directAt(from, mid, this.radius);
195
272
  if (!first) continue;
196
- const second = this.direct(mid, to);
273
+ const second = this.directAt(mid, to, this.radius);
197
274
  if (!second || !chainIsSmooth([...first.words, ...second.words])) continue;
198
275
  return { points: [...first.points, ...second.points.slice(1)], length: first.length + second.length, words: [...first.words, ...second.words] };
199
276
  }
@@ -219,7 +296,7 @@ class PathPlanner {
219
296
  }
220
297
  });
221
298
  candidates.sort((a, b) => a.length - b.length);
222
- return candidates.slice(0, ESCAPE_CHECKS).some(({ target }) => this.direct(from, target));
299
+ return candidates.slice(0, ESCAPE_CHECKS).some(({ target }) => this.directAt(from, target, this.radius));
223
300
  }
224
301
 
225
302
  graph(margin) {
@@ -341,7 +418,7 @@ class PathPlanner {
341
418
  let hop = null;
342
419
  let reached = -1;
343
420
  for (let j = targets.length - 1; j >= index; j -= 1) {
344
- const candidate = this.direct(current, targets[j]);
421
+ const candidate = this.directAt(current, targets[j], this.radius);
345
422
  if (candidate && chainIsSmooth([...words, ...candidate.words])) {
346
423
  hop = candidate;
347
424
  reached = j;
@@ -359,4 +436,4 @@ class PathPlanner {
359
436
  }
360
437
  }
361
438
 
362
- module.exports = { PathPlanner, pose, smoothWords, chainIsSmooth, UTURN_STRAIGHT_FACTOR };
439
+ module.exports = { hasCircle, PathPlanner, pose, smoothWords, chainIsSmooth, UTURN_STRAIGHT_FACTOR };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anandommi/fields2cover",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Pure-JavaScript Fields2Cover-style coverage path planner for mowers: headlands, boustrophedon cells, swaths, Dubins turns and headland laps on GeoJSON fields.",
5
5
  "main": "index.js",
6
6
  "files": [