@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,439 @@
1
+ const turf = require('@turf/turf');
2
+ const { dubinsCandidates, sampleDubins } = require('./mowerLoopFallback');
3
+ const { areaFromGeoJSON, freeSpaceReflexVertices } = require('./geometry');
4
+ const { bufferMeters } = require('./headland');
5
+
6
+ // Port of Fields2Cover's pp::PathPlanning plus the v2 route planner's
7
+ // headland transit. Every connection is a minimum-radius Dubins path that
8
+ // must stay inside the drive area (boundary and obstacle clearance already
9
+ // applied), and never loops. When no single Dubins word fits, the vehicle
10
+ // either swings out wide and comes back (two smooth turns), or transits
11
+ // through the free space: shortest path over a visibility graph of
12
+ // free-space corners, then a chain of Dubins hops along it.
13
+
14
+ const CHECK_STEP_M = 0.25;
15
+ const OUTPUT_STEP_M = 0.1; // same point density the vehicle already gets on turns
16
+ const NODE_SIMPLIFY_TOLERANCE_DEG = 0.000004; // ~0.4m, keeps the graph small
17
+ const TWO_HOP_RADII = [1.5, 2.5, 4, 5]; // intermediate poses this many turning radii out
18
+ const TWO_HOP_BEARINGS = 12;
19
+ const TWO_HOP_HEADINGS = 8;
20
+ const TWO_HOP_CHECKS = 60;
21
+ const ESCAPE_RADII = [4, 5]; // far enough that reaching it means actually leaving a pocket
22
+ const ESCAPE_CHECKS = 40;
23
+
24
+ const pose = (x, y, th) => ({ x, y, th });
25
+
26
+
27
+ // No loops: a single manoeuvre may turn at most a U-turn plus a little
28
+ // (enough for a U-turn between rows whose ends are not level). Anything more
29
+ // is a circle/loop, which the operator does not want.
30
+ const MAX_TURN_RAD = Math.PI + 0.35;
31
+ const L_SEG = 0;
32
+ const S_SEG = 1;
33
+ const turnOf = (word) => word.params.reduce((sum, value, i) => (word.types[i] === S_SEG ? sum : sum + value), 0);
34
+
35
+ // No semicircles either: a U-turn must be quarter arc, straight, quarter
36
+ // arc. A single arc this long only appears in a bare semicircle U-turn
37
+ // (rows exactly one turn diameter apart) or a near-loop.
38
+ const MAX_SINGLE_ARC_RAD = (150 * Math.PI) / 180;
39
+ // Two same-way arcs read as one arc (a semicircle) unless a straight of at
40
+ // least this × R separates them — the same flat U-turn the row order plans.
41
+ const UTURN_STRAIGHT_FACTOR = 0.5;
42
+ // Longest same-way arc across one or more consecutive words (hops of one
43
+ // connection chain their arcs just like segments of one word do).
44
+ function longestArc(words) {
45
+ let longest = 0;
46
+ let run = 0;
47
+ let runType = null;
48
+ [].concat(words).forEach((word) => word.types.forEach((type, i) => {
49
+ const amount = word.params[i];
50
+ if (amount < 1e-9) return;
51
+ if (type === S_SEG) {
52
+ if (amount >= UTURN_STRAIGHT_FACTOR - 1e-6) {
53
+ run = 0;
54
+ runType = null;
55
+ }
56
+ return;
57
+ }
58
+ run = type === runType ? run + amount : amount;
59
+ runType = type;
60
+ longest = Math.max(longest, run);
61
+ }));
62
+ return longest;
63
+ }
64
+
65
+ // Number of U-turn sized turns in a chain: turning (either way) between
66
+ // straights of at least the flat-U-turn straight, totalling over 120°.
67
+ function uTurnCount(words) {
68
+ let count = 0;
69
+ let group = 0;
70
+ const close = () => {
71
+ if (group > U_TURN_SIZED_RAD) count += 1;
72
+ group = 0;
73
+ };
74
+ [].concat(words).forEach((word) => word.types.forEach((type, i) => {
75
+ const amount = word.params[i];
76
+ if (type === S_SEG) {
77
+ if (amount >= UTURN_STRAIGHT_FACTOR - 1e-6) close();
78
+ return;
79
+ }
80
+ group += amount;
81
+ }));
82
+ close();
83
+ return count;
84
+ }
85
+
86
+ // A chain of hops is acceptable when, taken as one manoeuvre, it neither
87
+ // loops, nor bends through a semicircle, nor swings out and back with two
88
+ // U-turns.
89
+ //
90
+ // `wrapping`: a lap going round an obstacle corner, where one long arc is the
91
+ // ring itself rather than a U-turn — only the no-loop limit applies.
92
+ const chainIsSmooth = (words, { wrapping = false } = {}) => longestTurn(words) <= MAX_TURN_RAD
93
+ && (wrapping || (longestArc(words) <= MAX_SINGLE_ARC_RAD && uTurnCount(words) <= 1));
94
+
95
+ // Dubins words between two poses, shortest first, without loops or (unless
96
+ // `wrapping`, see chainIsSmooth) semicircles.
97
+ function smoothWords(from, to, radius, { wrapping = false } = {}) {
98
+ return dubinsCandidates(from, to, radius)
99
+ .filter((word) => turnOf(word) <= MAX_TURN_RAD && (wrapping || longestArc(word) <= MAX_SINGLE_ARC_RAD));
100
+ }
101
+
102
+ // A turn this big counts as a U-turn; two in one connection is a swing out
103
+ // and back, which the operator does not want.
104
+ const U_TURN_SIZED_RAD = (120 * Math.PI) / 180;
105
+
106
+ // Longest continuous same-direction turn across consecutive words (a hop
107
+ // ending in a left arc followed by one starting with a left arc is one turn).
108
+ // Two loop-free U-turns back to back the same way are still a full circle.
109
+ function longestTurn(words) {
110
+ let longest = 0;
111
+ let run = 0;
112
+ words.forEach((word) => word.types.forEach((type, i) => {
113
+ const amount = word.params[i];
114
+ if (amount < 1e-9) return;
115
+ if (type === S_SEG) {
116
+ run = 0;
117
+ return;
118
+ }
119
+ const signed = type === L_SEG ? amount : -amount;
120
+ run = Math.sign(run) === Math.sign(signed) ? run + signed : signed;
121
+ longest = Math.max(longest, Math.abs(run));
122
+ }));
123
+ return longest;
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
+
194
+ class PathPlanner {
195
+ constructor({ driveArea, driveFeature, toLocal, radius }) {
196
+ this.driveArea = driveArea;
197
+ this.driveFeature = driveFeature;
198
+ this.toLocal = toLocal;
199
+ this.radius = radius;
200
+ this.onFreeGround = (x, y) => this.driveArea.contains(x, y);
201
+ this.graphs = new Map();
202
+ // Larger margins first: waypoints further from obstacles leave the Dubins
203
+ // hops room to turn; smaller ones still get through narrow passages.
204
+ this.margins = [...new Set([radius, radius / 2, 2, 1].map((m) => Math.max(0.5, m)))];
205
+ }
206
+
207
+ // Shortest loop-free Dubins word that stays inside the drive area, or null.
208
+ direct(from, to) {
209
+ return this.directAt(from, to, this.radius);
210
+ }
211
+
212
+ directAt(from, to, radius) {
213
+ for (const word of smoothWords(from, to, radius)) {
214
+ if (this.driveArea.containsAll(sampleDubins(word, CHECK_STEP_M))) {
215
+ return { points: sampleDubins(word, OUTPUT_STEP_M), length: word.length, words: [word] };
216
+ }
217
+ }
218
+ return null;
219
+ }
220
+
221
+ connect(from, to) {
222
+ return this.direct(from, to) || this.transit(from, to);
223
+ }
224
+
225
+ transit(from, to) {
226
+ const turnaround = this.twoHop(from, to);
227
+ if (turnaround && !hasCircle(turnaround.points, this.radius, this.onFreeGround)) return turnaround;
228
+ for (const margin of this.margins) {
229
+ const graph = this.graph(margin);
230
+ if (!graph) continue;
231
+ const waypoints = this.shortestPath(graph, [from.x, from.y], [to.x, to.y]);
232
+ if (!waypoints || waypoints.length === 0) continue;
233
+ const result = this.followWaypoints(from, waypoints, to);
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;
238
+ }
239
+ return null;
240
+ }
241
+
242
+ // Target the shortest smooth turn cannot reach (it would leave the drive
243
+ // area, or needs more than one manoeuvre's worth of turning — e.g. onto
244
+ // the perpendicular rows of a criss-cross pass): detour through an
245
+ // intermediate pose. At most one of the two hops may be a U-turn — no
246
+ // swinging out with a U-turn and back with another. Candidates are ranked
247
+ // by unchecked length and only the best few are validated.
248
+ twoHop(from, to) {
249
+ const candidates = [];
250
+ const centres = [[from.x, from.y], [(from.x + to.x) / 2, (from.y + to.y) / 2], [to.x, to.y]];
251
+ centres.forEach(([cx, cy]) => {
252
+ TWO_HOP_RADII.forEach((k) => {
253
+ for (let b = 0; b < TWO_HOP_BEARINGS; b += 1) {
254
+ const angle = (2 * Math.PI * b) / TWO_HOP_BEARINGS;
255
+ const x = cx + k * this.radius * Math.cos(angle);
256
+ const y = cy + k * this.radius * Math.sin(angle);
257
+ if (!this.driveArea.contains(x, y)) continue;
258
+ for (let h = 0; h < TWO_HOP_HEADINGS; h += 1) {
259
+ const mid = pose(x, y, (2 * Math.PI * h) / TWO_HOP_HEADINGS);
260
+ const first = smoothWords(from, mid, this.radius)[0];
261
+ if (!first) continue;
262
+ const second = smoothWords(mid, to, this.radius)[0];
263
+ if (!second || !chainIsSmooth([first, second])) continue;
264
+ candidates.push({ mid, length: first.length + second.length });
265
+ }
266
+ }
267
+ });
268
+ });
269
+ candidates.sort((a, b) => a.length - b.length);
270
+ for (const { mid } of candidates.slice(0, TWO_HOP_CHECKS)) {
271
+ const first = this.directAt(from, mid, this.radius);
272
+ if (!first) continue;
273
+ const second = this.directAt(mid, to, this.radius);
274
+ if (!second || !chainIsSmooth([...first.words, ...second.words])) continue;
275
+ return { points: [...first.points, ...second.points.slice(1)], length: first.length + second.length, words: [...first.words, ...second.words] };
276
+ }
277
+ return null;
278
+ }
279
+
280
+ // True when some smooth, valid manoeuvre leads away from `from` — i.e. the
281
+ // vehicle is not stuck facing a wall in a pocket too narrow to turn in.
282
+ // `radii`: how far out (in turning radii) the manoeuvre must get.
283
+ canEscape(from, radii = ESCAPE_RADII) {
284
+ const candidates = [];
285
+ radii.forEach((k) => {
286
+ for (let b = 0; b < TWO_HOP_BEARINGS; b += 1) {
287
+ const angle = (2 * Math.PI * b) / TWO_HOP_BEARINGS;
288
+ const x = from.x + k * this.radius * Math.cos(angle);
289
+ const y = from.y + k * this.radius * Math.sin(angle);
290
+ if (!this.driveArea.contains(x, y)) continue;
291
+ for (let h = 0; h < TWO_HOP_HEADINGS; h += 1) {
292
+ const target = pose(x, y, (2 * Math.PI * h) / TWO_HOP_HEADINGS);
293
+ const word = smoothWords(from, target, this.radius)[0];
294
+ if (word) candidates.push({ target, length: word.length });
295
+ }
296
+ }
297
+ });
298
+ candidates.sort((a, b) => a.length - b.length);
299
+ return candidates.slice(0, ESCAPE_CHECKS).some(({ target }) => this.directAt(from, target, this.radius));
300
+ }
301
+
302
+ graph(margin) {
303
+ if (this.graphs.has(margin)) return this.graphs.get(margin);
304
+ let graph = null;
305
+ try {
306
+ const shrunk = bufferMeters(this.driveFeature, -margin);
307
+ if (shrunk) {
308
+ const simplified = turf.simplify(shrunk, { tolerance: NODE_SIMPLIFY_TOLERANCE_DEG });
309
+ const nodes = freeSpaceReflexVertices(areaFromGeoJSON(simplified, this.toLocal))
310
+ .filter(([x, y]) => this.driveArea.contains(x, y));
311
+ graph = { nodes, adjacency: new Map() };
312
+ }
313
+ } catch (err) {
314
+ console.warn(`Transit graph unavailable at ${margin} m margin:`, err.message);
315
+ }
316
+ this.graphs.set(margin, graph);
317
+ return graph;
318
+ }
319
+
320
+ neighbours(graph, index) {
321
+ if (!graph.adjacency.has(index)) {
322
+ const a = graph.nodes[index];
323
+ const list = [];
324
+ graph.nodes.forEach((b, j) => {
325
+ if (j !== index && this.driveArea.segmentClear(a, b)) list.push(j);
326
+ });
327
+ graph.adjacency.set(index, list);
328
+ }
329
+ return graph.adjacency.get(index);
330
+ }
331
+
332
+ // A* over the visibility graph; returns the intermediate corner points
333
+ // (start and goal excluded), or null when the goal is unreachable.
334
+ shortestPath(graph, start, goal) {
335
+ const { nodes } = graph;
336
+ const START = nodes.length;
337
+ const GOAL = nodes.length + 1;
338
+ const point = (i) => (i === START ? start : i === GOAL ? goal : nodes[i]);
339
+ const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
340
+
341
+ // Checked only for the nodes the search actually expands.
342
+ const goalVisible = new Map();
343
+ const seesGoal = (j) => {
344
+ if (!goalVisible.has(j)) goalVisible.set(j, this.driveArea.segmentClear(nodes[j], goal));
345
+ return goalVisible.get(j);
346
+ };
347
+ const edgesOf = (i) => {
348
+ if (i === START) {
349
+ const list = [];
350
+ nodes.forEach((n, j) => {
351
+ if (this.driveArea.segmentClear(start, n)) list.push(j);
352
+ });
353
+ if (this.driveArea.segmentClear(start, goal)) list.push(GOAL);
354
+ return list;
355
+ }
356
+ const list = this.neighbours(graph, i);
357
+ return seesGoal(i) ? [...list, GOAL] : list;
358
+ };
359
+
360
+ const g = new Map([[START, 0]]);
361
+ const parent = new Map();
362
+ const open = new Set([START]);
363
+ const closed = new Set();
364
+ while (open.size) {
365
+ let current = null;
366
+ let best = Infinity;
367
+ open.forEach((i) => {
368
+ const f = g.get(i) + dist(point(i), goal);
369
+ if (f < best) {
370
+ best = f;
371
+ current = i;
372
+ }
373
+ });
374
+ if (current === GOAL) {
375
+ const path = [];
376
+ for (let i = parent.get(GOAL); i !== START; i = parent.get(i)) path.unshift(nodes[i]);
377
+ return path;
378
+ }
379
+ open.delete(current);
380
+ closed.add(current);
381
+ for (const j of edgesOf(current)) {
382
+ if (closed.has(j)) continue;
383
+ const cost = g.get(current) + dist(point(current), point(j));
384
+ if (cost < (g.has(j) ? g.get(j) : Infinity)) {
385
+ g.set(j, cost);
386
+ parent.set(j, current);
387
+ open.add(j);
388
+ }
389
+ }
390
+ }
391
+ return null;
392
+ }
393
+
394
+ // Dubins hops along the waypoints, each waypoint passed with the heading
395
+ // bisecting its incoming and outgoing legs. Greedily skips ahead to the
396
+ // furthest pose a single valid hop can reach, so the result is as smooth
397
+ // as the free space allows.
398
+ followWaypoints(from, waypoints, to) {
399
+ const chain = [[from.x, from.y], ...waypoints, [to.x, to.y]];
400
+ const targets = waypoints.map((w, i) => {
401
+ const prev = chain[i];
402
+ const next = chain[i + 2];
403
+ const inA = Math.atan2(w[1] - prev[1], w[0] - prev[0]);
404
+ const outA = Math.atan2(next[1] - w[1], next[0] - w[0]);
405
+ const sx = Math.cos(inA) + Math.cos(outA);
406
+ const sy = Math.sin(inA) + Math.sin(outA);
407
+ const th = Math.hypot(sx, sy) < 1e-6 ? inA : Math.atan2(sy, sx);
408
+ return pose(w[0], w[1], th);
409
+ });
410
+ targets.push(to);
411
+
412
+ const points = [[from.x, from.y]];
413
+ const words = [];
414
+ let length = 0;
415
+ let current = from;
416
+ let index = 0;
417
+ while (index < targets.length) {
418
+ let hop = null;
419
+ let reached = -1;
420
+ for (let j = targets.length - 1; j >= index; j -= 1) {
421
+ const candidate = this.directAt(current, targets[j], this.radius);
422
+ if (candidate && chainIsSmooth([...words, ...candidate.words])) {
423
+ hop = candidate;
424
+ reached = j;
425
+ break;
426
+ }
427
+ }
428
+ if (!hop) return null;
429
+ points.push(...hop.points.slice(1));
430
+ words.push(...hop.words);
431
+ length += hop.length;
432
+ current = targets[reached];
433
+ index = reached + 1;
434
+ }
435
+ return { points, length, words };
436
+ }
437
+ }
438
+
439
+ module.exports = { hasCircle, PathPlanner, pose, smoothWords, chainIsSmooth, UTURN_STRAIGHT_FACTOR };
@@ -0,0 +1,56 @@
1
+ // Swath order inside one cell — the F2C rp::CustomOrder slot, filled with a
2
+ // leapfrog skip pattern.
3
+ //
4
+ // k is the smallest jump whose *backward* step (k-1 rows) still leaves room
5
+ // for a flat U-turn: quarter arc, a straight of UTURN_STRAIGHT_FACTOR × R,
6
+ // quarter arc — never a bare semicircle, and never a loop. (With
7
+ // k = floor(2R/spacing) the backward step was narrower than 2R and every
8
+ // second turn became a loop.)
9
+ const { UTURN_STRAIGHT_FACTOR } = require('./pathPlanner'); // R=6: 3 m straight across the U-turn
10
+
11
+ function rowSkip(spacing, minTurnRadius) {
12
+ const turnWidth = (2 + UTURN_STRAIGHT_FACTOR) * minTurnRadius;
13
+ return Math.max(1, Math.ceil(turnWidth / spacing - 1e-9) + 1);
14
+ }
15
+
16
+ const generateCustomOrder = (totalSwaths, spacing, minTurnRadius) => {
17
+ if (totalSwaths <= 0) return [];
18
+ const k = rowSkip(spacing, minTurnRadius);
19
+ const customOrder = [];
20
+ const swathsPerCircuit = 2 * k;
21
+ const numCircuits = Math.floor(totalSwaths / swathsPerCircuit);
22
+ const remainingSwaths = totalSwaths % swathsPerCircuit;
23
+ const circuits = [];
24
+ for (let i = 0; i < numCircuits; i++) {
25
+ circuits.push(i === 0 ? swathsPerCircuit + remainingSwaths : swathsPerCircuit);
26
+ }
27
+ if (circuits.length === 0) circuits.push(totalSwaths);
28
+
29
+ let swathCounter = 1; // 1-based start index of the current circuit
30
+ for (let c = 0; c < circuits.length; c++) {
31
+ const circuitSwaths = circuits[c];
32
+ if (c === 0) {
33
+ // First circuit (absorbs the remainder): pair row i with row i+skip.
34
+ const skip = circuitSwaths % 2 === 0 ? circuitSwaths / 2 : Math.floor(circuitSwaths / 2) + 1;
35
+ for (let i = 1; i <= skip; i++) {
36
+ const a = i;
37
+ const b = i + skip;
38
+ if (a <= circuitSwaths) customOrder.push(swathCounter + a - 1);
39
+ if (b <= circuitSwaths) customOrder.push(swathCounter + b - 1);
40
+ }
41
+ } else {
42
+ // Later circuits: start on the high half, then interleave.
43
+ const skip = Math.floor(circuitSwaths / 2);
44
+ for (let i = 0; i < skip; i++) {
45
+ const high = skip + i;
46
+ const low = i;
47
+ if (high < circuitSwaths) customOrder.push(swathCounter + high);
48
+ if (low < circuitSwaths) customOrder.push(swathCounter + low);
49
+ }
50
+ }
51
+ swathCounter += circuitSwaths;
52
+ }
53
+ return customOrder.map((v) => v - 1); // 0-based
54
+ };
55
+
56
+ module.exports = { generateCustomOrder, rowSkip };
package/lib/swaths.js ADDED
@@ -0,0 +1,46 @@
1
+ // Port of Fields2Cover's sg (swath generator) for a fixed angle: parallel
2
+ // swaths one coverage width apart, clipped to the mainland. The angle comes
3
+ // from the user's reference line rather than F2C's brute-force angle search,
4
+ // so the operator keeps control of the mowing direction.
5
+ //
6
+ // Output is per column (one column per swath line u = const), each with the
7
+ // inside intervals [v0, v1] where that line crosses the mainland — a column
8
+ // has several intervals wherever an obstacle or a concave notch cuts it.
9
+ function generateSwathColumns(area, swathFrame, spacing, minLength) {
10
+ const rings = area.polygons.flat().map((ring) => ring.map(swathFrame.toUV));
11
+ let uMin = Infinity;
12
+ let uMax = -Infinity;
13
+ rings.forEach((ring) => ring.forEach(([u]) => {
14
+ if (u < uMin) uMin = u;
15
+ if (u > uMax) uMax = u;
16
+ }));
17
+ const width = uMax - uMin;
18
+ if (!Number.isFinite(width) || width <= 0) return [];
19
+
20
+ // Centre the swaths across the mainland so both outer swaths sit the same
21
+ // distance inside its edges (at most half a coverage width).
22
+ const count = Math.max(1, Math.ceil(width / spacing - 1e-9));
23
+ const first = uMin + (width - (count - 1) * spacing) / 2;
24
+
25
+ const columns = [];
26
+ for (let c = 0; c < count; c += 1) {
27
+ const u = first + c * spacing;
28
+ const crossings = [];
29
+ rings.forEach((ring) => {
30
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
31
+ const [ua, va] = ring[j];
32
+ const [ub, vb] = ring[i];
33
+ if ((ua <= u) !== (ub <= u)) crossings.push(va + ((u - ua) * (vb - va)) / (ub - ua));
34
+ }
35
+ });
36
+ crossings.sort((a, b) => a - b);
37
+ const intervals = [];
38
+ for (let k = 0; k + 1 < crossings.length; k += 2) {
39
+ if (crossings[k + 1] - crossings[k] >= minLength) intervals.push([crossings[k], crossings[k + 1]]);
40
+ }
41
+ columns.push({ u, intervals });
42
+ }
43
+ return columns;
44
+ }
45
+
46
+ module.exports = { generateSwathColumns };
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@anandommi/fields2cover",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Pure-JavaScript Fields2Cover-style coverage path planner for mowers: headlands, boustrophedon cells, swaths, Dubins turns and headland laps on GeoJSON fields.",
5
+ "main": "index.js",
6
+ "files": [
7
+ "index.js",
8
+ "index.d.ts",
9
+ "lib/",
10
+ "LICENSE",
11
+ "README.md",
12
+ "CHANGELOG.md"
13
+ ],
14
+ "scripts": {
15
+ "test": "node test/smoke.js",
16
+ "prepublishOnly": "npm test"
17
+ },
18
+ "keywords": [
19
+ "fields2cover",
20
+ "coverage-path-planning",
21
+ "boustrophedon",
22
+ "dubins",
23
+ "mower",
24
+ "geojson",
25
+ "turf"
26
+ ],
27
+ "license": "BSD-3-Clause",
28
+ "engines": {
29
+ "node": ">=18"
30
+ },
31
+ "dependencies": {
32
+ "@turf/turf": "^7.2.0"
33
+ },
34
+ "author": "Anand (https://github.com/AnandOmmi)",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/AnandOmmi/fields2cover.git"
38
+ },
39
+ "homepage": "https://github.com/AnandOmmi/fields2cover#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/AnandOmmi/fields2cover/issues"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "types": "index.d.ts"
47
+ }