@indispec/fs-compat 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,923 @@
1
+ /**
2
+ * regions.js — sketch entities → **closed 2D regions** (outer contour + holes).
3
+ *
4
+ * This is the engine's first piece of *topology*. Before it, a sketch was a
5
+ * bag of disconnected profiles and `opExtrude` simply unioned them: two
6
+ * concentric circles made a disc, a rectangle with a round pocket in it made a
7
+ * solid block, and a profile could not be chained out of more than one kind of
8
+ * entity. That is the 2D shadow of the same problem a mesh kernel has when it
9
+ * cannot represent a face with an inner loop.
10
+ *
11
+ * A real CAD sketch (and every B-rep kernel's face loop set) is different: open
12
+ * entities — line segments and circular arcs — chain *end to end* into closed
13
+ * contours, contours nest, and nesting has **parity**:
14
+ *
15
+ * depth 0 → material (outer boundary of a region)
16
+ * depth 1 → a hole in it (the face's inner loop)
17
+ * depth 2 → an island inside the hole (a new region)
18
+ *
19
+ * `nestProfiles` recovers that hierarchy from the sketch's profiles, and
20
+ * `opExtrude` turns each region into the exact CSG it means:
21
+ * `Outer − holes` (a `Diff` of two `Prism`s), with islands as further regions.
22
+ * No new solid node types and no changes to the emitters are needed — the
23
+ * boolean representation is already exact, and every renderer path (ray
24
+ * marcher, display-mesh clip shaders, CPU bake, clash SDF) already understands
25
+ * `Diff`. The topology lives where it belongs: in the sketch.
26
+ *
27
+ * **Overlapping contours** are the other half of the face model. A real sketch
28
+ * (Onshape included) is a *planar arrangement*: every contour is a boundary,
29
+ * boundaries that cross each other are split at their intersections, and every
30
+ * disjoint cell of the resulting subdivision is a face. Two overlapping
31
+ * rectangles therefore bound **three** faces — each rectangle alone and their
32
+ * overlap — not two. {@link sketchRegions} derives those cells with
33
+ * {@link arrangementFaces}: it splits every segment at crossings / T-junctions /
34
+ * collinear overlaps, walks the planar graph into loops (left-hand face
35
+ * traversal), pairs each loop with the loops directly enclosed as holes, and
36
+ * hands back the same `{ outer, holes, depth }` faces the nesting path returns.
37
+ * Sketches whose boundaries never overlap keep the exact, unsampled nesting
38
+ * path (`Circle2`/`Rect2` profiles stay analytic); the arrangement only runs
39
+ * when a segment actually needs splitting, and loops that are a whole untouched
40
+ * contour are handed back as that contour's own profile.
41
+ *
42
+ * The module is pure (no interpreter, no scene): it takes profiles in and gives
43
+ * plain point arrays / region descriptors out, so it can be unit-tested in
44
+ * Node and reused by any other sketch consumer.
45
+ */
46
+
47
+ import { Circle2, Poly2, Rect2 } from './csg.js'
48
+
49
+ const TAU = Math.PI * 2
50
+
51
+ /** How close two segment ends must be to be considered the same point (mm). */
52
+ export const JOIN_TOL = 1e-3
53
+
54
+ /** Max chord error when sampling an arc (mm). Matches the mesh chord order. */
55
+ export const ARC_CHORD_TOL = 0.35
56
+
57
+ const dist2d = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1])
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // arcs
61
+ // ---------------------------------------------------------------------------
62
+
63
+ /**
64
+ * Sample a circular arc (centre `c`, radius `r`, start angle `a0`, signed sweep
65
+ * in radians) into points, inclusive of both ends. The sample count comes from
66
+ * a chord tolerance, so a small fillet stays cheap and a large radius does not
67
+ * facet visibly.
68
+ */
69
+ export function arcPoints(c, r, a0, sweep) {
70
+ const first = [c[0] + r * Math.cos(a0), c[1] + r * Math.sin(a0)]
71
+ const span = Math.abs(sweep)
72
+ if (span < 1e-12 || r <= 0) return [first]
73
+ // sagitta of a chord subtending dθ is r(1−cos(dθ/2)); solve for dθ
74
+ const ratio = Math.max(-1, Math.min(1, 1 - ARC_CHORD_TOL / r))
75
+ const maxStep = 2 * Math.acos(ratio)
76
+ const n = Math.max(2, Math.min(512, Math.ceil(span / Math.max(maxStep, 1e-6))))
77
+ const out = [first]
78
+ for (let i = 1; i <= n; i++) {
79
+ const th = a0 + sweep * (i / n)
80
+ out.push([c[0] + r * Math.cos(th), c[1] + r * Math.sin(th)])
81
+ }
82
+ // exact endpoint when the caller gave us one, so chaining closes cleanly
83
+ const end = [c[0] + r * Math.cos(a0 + sweep), c[1] + r * Math.sin(a0 + sweep)]
84
+ out[out.length - 1] = end
85
+ return out
86
+ }
87
+
88
+ /**
89
+ * Chain open segments (each `{ pts: [[x,y], ...] }`, a line or a sampled arc)
90
+ * into closed contours. Segments may be given in any order and either
91
+ * orientation: the contour is built by matching endpoints within `tol`.
92
+ *
93
+ * Returns `{ contours, open }` — `contours` are closed point loops with the
94
+ * duplicated closing point removed, `open` is the leftover chains (a sketch
95
+ * with an open wire, which the legacy single-profile path still extrudes
96
+ * implicitly closed).
97
+ */
98
+ export function chainContours(segments, tol = JOIN_TOL) {
99
+ const used = new Array(segments.length).fill(false)
100
+ const contours = []
101
+ const open = []
102
+ for (let s = 0; s < segments.length; s++) {
103
+ if (used[s]) continue
104
+ used[s] = true
105
+ const pts = segments[s].pts.map((p) => [p[0], p[1]])
106
+ let closed = false
107
+ for (;;) {
108
+ const last = pts[pts.length - 1]
109
+ if (pts.length > 3 && dist2d(pts[0], last) <= tol) { closed = true; break }
110
+ let found = -1
111
+ let reversed = false
112
+ for (let k = 0; k < segments.length; k++) {
113
+ if (used[k]) continue
114
+ const q = segments[k].pts
115
+ if (dist2d(q[0], last) <= tol) { found = k; break }
116
+ if (dist2d(q[q.length - 1], last) <= tol) { found = k; reversed = true; break }
117
+ }
118
+ if (found < 0) break
119
+ used[found] = true
120
+ const q = segments[found].pts
121
+ const add = reversed ? [...q].reverse() : q
122
+ for (let i = 1; i < add.length; i++) pts.push([add[i][0], add[i][1]])
123
+ }
124
+ if (!closed && pts.length > 3 && dist2d(pts[0], pts[pts.length - 1]) <= tol) closed = true
125
+ if (closed) {
126
+ if (dist2d(pts[0], pts[pts.length - 1]) <= tol) pts.pop()
127
+ if (pts.length >= 3) { contours.push(pts); continue }
128
+ }
129
+ open.push(pts)
130
+ }
131
+ return { contours, open }
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // polygons
136
+ // ---------------------------------------------------------------------------
137
+
138
+ export function polygonArea(pts) {
139
+ let a = 0
140
+ for (let i = 0; i < pts.length; i++) {
141
+ const j = (i + 1) % pts.length
142
+ a += pts[i][0] * pts[j][1] - pts[j][0] * pts[i][1]
143
+ }
144
+ return a / 2
145
+ }
146
+
147
+ /** Counter-clockwise copy of a point loop (outer contours are stored CCW). */
148
+ export function toCCW(pts) {
149
+ return polygonArea(pts) < 0 ? [...pts].reverse() : pts
150
+ }
151
+
152
+ /** Ray-cast point-in-polygon test; boundary behaviour is "inside". */
153
+ export function pointInPolygon(p, pts) {
154
+ let inside = false
155
+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
156
+ const [xi, yi] = pts[i]
157
+ const [xj, yj] = pts[j]
158
+ const crosses = (yi > p[1]) !== (yj > p[1])
159
+ if (crosses && p[0] < (xj - xi) * (p[1] - yi) / ((yj - yi) || 1e-12) + xi) {
160
+ inside = !inside
161
+ }
162
+ }
163
+ return inside
164
+ }
165
+
166
+ /**
167
+ * A point that is strictly inside a simple polygon: the centroid of the first
168
+ * convex corner that is actually inside (a convex corner is not automatically
169
+ * an ear in a concave polygon). Falls back to the vertex average.
170
+ */
171
+ export function interiorPoint(pts) {
172
+ const n = pts.length
173
+ for (let i = 0; i < n; i++) {
174
+ const a = pts[(i + n - 1) % n]
175
+ const b = pts[i]
176
+ const c = pts[(i + 1) % n]
177
+ const cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
178
+ if (cross <= 0) continue // reflex corner on a CCW loop
179
+ const m = [(a[0] + b[0] + c[0]) / 3, (a[1] + b[1] + c[1]) / 3]
180
+ if (pointInPolygon(m, pts)) return m
181
+ }
182
+ let x = 0
183
+ let y = 0
184
+ for (const p of pts) { x += p[0]; y += p[1] }
185
+ return [x / n, y / n]
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // profiles
190
+ // ---------------------------------------------------------------------------
191
+
192
+ /** The profile as a point loop, for containment tests (a circle is sampled). */
193
+ export function profilePolygon(pr, circleSegs = 32) {
194
+ if (pr instanceof Rect2) {
195
+ return [[pr.lo[0], pr.lo[1]], [pr.hi[0], pr.lo[1]],
196
+ [pr.hi[0], pr.hi[1]], [pr.lo[0], pr.hi[1]]]
197
+ }
198
+ if (pr instanceof Circle2) {
199
+ const out = []
200
+ for (let i = 0; i < circleSegs; i++) {
201
+ const th = (i / circleSegs) * TAU
202
+ out.push([pr.c[0] + pr.r * Math.cos(th), pr.c[1] + pr.r * Math.sin(th)])
203
+ }
204
+ return out
205
+ }
206
+ if (pr instanceof Poly2) return pr.pts.map((p) => [p[0], p[1]])
207
+ throw new TypeError(`regions: unsupported profile ${pr?.constructor?.name}`)
208
+ }
209
+
210
+ /** A point strictly inside the profile, for nesting tests. */
211
+ export function profileSample(pr) {
212
+ if (pr instanceof Rect2) return [(pr.lo[0] + pr.hi[0]) / 2, (pr.lo[1] + pr.hi[1]) / 2]
213
+ if (pr instanceof Circle2) return [pr.c[0], pr.c[1]]
214
+ if (pr instanceof Poly2) return interiorPoint(pr.pts)
215
+ throw new TypeError(`regions: unsupported profile ${pr?.constructor?.name}`)
216
+ }
217
+
218
+ export function profileContains(pr, p) {
219
+ if (pr instanceof Rect2) {
220
+ return p[0] >= pr.lo[0] && p[0] <= pr.hi[0] && p[1] >= pr.lo[1] && p[1] <= pr.hi[1]
221
+ }
222
+ if (pr instanceof Circle2) return dist2d(pr.c, p) <= pr.r
223
+ if (pr instanceof Poly2) return pointInPolygon(p, pr.pts)
224
+ throw new TypeError(`regions: unsupported profile ${pr?.constructor?.name}`)
225
+ }
226
+
227
+ /**
228
+ * Recover the region hierarchy from a sketch's profiles.
229
+ *
230
+ * Returns one entry per *material* region (even nesting depth):
231
+ *
232
+ * { outer, holes, depth }
233
+ *
234
+ * `outer` and each of `holes` are the profiles passed in; `depth` is the
235
+ * nesting depth of `outer` (0 normally, 2+ for islands inside a hole).
236
+ *
237
+ * Containment is "every vertex of A lies inside B", not "a point of A does":
238
+ * concentric shapes share their centre, so a centre-point test would make
239
+ * nested circles contain each other. Ties (coincident profiles) are broken by
240
+ * area and then by the order they were added, so the hierarchy is total.
241
+ *
242
+ * Profile order is preserved — the extrude emitter's output stays
243
+ * byte-identical for sketches that have no nesting at all.
244
+ */
245
+ export function nestProfiles(profiles) {
246
+ const { list, depth, parent } = nestingInfo(profiles)
247
+ const regions = []
248
+ list.forEach((a, i) => {
249
+ if (depth[i] % 2 !== 0) return // a hole, consumed below
250
+ const holes = []
251
+ list.forEach((b, j) => {
252
+ if (depth[j] === depth[i] + 1 && parent[j] === i) holes.push(b)
253
+ })
254
+ regions.push({ outer: a, holes, depth: depth[i] })
255
+ })
256
+ return regions
257
+ }
258
+
259
+ /**
260
+ * One **face** of a sketch: an outer boundary loop and the loops directly inside it.
261
+ *
262
+ * This is the region model of a real CAD sketch / a B-rep face's loop set.
263
+ * Unlike {@link nestProfiles} (which keeps only the even-depth *material*
264
+ * regions), every contour bounds a face: two concentric circles are two
265
+ * faces — the ring between them and the disc inside it. That is what lets a
266
+ * user extrude "the face in between" and, separately, the inner disc.
267
+ *
268
+ * **Overlapping contours split each other** (the Onshape behaviour): the faces
269
+ * are the cells of the sketch's planar arrangement, so two overlapping
270
+ * rectangles are three faces — each rectangle alone and the overlap — and a
271
+ * contour nested in a cell becomes a hole in it. See {@link arrangementFaces};
272
+ * a sketch whose boundaries never overlap keeps the exact nesting path below,
273
+ * so analytic circles/rectangles are not sampled.
274
+ *
275
+ * Ordering is canonical and deterministic — outer faces before their holes,
276
+ * then larger face first, then a stable point order — so
277
+ * `qNthElement(qCreatedBy(sketch, EntityType.FACE), i)` addresses
278
+ * `sketchRegions(...)[i]` and the editor's region picker and the generated
279
+ * query agree on which face is "Region 1".
280
+ *
281
+ * @param {Array} profiles Sketch profiles (`Circle2` | `Rect2` | `Poly2`).
282
+ * @returns {Array<{outer: unknown, holes: unknown[], depth: number}>} One entry per face.
283
+ */
284
+ export function sketchRegions(profiles) {
285
+ const arranged = arrangementFaces(profiles)
286
+ if (arranged) return arranged
287
+ const { list, depth, parent } = nestingInfo(profiles)
288
+ const order = list.map((_, i) => i).sort((a, b) => depth[a] - depth[b] || a - b)
289
+ return order.map((i) => {
290
+ const holes = []
291
+ list.forEach((b, j) => {
292
+ if (parent[j] === i) holes.push(b)
293
+ })
294
+ return { outer: list[i], holes, depth: depth[i] }
295
+ })
296
+ }
297
+
298
+ /**
299
+ * The region's net area (outer area minus its holes), in mm².
300
+ *
301
+ * @param {{outer: unknown, holes: unknown[]}} region Region from {@link sketchRegions}.
302
+ * @returns Area in mm².
303
+ */
304
+ export function regionArea(region) {
305
+ let area = Math.abs(polygonArea(profilePolygon(region.outer)))
306
+ for (const hole of region.holes) area -= Math.abs(polygonArea(profilePolygon(hole)))
307
+ return Math.max(0, area)
308
+ }
309
+
310
+ /**
311
+ * The region's boundaries as point loops, in sketch `(u, v)` millimetres.
312
+ *
313
+ * The outer loop is CCW; hole loops are CW (B-rep winding convention), so a
314
+ * renderer can draw them with an even-odd fill rule without reordering.
315
+ *
316
+ * @param {{outer: unknown, holes: unknown[]}} region Region from {@link sketchRegions}.
317
+ * @returns {{outer: number[][], holes: number[][][]}} Boundary loops.
318
+ */
319
+ export function regionPolygon(region) {
320
+ return {
321
+ outer: toCCW(profilePolygon(region.outer)),
322
+ holes: region.holes.map((hole) => [...toCCW(profilePolygon(hole))].reverse()),
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Whether a sketch-plane point lies inside the region (inside the outer contour,
328
+ * outside every hole).
329
+ *
330
+ * @param {{outer: unknown, holes: unknown[]}} region Region from {@link sketchRegions}.
331
+ * @param {number[]} point Sketch `(u, v)` point in millimetres.
332
+ * @returns True when the point is inside the face.
333
+ */
334
+ export function regionContains(region, point) {
335
+ if (!profileContains(region.outer, point)) return false
336
+ return !region.holes.some((hole) => profileContains(hole, point))
337
+ }
338
+
339
+ /**
340
+ * A point strictly inside the region, for labels, markers and click targets.
341
+ *
342
+ * A horizontal scanline is swept across the face (outer + hole crossings, even-odd parity) and the
343
+ * midpoint of the widest inside interval is returned. Unlike a corner centroid that is robust: it
344
+ * lands in the middle of an annulus or a concave arrangement cell — never in a hole and never within
345
+ * a chord of the boundary, which matters because the point is also the viewport's click target for
346
+ * the face. A simple convex contour still gets its centre.
347
+ *
348
+ * Falls back to the outer contour's convex-corner point only for a degenerate loop a scanline cannot
349
+ * split (a zero-height sliver).
350
+ *
351
+ * @param {{outer: unknown, holes: unknown[]}} region Region from {@link sketchRegions}.
352
+ * @returns {[number, number]} Sketch `(u, v)` millimetres.
353
+ */
354
+ export function regionInteriorPoint(region) {
355
+ const scanline = scanlineInteriorPoint(region)
356
+ if (scanline) return scanline
357
+ return interiorPoint(profilePolygon(region.outer))
358
+ }
359
+
360
+ /**
361
+ * The midpoint of the widest inside interval of a horizontal scanline across a region.
362
+ *
363
+ * Crossings of the outer contour and every hole are collected along the line, sorted, and read with
364
+ * the even-odd rule: odd-indexed intervals are inside the region (outside every hole). The widest
365
+ * such interval gives a point comfortably away from the boundary, which is what a label or a pick
366
+ * marker needs.
367
+ *
368
+ * @param {{outer: unknown, holes: unknown[]}} region Region from {@link sketchRegions}.
369
+ * @returns {[number, number] | null} Interior point, or null when no scanline found one.
370
+ */
371
+ function scanlineInteriorPoint(region) {
372
+ const loops = [profilePolygon(region.outer), ...region.holes.map((hole) => profilePolygon(hole))]
373
+ let lo = [Infinity, Infinity]
374
+ let hi = [-Infinity, -Infinity]
375
+ for (const point of loops[0]) {
376
+ lo = [Math.min(lo[0], point[0]), Math.min(lo[1], point[1])]
377
+ hi = [Math.max(hi[0], point[0]), Math.max(hi[1], point[1])]
378
+ }
379
+ // Several heights, so a scanline through a vertex row or a tab does not give up immediately.
380
+ for (const fraction of [0.5, 0.37, 0.63, 0.29, 0.71, 0.15, 0.85]) {
381
+ const y = lo[1] + (hi[1] - lo[1]) * fraction
382
+ const cuts = []
383
+ for (const loop of loops) {
384
+ for (let i = 0; i < loop.length; i++) {
385
+ const a = loop[i]
386
+ const b = loop[(i + 1) % loop.length]
387
+ if ((a[1] > y) === (b[1] > y)) continue
388
+ cuts.push(a[0] + ((y - a[1]) * (b[0] - a[0])) / (b[1] - a[1]))
389
+ }
390
+ }
391
+ cuts.sort((a, b) => a - b)
392
+ let best = null
393
+ let bestWidth = 0
394
+ for (let i = 0; i + 1 < cuts.length; i += 2) {
395
+ const width = cuts[i + 1] - cuts[i]
396
+ if (width > bestWidth) {
397
+ bestWidth = width
398
+ best = [(cuts[i] + cuts[i + 1]) / 2, y]
399
+ }
400
+ }
401
+ if (best && regionContains(region, best)) return best
402
+ }
403
+ return null
404
+ }
405
+
406
+ /**
407
+ * The nesting depth / parent hierarchy of a set of contours.
408
+ *
409
+ * Shared by {@link nestProfiles} (material regions) and {@link sketchRegions}
410
+ * (every face) so the two views of the same sketch can never disagree.
411
+ *
412
+ * @param {Array} profiles Sketch profiles.
413
+ * @returns {{list: Array, depth: number[], parent: number[]}} Hierarchy.
414
+ */
415
+ function nestingInfo(profiles) {
416
+ const info = profiles.map((pr) => ({ pr, poly: profilePolygon(pr) }))
417
+ const area = info.map((a) => Math.abs(polygonArea(a.poly)))
418
+ const encloses = (i, j) => j !== i
419
+ && info[j].poly.length >= 3
420
+ && info[i].poly.every((p) => profileContains(info[j].pr, p))
421
+ /** `j` is `i`'s container: mutual enclosure is broken by area, then order. */
422
+ const isContainer = (j, i) => {
423
+ if (!encloses(i, j)) return false
424
+ if (!encloses(j, i)) return true
425
+ return area[j] > area[i] + 1e-9 || (Math.abs(area[j] - area[i]) <= 1e-9 && j < i)
426
+ }
427
+ const depth = info.map((a, i) => info.filter((b, j) => isContainer(j, i)).length)
428
+ const parent = info.map((a, i) => {
429
+ let best = -1
430
+ let bestDepth = -1
431
+ info.forEach((b, j) => {
432
+ if (!isContainer(j, i)) return
433
+ if (depth[j] > bestDepth) { bestDepth = depth[j]; best = j }
434
+ })
435
+ return best
436
+ })
437
+ return { list: profiles, depth, parent }
438
+ }
439
+
440
+
441
+ // ---------------------------------------------------------------------------
442
+ // planar arrangement — overlapping contours bound extra faces
443
+ // ---------------------------------------------------------------------------
444
+
445
+ /**
446
+ * Chord tolerance used to sample circles **for the planar arrangement** (mm).
447
+ *
448
+ * Sketches whose boundaries never overlap keep their exact `Circle2`/`Rect2` profiles on the
449
+ * nesting path, so this only shapes circles that an overlapping contour actually cuts. It is finer
450
+ * than the chained-arc tolerance because a cut circle's arcs become polygon loop pieces in the
451
+ * extruded solid.
452
+ */
453
+ const ARRANGEMENT_CHORD_TOL = 0.05
454
+
455
+ /** Points (and computed intersections) closer than this are the same arrangement vertex (mm). */
456
+ const ARRANGEMENT_TOL = 1e-5
457
+
458
+ /** Faces with less area than this (mm²) are tangency artifacts, not regions. */
459
+ const ARRANGEMENT_MIN_AREA = 1e-6
460
+
461
+ /** Sampled-segment cap above which a sketch keeps the plain nesting face model. */
462
+ const ARRANGEMENT_MAX_SEGMENTS = 3000
463
+
464
+ /** Split-count cap above which a sketch keeps the plain nesting face model. */
465
+ const ARRANGEMENT_MAX_SPLITS = 4000
466
+
467
+ /**
468
+ * The cells of a sketch's planar arrangement, or null when no boundaries overlap.
469
+ *
470
+ * Onshape-style sketch regions are the faces of the planar subdivision: every closed contour is a
471
+ * boundary, boundaries that cross split each other at the intersection, and every disjoint cell is
472
+ * a face. Two overlapping rectangles therefore make **three** faces — each rectangle alone and
473
+ * their overlap — while two concentric circles keep the ring/disc faces of the nesting path.
474
+ *
475
+ * The algorithm is the standard planar-graph construction:
476
+ *
477
+ * 1. sample the contours (circles at {@link ARRANGEMENT_CHORD_TOL}), collect their segments and
478
+ * split each segment at crossings, T-junctions and collinear-overlap ends;
479
+ * 2. weld the split points into vertices and the pieces into a simple planar graph;
480
+ * 3. walk the half-edges left-hand-side-in (at each vertex take the edge just clockwise of the
481
+ * reverse edge), which yields every bounded face counter-clockwise and each component's outer
482
+ * boundary clockwise;
483
+ * 4. attach each clockwise loop to the smallest counter-clockwise loop strictly around it — that is
484
+ * the hole of the enclosing face (the annulus keeps the inner circle as its hole; a contour
485
+ * nested in one arrangement cell becomes that cell's hole);
486
+ * 5. hand back loops that are a whole untouched contour as that contour's own profile, so only the
487
+ * geometry an overlap actually cuts is sampled.
488
+ *
489
+ * Returns `null` as soon as no segment needs splitting (no boundary overlap at all), because the
490
+ * nesting path is exact, cheaper and keeps analytic circles.
491
+ *
492
+ * @param {Array} profiles Sketch profiles (`Circle2` | `Rect2` | `Poly2`).
493
+ * @returns {Array<{outer: unknown, holes: unknown[], depth: number}> | null} Arrangement faces, or
494
+ * null when nothing overlaps.
495
+ */
496
+ function arrangementFaces(profiles) {
497
+ // ---- sampled contours ---------------------------------------------------
498
+ const contours = []
499
+ for (const profile of profiles) {
500
+ const points = cleanLoop(arrangementLoop(profile))
501
+ if (points.length < 3) continue
502
+ contours.push({ profile, points, bounds: loopBounds(points), segments: [] })
503
+ }
504
+ if (!contours.length) return null
505
+ let segmentCount = 0
506
+ for (const contour of contours) {
507
+ for (let i = 0; i < contour.points.length; i++) {
508
+ const a = contour.points[i]
509
+ const b = contour.points[(i + 1) % contour.points.length]
510
+ contour.segments.push({ contour, a, b, bounds: segmentBounds(a, b), splits: [] })
511
+ }
512
+ segmentCount += contour.segments.length
513
+ }
514
+ if (segmentCount > ARRANGEMENT_MAX_SEGMENTS) return null
515
+
516
+ // ---- split every segment where a boundary overlaps another -------------
517
+ let splitCount = 0
518
+ for (let i = 0; i < contours.length; i++) {
519
+ const first = contours[i]
520
+ // A hand-drawn wire can cross itself.
521
+ for (let a = 0; a < first.segments.length; a++) {
522
+ const firstSegment = first.segments[a]
523
+ for (let b = a + 1; b < first.segments.length; b++) {
524
+ // Adjacent segments share a vertex by construction; they never need a split.
525
+ if (b === a + 1 || (a === 0 && b === first.segments.length - 1)) continue
526
+ const secondSegment = first.segments[b]
527
+ if (!boundsOverlap(firstSegment.bounds, secondSegment.bounds, ARRANGEMENT_TOL)) continue
528
+ splitCount += splitAtContacts(firstSegment, secondSegment)
529
+ if (splitCount > ARRANGEMENT_MAX_SPLITS) return null
530
+ }
531
+ }
532
+ for (let j = i + 1; j < contours.length; j++) {
533
+ const second = contours[j]
534
+ if (!boundsOverlap(first.bounds, second.bounds, 0)) continue
535
+ for (const firstSegment of first.segments) {
536
+ for (const secondSegment of second.segments) {
537
+ if (!boundsOverlap(firstSegment.bounds, secondSegment.bounds, 0)) continue
538
+ splitCount += splitAtContacts(firstSegment, secondSegment)
539
+ if (splitCount > ARRANGEMENT_MAX_SPLITS) return null
540
+ }
541
+ }
542
+ }
543
+ }
544
+ // No boundary overlaps: the exact nesting path is both correct and cheaper.
545
+ if (!splitCount) return null
546
+
547
+ // ---- planar graph: split pieces welded into vertices and simple edges --
548
+ const vertexIndex = new ArrangementPoints()
549
+ const edges = new Map()
550
+ /** Emit the sub-edges of one segment, split at its recorded points. */
551
+ const emit = (segment) => {
552
+ segment.splits.sort((a, b) => a.t - b.t)
553
+ let previous = vertexIndex.index(segment.a)
554
+ for (const split of segment.splits) {
555
+ const next = vertexIndex.index(split.point)
556
+ if (next === previous) continue
557
+ addArrangementEdge(edges, previous, next, segment.contour)
558
+ previous = next
559
+ }
560
+ const end = vertexIndex.index(segment.b)
561
+ if (end === previous) return
562
+ addArrangementEdge(edges, previous, end, segment.contour)
563
+ }
564
+ for (const contour of contours) for (const segment of contour.segments) emit(segment)
565
+ if (!edges.size) return null
566
+ const points = vertexIndex.points
567
+
568
+ // ---- half-edges: walk each face with the face on the left ---------------
569
+ const outgoing = Array.from({ length: points.length }, () => [])
570
+ const halfEdges = []
571
+ for (const edge of edges.values()) {
572
+ const forward = { from: edge.u, to: edge.v, contour: edge.contour, twin: halfEdges.length + 1 }
573
+ const backward = { from: edge.v, to: edge.u, contour: edge.contour, twin: halfEdges.length }
574
+ outgoing[edge.u].push(halfEdges.length)
575
+ outgoing[edge.v].push(halfEdges.length + 1)
576
+ halfEdges.push(forward, backward)
577
+ }
578
+ const angleOf = (index) => {
579
+ const half = halfEdges[index]
580
+ return Math.atan2(points[half.to][1] - points[half.from][1], points[half.to][0] - points[half.from][0])
581
+ }
582
+ const positionInRing = new Map()
583
+ for (const ring of outgoing) {
584
+ ring.sort((a, b) => angleOf(a) - angleOf(b) || halfEdges[a].to - halfEdges[b].to)
585
+ ring.forEach((index, position) => positionInRing.set(index, position))
586
+ }
587
+ /** At `half.to`, the next edge of the left-hand face is the one just clockwise of the reverse. */
588
+ const nextOf = new Array(halfEdges.length)
589
+ for (let index = 0; index < halfEdges.length; index++) {
590
+ const ring = outgoing[halfEdges[index].to]
591
+ const reverse = positionInRing.get(halfEdges[index].twin)
592
+ nextOf[index] = ring[(reverse - 1 + ring.length) % ring.length]
593
+ }
594
+
595
+ // ---- loops: bounded cells are CCW, each component's outer boundary CW --
596
+ const loops = []
597
+ const visited = new Uint8Array(halfEdges.length)
598
+ for (let start = 0; start < halfEdges.length; start++) {
599
+ if (visited[start]) continue
600
+ const cycle = []
601
+ let current = start
602
+ while (!visited[current] && cycle.length <= halfEdges.length) {
603
+ visited[current] = 1
604
+ cycle.push(current)
605
+ current = nextOf[current]
606
+ }
607
+ if (current !== start || cycle.length < 3) continue
608
+ const loopPoints = cycle.map((index) => points[halfEdges[index].from])
609
+ const area = polygonArea(loopPoints)
610
+ if (Math.abs(area) <= ARRANGEMENT_MIN_AREA) continue
611
+ loops.push({
612
+ points: loopPoints,
613
+ area,
614
+ bounds: loopBounds(loopPoints),
615
+ contours: new Set(cycle.map((index) => halfEdges[index].contour)),
616
+ })
617
+ }
618
+ if (!loops.length) return null
619
+
620
+ // ---- cells and their holes ---------------------------------------------
621
+ const cells = loops.filter((loop) => loop.area > 0).map((loop) => ({ loop, holes: [] }))
622
+ if (!cells.length) return null
623
+ for (const holeLoop of loops) {
624
+ if (holeLoop.area >= 0) continue
625
+ // The hole belongs to the smallest face that strictly contains the whole loop.
626
+ let owner = null
627
+ for (const cell of cells) {
628
+ if (!boundsContains(cell.loop.bounds, holeLoop.bounds, ARRANGEMENT_TOL)) continue
629
+ if (owner && cell.loop.area >= owner.loop.area) continue
630
+ if (!loopInsideLoop(holeLoop.points, cell.loop.points)) continue
631
+ owner = cell
632
+ }
633
+ if (owner) owner.holes.push(holeLoop)
634
+ }
635
+
636
+ // ---- faces, nesting depth and canonical order ---------------------------
637
+ const placed = cells.map((cell) => {
638
+ const region = {
639
+ outer: loopProfile(cell.loop),
640
+ holes: cell.holes.map((holeLoop) => loopProfile(holeLoop)),
641
+ depth: 0,
642
+ }
643
+ const interior = regionInteriorPoint(region)
644
+ const containing = contours.filter((contour) => pointInPolygon(interior, contour.points)).length
645
+ const own = [...cell.loop.contours]
646
+ .filter((contour) => pointInPolygon(interior, contour.points)).length
647
+ region.depth = Math.max(0, containing - own)
648
+ return { region, interior }
649
+ })
650
+ placed.sort((a, b) =>
651
+ a.region.depth - b.region.depth ||
652
+ regionArea(b.region) - regionArea(a.region) ||
653
+ a.interior[0] - b.interior[0] ||
654
+ a.interior[1] - b.interior[1] ||
655
+ a.region.holes.length - b.region.holes.length)
656
+ return placed.map((entry) => entry.region)
657
+ }
658
+
659
+ /**
660
+ * A profile as a closed point loop for the arrangement.
661
+ *
662
+ * Rectangles return their four corners; circles are sampled CCW at {@link ARRANGEMENT_CHORD_TOL};
663
+ * polygons keep their own points. Winding does not matter here — the planar graph is undirected.
664
+ *
665
+ * @param {unknown} profile `Circle2` | `Rect2` | `Poly2`.
666
+ * @returns {number[][]} Closed loop (no duplicated last point).
667
+ */
668
+ function arrangementLoop(profile) {
669
+ if (profile instanceof Rect2) {
670
+ return [
671
+ [profile.lo[0], profile.lo[1]],
672
+ [profile.hi[0], profile.lo[1]],
673
+ [profile.hi[0], profile.hi[1]],
674
+ [profile.lo[0], profile.hi[1]],
675
+ ]
676
+ }
677
+ if (profile instanceof Circle2) {
678
+ if (!(profile.r > 0)) return []
679
+ const ratio = Math.max(-1, Math.min(1, 1 - ARRANGEMENT_CHORD_TOL / profile.r))
680
+ const step = 2 * Math.acos(ratio)
681
+ const count = Math.max(16, Math.min(512, Math.ceil(TAU / Math.max(step, 1e-6))))
682
+ const loop = []
683
+ for (let i = 0; i < count; i++) {
684
+ const angle = (i / count) * TAU
685
+ loop.push([profile.c[0] + profile.r * Math.cos(angle), profile.c[1] + profile.r * Math.sin(angle)])
686
+ }
687
+ return loop
688
+ }
689
+ if (profile instanceof Poly2) return profile.pts.map((point) => [point[0], point[1]])
690
+ throw new TypeError(`regions: unsupported profile ${profile?.constructor?.name}`)
691
+ }
692
+
693
+ /** Drop consecutive duplicates (and a repeated closing point) from a loop. */
694
+ function cleanLoop(points) {
695
+ const loop = []
696
+ for (const point of points) {
697
+ if (!Number.isFinite(point[0]) || !Number.isFinite(point[1])) return []
698
+ const last = loop[loop.length - 1]
699
+ if (last && dist2d(last, point) <= ARRANGEMENT_TOL) continue
700
+ loop.push([point[0], point[1]])
701
+ }
702
+ if (loop.length > 1 && dist2d(loop[0], loop[loop.length - 1]) <= ARRANGEMENT_TOL) loop.pop()
703
+ return loop.length >= 3 ? loop : []
704
+ }
705
+
706
+ /** Axis-aligned bounds of a point loop. */
707
+ function loopBounds(points) {
708
+ const lo = [Infinity, Infinity]
709
+ const hi = [-Infinity, -Infinity]
710
+ for (const point of points) {
711
+ lo[0] = Math.min(lo[0], point[0])
712
+ lo[1] = Math.min(lo[1], point[1])
713
+ hi[0] = Math.max(hi[0], point[0])
714
+ hi[1] = Math.max(hi[1], point[1])
715
+ }
716
+ return { lo, hi }
717
+ }
718
+
719
+ /** Axis-aligned bounds of one segment. */
720
+ function segmentBounds(a, b) {
721
+ return {
722
+ lo: [Math.min(a[0], b[0]), Math.min(a[1], b[1])],
723
+ hi: [Math.max(a[0], b[0]), Math.max(a[1], b[1])],
724
+ }
725
+ }
726
+
727
+ /** Whether two axis-aligned bounds overlap (grow one side by `pad`). */
728
+ function boundsOverlap(first, second, pad) {
729
+ return first.lo[0] <= second.hi[0] + pad && second.lo[0] <= first.hi[0] + pad
730
+ && first.lo[1] <= second.hi[1] + pad && second.lo[1] <= first.hi[1] + pad
731
+ }
732
+
733
+ /** Whether one axis-aligned bounds strictly contains another (grown by `pad`). */
734
+ function boundsContains(outer, inner, pad) {
735
+ return inner.lo[0] >= outer.lo[0] - pad && inner.hi[0] <= outer.hi[0] + pad
736
+ && inner.lo[1] >= outer.lo[1] - pad && inner.hi[1] <= outer.hi[1] + pad
737
+ }
738
+
739
+ /** Distance from a point to a segment, in mm. */
740
+ function distancePointSegment(point, a, b) {
741
+ const dx = b[0] - a[0]
742
+ const dy = b[1] - a[1]
743
+ const length2 = dx * dx + dy * dy
744
+ const t = length2 > 0
745
+ ? Math.min(1, Math.max(0, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dy) / length2))
746
+ : 0
747
+ return dist2d(point, [a[0] + dx * t, a[1] + dy * t])
748
+ }
749
+
750
+ /**
751
+ * The points where two segments meet: one crossing point, one T-junction point, or the two ends of a
752
+ * collinear overlap.
753
+ *
754
+ * An empty array means disjoint. Endpoint-to-endpoint contact returns the shared endpoint, which
755
+ * {@link addSplit} then ignores (it is already a vertex) — so merely touching contours, exactly
756
+ * coincident edges and identical duplicate profiles do not trigger the arrangement.
757
+ *
758
+ * @param {number[]} a First segment start.
759
+ * @param {number[]} b First segment end.
760
+ * @param {number[]} c Second segment start.
761
+ * @param {number[]} d Second segment end.
762
+ * @returns {number[][]} Contact points in sketch `(u, v)` millimetres.
763
+ */
764
+ function segmentContact(a, b, c, d) {
765
+ const rx = b[0] - a[0]
766
+ const ry = b[1] - a[1]
767
+ const sx = d[0] - c[0]
768
+ const sy = d[1] - c[1]
769
+ const qx = c[0] - a[0]
770
+ const qy = c[1] - a[1]
771
+ const firstLength = Math.hypot(rx, ry)
772
+ const secondLength = Math.hypot(sx, sy)
773
+ if (firstLength <= ARRANGEMENT_TOL || secondLength <= ARRANGEMENT_TOL) return []
774
+ const denominator = rx * sy - ry * sx
775
+ if (Math.abs(denominator) > 1e-9 * firstLength * secondLength) {
776
+ const t = (qx * sy - qy * sx) / denominator
777
+ const u = (qx * ry - qy * rx) / denominator
778
+ const tTolerance = ARRANGEMENT_TOL / firstLength
779
+ const uTolerance = ARRANGEMENT_TOL / secondLength
780
+ if (t < -tTolerance || t > 1 + tTolerance || u < -uTolerance || u > 1 + uTolerance) return []
781
+ return [[a[0] + rx * t, a[1] + ry * t]]
782
+ }
783
+ // Parallel: only a collinear overlap can touch.
784
+ if (Math.abs(qx * ry - qy * rx) > ARRANGEMENT_TOL * firstLength) return []
785
+ const length2 = rx * rx + ry * ry
786
+ const at = (qx * rx + qy * ry) / length2
787
+ const bt = ((d[0] - a[0]) * rx + (d[1] - a[1]) * ry) / length2
788
+ const lo = Math.max(0, Math.min(at, bt))
789
+ const hi = Math.min(1, Math.max(at, bt))
790
+ if ((hi - lo) * firstLength <= ARRANGEMENT_TOL) return []
791
+ const atPoint = (parameter) => [a[0] + rx * parameter, a[1] + ry * parameter]
792
+ return [atPoint(lo), atPoint(hi)]
793
+ }
794
+
795
+ /**
796
+ * Record a contact point as a split of one segment.
797
+ *
798
+ * Only a point strictly inside the segment (further than {@link ARRANGEMENT_TOL} from either end)
799
+ * splits it: a contact at an existing vertex needs no new vertex and must not count as an overlap.
800
+ *
801
+ * @param {object} segment Segment record with `a`, `b` and a `splits` array.
802
+ * @param {number[]} point Contact point.
803
+ * @returns {number} 1 when a split was added, else 0.
804
+ */
805
+ function addSplit(segment, point) {
806
+ if (dist2d(point, segment.a) <= ARRANGEMENT_TOL || dist2d(point, segment.b) <= ARRANGEMENT_TOL) return 0
807
+ const dx = segment.b[0] - segment.a[0]
808
+ const dy = segment.b[1] - segment.a[1]
809
+ const length2 = dx * dx + dy * dy
810
+ if (length2 <= 0) return 0
811
+ const t = ((point[0] - segment.a[0]) * dx + (point[1] - segment.a[1]) * dy) / length2
812
+ if (t <= 1e-9 || t >= 1 - 1e-9) return 0
813
+ segment.splits.push({ t, point })
814
+ return 1
815
+ }
816
+
817
+ /**
818
+ * Split both segments at every contact point between them.
819
+ *
820
+ * @param {object} first First segment record.
821
+ * @param {object} second Second segment record.
822
+ * @returns {number} 1 when at least one split was added (this pair overlaps), else 0.
823
+ */
824
+ function splitAtContacts(first, second) {
825
+ let added = 0
826
+ for (const point of segmentContact(first.a, first.b, second.a, second.b)) {
827
+ added += addSplit(first, point)
828
+ added += addSplit(second, point)
829
+ }
830
+ return added > 0 ? 1 : 0
831
+ }
832
+
833
+ /** Add one undirected graph edge between two vertex indices, keeping the first contour seen. */
834
+ function addArrangementEdge(edges, u, v, contour) {
835
+ if (u === v) return
836
+ const key = u < v ? `${u}|${v}` : `${v}|${u}`
837
+ if (!edges.has(key)) edges.set(key, { u, v, contour })
838
+ }
839
+
840
+ /**
841
+ * Whether `first` is a whole untouched contour of the sketch.
842
+ *
843
+ * A loop covering exactly one contour's vertices is handed back as that contour's own profile, so an
844
+ * untouched circle/rectangle stays analytic in the arrangement (only cut geometry becomes a polygon
845
+ * loop). Without this a sketch that merely *contains* one overlap would sample every circle in it.
846
+ *
847
+ * @param {{points: number[][], contours: Set<object>}} loop Arrangement loop.
848
+ * @returns {unknown} The contour's original profile, or a `Poly2` of the loop.
849
+ */
850
+ function loopProfile(loop) {
851
+ if (loop.contours.size === 1) {
852
+ const [contour] = loop.contours
853
+ if (loop.points.length === contour.points.length) {
854
+ if (contour.profile instanceof Circle2 || contour.profile instanceof Rect2) return contour.profile
855
+ if (contour.profile instanceof Poly2 && loop.points.length === contour.profile.pts.length) return contour.profile
856
+ }
857
+ }
858
+ return new Poly2(loop.points)
859
+ }
860
+
861
+ /**
862
+ * Whether one loop lies strictly inside another.
863
+ *
864
+ * Every vertex must be inside the outer loop and further than {@link ARRANGEMENT_TOL} from its
865
+ * boundary, so a loop that merely touches the boundary (a tangent contour, or the same contour
866
+ * traversed the other way) is not claimed as a hole.
867
+ *
868
+ * @param {number[][]} inner Candidate hole loop.
869
+ * @param {number[][]} outer Candidate enclosing loop.
870
+ * @returns {boolean} True when `inner` is wholly inside `outer`.
871
+ */
872
+ function loopInsideLoop(inner, outer) {
873
+ for (const point of inner) {
874
+ if (!pointInPolygon(point, outer)) return false
875
+ for (let i = 0; i < outer.length; i++) {
876
+ if (distancePointSegment(point, outer[i], outer[(i + 1) % outer.length]) <= ARRANGEMENT_TOL) return false
877
+ }
878
+ }
879
+ return true
880
+ }
881
+
882
+ /**
883
+ * A spatial hash over arrangement vertices: points within {@link ARRANGEMENT_TOL} are one vertex.
884
+ *
885
+ * Intersections computed from different segment pairs in a multi-boundary crossing can differ in the
886
+ * last bits, so vertices are welded by tolerance rather than by exact coordinates.
887
+ */
888
+ class ArrangementPoints {
889
+ constructor() {
890
+ /** Welded vertex coordinates, in sketch `(u, v)` millimetres. */
891
+ this.points = []
892
+ /** Spatial hash cell → vertex indices. */
893
+ this.cells = new Map()
894
+ }
895
+
896
+ /**
897
+ * The index of the vertex at `point`, creating one when no existing vertex is close enough.
898
+ *
899
+ * @param {number[]} point Arrangement point in sketch `(u, v)` millimetres.
900
+ * @returns {number} Vertex index into {@link ArrangementPoints#points}.
901
+ */
902
+ index(point) {
903
+ const size = ARRANGEMENT_TOL * 4
904
+ const cellX = Math.floor(point[0] / size)
905
+ const cellY = Math.floor(point[1] / size)
906
+ for (let dx = -1; dx <= 1; dx++) {
907
+ for (let dy = -1; dy <= 1; dy++) {
908
+ const bucket = this.cells.get(`${cellX + dx}|${cellY + dy}`)
909
+ if (!bucket) continue
910
+ for (const id of bucket) {
911
+ if (dist2d(this.points[id], point) <= ARRANGEMENT_TOL) return id
912
+ }
913
+ }
914
+ }
915
+ const id = this.points.length
916
+ this.points.push([point[0], point[1]])
917
+ const key = `${cellX}|${cellY}`
918
+ const bucket = this.cells.get(key)
919
+ if (bucket) bucket.push(id)
920
+ else this.cells.set(key, [id])
921
+ return id
922
+ }
923
+ }