Skip to main content

brep_kernel/intersect/
arrangement.rs

1use crate::spatial::{Aabb, Bvh};
2use crate::Vec3;
3use rustc_hash::FxHashMap;
4use serde::{Deserialize, Serialize};
5
6const PARALLEL_THRESHOLD: f64 = 1e-12;
7
8#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
9pub struct Vec2 {
10    pub x: f64,
11    pub y: f64,
12}
13
14impl Vec2 {
15    /// Distance to a segment. `guard` is the caller's squared-length threshold.
16    #[inline]
17    pub fn distance_to_segment(self, start: Self, end: Self, guard: f64) -> f64 {
18        let segment = end.sub(start);
19        let length_squared = segment.dot(segment);
20        if length_squared <= guard {
21            return self.sub(start).length();
22        }
23        let parameter = (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0);
24        self.sub(start.add(segment.scale(parameter))).length()
25    }
26
27    /// Squared distance, retaining the seed sweep's projection on zero-length segments.
28    #[inline]
29    pub fn distance_to_segment_squared(self, start: Self, end: Self) -> f64 {
30        let segment = end.sub(start);
31        let length_squared = segment.dot(segment);
32        let parameter = if length_squared > 0.0 {
33            (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0)
34        } else {
35            0.0
36        };
37        let residual = self.sub(start.add(segment.scale(parameter)));
38        residual.dot(residual)
39    }
40
41    pub(crate) fn sub(self, other: Self) -> Self {
42        Self {
43            x: self.x - other.x,
44            y: self.y - other.y,
45        }
46    }
47    pub(crate) fn add(self, other: Self) -> Self {
48        Self {
49            x: self.x + other.x,
50            y: self.y + other.y,
51        }
52    }
53    pub(crate) fn scale(self, factor: f64) -> Self {
54        Self {
55            x: self.x * factor,
56            y: self.y * factor,
57        }
58    }
59    fn distance(self, other: Self) -> f64 {
60        self.sub(other).length()
61    }
62    pub(crate) fn length(self) -> f64 {
63        (self.x * self.x + self.y * self.y).sqrt()
64    }
65    fn cross(self, other: Self) -> f64 {
66        self.x * other.y - self.y * other.x
67    }
68    pub(crate) fn dot(self, other: Self) -> f64 {
69        self.x * other.x + self.y * other.y
70    }
71}
72
73#[derive(Clone, Debug, Deserialize, Serialize)]
74pub struct Segment2 {
75    pub a: Vec2,
76    pub b: Vec2,
77    #[serde(default)]
78    pub tag: serde_json::Value,
79}
80
81#[derive(Clone, Debug, Serialize)]
82pub struct ArrangementPiece {
83    pub a: Vec2,
84    pub b: Vec2,
85    pub parent: Segment2,
86}
87
88#[derive(Clone, Debug, Serialize)]
89pub struct CycleUse {
90    pub piece: ArrangementPiece,
91    pub forward: bool,
92}
93
94#[derive(Clone, Debug, Serialize)]
95pub struct ArrangementRegion {
96    pub outer: Vec<CycleUse>,
97    pub holes: Vec<Vec<CycleUse>>,
98    pub area: f64,
99    /// The outer cycle's area alone, the key regions are returned by
100    /// (ascending); `area` nets the holes out.
101    pub outer_area: f64,
102}
103
104#[derive(Clone)]
105struct Node {
106    point: Vec2,
107    outgoing: Vec<usize>,
108}
109
110/// Append-only node lookup. A match always selects the lowest existing node
111/// index, exactly like the original linear `.position` scan, not the nearest
112/// point or the first occupied neighboring cell.
113struct NodeLookup {
114    tolerance: f64,
115    width: f64,
116    cells: Option<FxHashMap<[i64; 2], Vec<usize>>>,
117}
118
119impl NodeLookup {
120    fn new(tolerance: f64, indexed: bool) -> Self {
121        let width = tolerance * 2.0;
122        Self {
123            tolerance,
124            width,
125            // Squared distances can underflow and accept farther points at
126            // tiny tolerances. Preserve that legacy behavior with a scan.
127            cells: (indexed && tolerance >= 1e-150 && width.is_finite()).then(FxHashMap::default),
128        }
129    }
130
131    fn key(&self, point: Vec2) -> Option<[i64; 2]> {
132        let q = [point.x / self.width, point.y / self.width];
133        // Two-radius cells leave half a cell of rounding headroom. Bound the
134        // quotient so division rounding cannot consume it, or integer neighbors
135        // overflow. This also rejects non-finite coordinates.
136        q.iter()
137            .all(|v| v.is_finite() && v.abs() <= (1u64 << 48) as f64)
138            .then(|| q.map(|v| v.floor() as i64))
139    }
140
141    fn find_or_insert(&mut self, point: Vec2, nodes: &mut Vec<Node>) -> usize {
142        let key = self.cells.as_ref().and_then(|_| self.key(point));
143        if key.is_none() {
144            // Once a point cannot be indexed, retain the scan for the rest of
145            // the stream, including comparisons against this newly added node.
146            self.cells = None;
147        }
148        let found = if let (Some(cells), Some([x, y])) = (&self.cells, key) {
149            let mut first = None;
150            for dx in -1..=1 {
151                for dy in -1..=1 {
152                    if let Some(indices) = cells.get(&[x + dx, y + dy]) {
153                        // Each bucket is in insertion order. Later nodes in
154                        // this bucket cannot beat an already earlier match.
155                        for &index in indices {
156                            if first.is_some_and(|first| index >= first) {
157                                break;
158                            }
159                            if nodes[index].point.distance(point) <= self.tolerance {
160                                first = Some(index);
161                                break;
162                            }
163                        }
164                    }
165                }
166            }
167            first
168        } else {
169            nodes
170                .iter()
171                .position(|node| node.point.distance(point) <= self.tolerance)
172        };
173        if let Some(index) = found {
174            return index;
175        }
176        let index = nodes.len();
177        nodes.push(Node {
178            point,
179            outgoing: Vec::new(),
180        });
181        if let (Some(cells), Some(key)) = (&mut self.cells, key) {
182            cells.entry(key).or_default().push(index);
183        }
184        index
185    }
186}
187
188fn tolerance_parameter(segment: &Segment2, tolerance: f64) -> f64 {
189    let length = segment.a.distance(segment.b);
190    if length <= tolerance {
191        0.5
192    } else {
193        tolerance / length
194    }
195}
196
197fn interpolate(a: Vec2, b: Vec2, parameter: f64) -> Vec2 {
198    Vec2 {
199        x: a.x + (b.x - a.x) * parameter,
200        y: a.y + (b.y - a.y) * parameter,
201    }
202}
203
204pub fn segment_intersection(
205    a1: Vec2,
206    b1: Vec2,
207    a2: Vec2,
208    b2: Vec2,
209    tolerance: f64,
210) -> Option<[f64; 2]> {
211    let d1 = b1.sub(a1);
212    let d2 = b2.sub(a2);
213    let denominator = d1.cross(d2);
214    let length1 = d1.length();
215    let length2 = d2.length();
216    if denominator.abs() <= PARALLEL_THRESHOLD * length1 * length2 {
217        return None;
218    }
219    let offset = a2.sub(a1);
220    let t1 = offset.cross(d2) / denominator;
221    let t2 = offset.cross(d1) / denominator;
222    let epsilon1 = tolerance / length1.max(tolerance);
223    let epsilon2 = tolerance / length2.max(tolerance);
224    if t1 < -epsilon1 || t1 > 1.0 + epsilon1 || t2 < -epsilon2 || t2 > 1.0 + epsilon2 {
225        None
226    } else {
227        Some([t1.clamp(0.0, 1.0), t2.clamp(0.0, 1.0)])
228    }
229}
230
231pub use crate::polygon::PolygonClass;
232
233fn point_segment_distance(point: Vec2, a: Vec2, b: Vec2) -> f64 {
234    point.distance_to_segment(a, b, 1e-300)
235}
236
237/// The hole assignment's box rejection (2026-11-02): a point
238/// beyond a region polygon's vertex box by more than the classifier's
239/// tolerance plus a rounding pad is classified Outside without the O(n) test,
240/// and the full classifier would say the same. Its boundary band cannot fire
241/// (every computed segment distance exceeds the tolerance: the clamped foot
242/// lies in the box up to rounding the pad covers). Its form-K parity reads
243/// Outside: above or below the box no edge straddles the ray; to the right no
244/// crossing lies right of the point; to the left every straddling edge crosses
245/// right of it, and a closed loop has an even number of them. The hole loop
246/// was 60-70% of the arrangement's time on the package models (one negative
247/// cycle tested node by node against every positive region's polygon).
248/// Returns `[min_x, min_y, max_x, max_y, reach]`; `reach` is NaN (never
249/// reject) for an empty or non-finite polygon.
250fn polygon_reject_box(polygon: &[Vec2], tolerance: f64) -> [f64; 5] {
251    let mut bounds = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
252    let mut magnitude = 1.0f64;
253    for point in polygon {
254        bounds[0] = bounds[0].min(point.x);
255        bounds[1] = bounds[1].min(point.y);
256        bounds[2] = bounds[2].max(point.x);
257        bounds[3] = bounds[3].max(point.y);
258        magnitude = magnitude.max(point.x.abs()).max(point.y.abs());
259    }
260    let finite = !polygon.is_empty() && bounds.iter().all(|value| value.is_finite()) && tolerance.is_finite() && tolerance >= 0.0;
261    let reach = if finite { tolerance * (1.0 + 1e-9) + 64.0 * f64::EPSILON * magnitude } else { f64::NAN };
262    [bounds[0], bounds[1], bounds[2], bounds[3], reach]
263}
264
265/// The classifier's boundary band, indexed (2026-11-02): a
266/// uniform grid over the polygon's vertex box whose cells list every edge whose
267/// box, widened by the tolerance plus a rounding pad, overlaps them. An edge
268/// whose computed distance to a point is within the tolerance has that point
269/// inside its widened box (the clamped foot lies in the edge's box up to
270/// rounding the pad covers), so the point's cell lists it; the band is an
271/// existence test, so testing the listed edges with the classifier's own
272/// distance gives the classifier's own answer. Parity is the original full
273/// scan. Why: a negative cycle that runs along a region's own boundary
274/// classifies Boundary at every node and goes on to the next, so the hole loop
275/// paid one full O(n) band scan per node.
276struct BoundaryBand {
277    origin: [f64; 2],
278    cell: [f64; 2],
279    side: usize,
280    reach: f64,
281    starts: Vec<u32>,
282    items: Vec<u32>,
283    usable: bool,
284}
285
286impl BoundaryBand {
287    fn new(polygon: &[Vec2], tolerance: f64) -> Self {
288        let reject = polygon_reject_box(polygon, tolerance);
289        let reach = reject[4];
290        let count = polygon.len();
291        let usable = reach.is_finite() && count >= 16 && count <= (1 << 24);
292        let side = if usable { ((count as f64).sqrt() as usize).clamp(4, 512) } else { 0 };
293        let origin = [reject[0] - reach, reject[1] - reach];
294        let extent = [(reject[2] + reach) - origin[0], (reject[3] + reach) - origin[1]];
295        let cell = [(extent[0] / side.max(1) as f64).max(f64::MIN_POSITIVE), (extent[1] / side.max(1) as f64).max(f64::MIN_POSITIVE)];
296        let mut band = Self { origin, cell, side, reach, starts: Vec::new(), items: Vec::new(), usable };
297        if !band.usable {
298            return band;
299        }
300        let mut counts = vec![0u32; side * side + 1];
301        let ranges: Vec<[usize; 4]> = (0..count)
302            .map(|index| {
303                let (a, b) = (polygon[index], polygon[(index + 1) % count]);
304                let pad = reach + 64.0 * f64::EPSILON * a.x.abs().max(a.y.abs()).max(b.x.abs()).max(b.y.abs());
305                [band.column(a.x.min(b.x) - pad), band.column(a.x.max(b.x) + pad), band.row(a.y.min(b.y) - pad), band.row(a.y.max(b.y) + pad)]
306            })
307            .collect();
308        for range in &ranges {
309            for y in range[2]..=range[3] {
310                for x in range[0]..=range[1] {
311                    counts[y * side + x + 1] += 1;
312                }
313            }
314        }
315        for index in 1..counts.len() {
316            counts[index] += counts[index - 1];
317        }
318        // Long edges cover many cells; past a budget the original scan is cheaper.
319        if counts[side * side] as usize > 64 * count + 4096 {
320            band.usable = false;
321            return band;
322        }
323        let mut cursor = counts.clone();
324        band.items = vec![0u32; counts[side * side] as usize];
325        for (edge, range) in ranges.iter().enumerate() {
326            for y in range[2]..=range[3] {
327                for x in range[0]..=range[1] {
328                    let slot = &mut cursor[y * side + x];
329                    band.items[*slot as usize] = edge as u32;
330                    *slot += 1;
331                }
332            }
333        }
334        band.starts = counts;
335        band
336    }
337    fn column(&self, x: f64) -> usize {
338        (((x - self.origin[0]) / self.cell[0]).floor().max(0.0) as usize).min(self.side - 1)
339    }
340    fn row(&self, y: f64) -> usize {
341        (((y - self.origin[1]) / self.cell[1]).floor().max(0.0) as usize).min(self.side - 1)
342    }
343    fn classify(&self, point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
344        if !self.usable || !point.x.is_finite() || !point.y.is_finite() {
345            return point_in_polygon_class(point, polygon, tolerance);
346        }
347        let cell = self.row(point.y) * self.side + self.column(point.x);
348        let count = polygon.len();
349        for &edge in &self.items[self.starts[cell] as usize..self.starts[cell + 1] as usize] {
350            let edge = edge as usize;
351            if point.distance_to_segment(polygon[edge], polygon[(edge + 1) % count], 1e-300) <= tolerance {
352                return PolygonClass::Boundary;
353            }
354        }
355        if crate::polygon::parity_inside([point.x, point.y], count, |i| [polygon[i].x, polygon[i].y]) {
356            PolygonClass::Inside
357        } else {
358            PolygonClass::Outside
359        }
360    }
361}
362
363fn outside_reject_box(point: Vec2, reject: &[f64; 5]) -> bool {
364    let reach = reject[4] + 64.0 * f64::EPSILON * point.x.abs().max(point.y.abs());
365    // NaN `reach` (or a NaN point) makes every comparison false: never reject.
366    point.x < reject[0] - reach || point.y < reject[1] - reach || point.x > reject[2] + reach || point.y > reject[3] + reach
367}
368
369fn hole_box_reject_enabled() -> bool {
370    switch!("BREP_ARRANGE_HOLE_BOX", true)
371}
372
373
374fn point_in_polygon_class(point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
375    crate::polygon::classify(point, polygon, tolerance, 1e-300)
376}
377
378pub fn point_in_polygon(point: Vec2, polygon: &[Vec2], tolerance: f64) -> &'static str {
379    match point_in_polygon_class(point, polygon, tolerance) {
380        PolygonClass::Inside => "in",
381        PolygonClass::Outside => "out",
382        PolygonClass::Boundary => "boundary",
383    }
384}
385
386// Arrangement decisions read endpoints and topology, never parent tags. Keep
387// the immutable source segment borrowed until a retained cycle needs an owned
388// output. The eager arm preserves the original allocation path for A/B.
389struct PieceInput<'a> {
390    a: Vec2,
391    b: Vec2,
392    parent: std::borrow::Cow<'a, Segment2>,
393}
394impl PieceInput<'_> {
395    fn materialize(&self, forward: bool) -> CycleUse {
396        CycleUse { piece: ArrangementPiece { a: self.a, b: self.b, parent: self.parent.as_ref().clone() }, forward }
397    }
398}
399
400#[derive(Clone)]
401enum CycleUses {
402    Eager(Vec<CycleUse>),
403    Deferred(Vec<usize>),
404}
405impl CycleUses {
406    fn push(&mut self, half: usize, pieces: &[PieceInput<'_>]) {
407        match self {
408            Self::Eager(uses) => uses.push(pieces[half >> 1].materialize(half % 2 == 0)),
409            Self::Deferred(halves) => halves.push(half),
410        }
411    }
412    fn into_uses(self, pieces: &[PieceInput<'_>]) -> Vec<CycleUse> {
413        match self {
414            Self::Eager(uses) => uses,
415            Self::Deferred(halves) => halves.into_iter().map(|h| pieces[h >> 1].materialize(h % 2 == 0)).collect(),
416        }
417    }
418    fn copy_uses(&self, pieces: &[PieceInput<'_>]) -> Vec<CycleUse> {
419        match self {
420            Self::Eager(uses) => uses.clone(),
421            Self::Deferred(halves) => halves.iter().map(|&h| pieces[h >> 1].materialize(h % 2 == 0)).collect(),
422        }
423    }
424}
425
426#[derive(Clone)]
427struct Cycle {
428    uses: CycleUses,
429    area: f64,
430    node_indices: Vec<usize>,
431}
432
433/// Visit a conservative subset of pairs in original input order. The narrow
434/// phase remains authoritative, including its endpoint tolerance and rounding.
435fn visit_segment_pairs(segments: &[Segment2], tolerance: f64, mut visit: impl FnMut(usize, usize)) {
436    let all_pairs = |visit: &mut dyn FnMut(usize, usize)| {
437        for first in 0..segments.len() {
438            for second in first + 1..segments.len() {
439                visit(first, second);
440            }
441        }
442    };
443    if segments.len() <= 32
444        || segments.len() > u32::MAX as usize
445        || !tolerance.is_finite()
446        || tolerance < 0.0
447        || tolerance > 1e100
448    {
449        all_pairs(&mut visit);
450        return;
451    }
452    let mut scale = 0.0f64;
453    let mut boxes = Vec::with_capacity(segments.len());
454    let mut extent = Aabb::empty();
455    for segment in segments {
456        let coordinates = [segment.a.x, segment.a.y, segment.b.x, segment.b.y];
457        let length = segment.a.distance(segment.b);
458        // Keep the legacy scan for numeric extremes: underflow/overflow or NaN
459        // in the narrow phase need not behave like geometric intersection.
460        if coordinates
461            .iter()
462            .any(|v| !v.is_finite() || v.abs() > 1e100)
463            || !(1e-100..=1e100).contains(&length)
464        {
465            all_pairs(&mut visit);
466            return;
467        }
468        for coordinate in coordinates {
469            scale = scale.max(coordinate.abs());
470        }
471        let bounds = Aabb {
472            minimum: Vec3::new(
473                segment.a.x.min(segment.b.x),
474                segment.a.y.min(segment.b.y),
475                0.0,
476            ),
477            maximum: Vec3::new(
478                segment.a.x.max(segment.b.x),
479                segment.a.y.max(segment.b.y),
480                0.0,
481            ),
482        };
483        extent.include(bounds);
484        boxes.push(bounds);
485    }
486    // Each accepted parameter may extend its segment by up to tolerance.
487    // Cross-product roundoff is amplified by up to 1/PARALLEL_THRESHOLD when
488    // solving the parameters. Bound it using the global coordinate magnitude
489    // (including translation), with headroom for subtraction, products, length
490    // and division rounding. This deliberately admits extra pairs near parallel
491    // lines instead of treating exact endpoint boxes as a bound on an inexact
492    // solve. The numeric guards above keep these operations in the normal range.
493    let padding = 2.0 * tolerance + 128.0 * f64::EPSILON / PARALLEL_THRESHOLD * scale;
494    // A large translation or tolerance can swallow the entire arrangement.
495    // An index cannot reject anything then, so avoid its query/sort overhead.
496    if padding >= extent.diagonal() {
497        all_pairs(&mut visit);
498        return;
499    }
500    let direction_tiers = direction_index_on();
501    // Row 29: the direction tiers' small-padding query is answered by a
502    // one-axis sweep instead of the tree, which is then not built (`None`
503    // from the sweep keeps the tree).
504    let small_padding = 2.0 * tolerance + 128.0 * f64::EPSILON / DIRECTION_SINE * scale;
505    let swept = if direction_tiers && arrange_sweep_on() { swept_pairs(&boxes, small_padding) } else { None };
506    let tree = swept.is_none().then(|| Bvh::build(&boxes));
507    let mut candidates = Vec::new();
508    if direction_tiers {
509        // DIRECTION TIERS (lane O, 2026-10-28). The padding above is what a
510        // pair as near-parallel as the narrow phase admits (`sin θ` down to
511        // PARALLEL_THRESHOLD) can need, and on a face whose uv sit far from
512        // the origin it reaches across most of the arrangement: the filleted
513        // box's outward offset sends a 252-segment quarter-arc chain through
514        // here twice per attempt and the index visited nearly all 37 000
515        // pairs (0.7 ms a face). The same rounding model bounds a pair whose
516        // directions differ by `sin θ ≥ s` with the padding at `s` in place of
517        // the threshold. So every pair is visited under that small padding,
518        // and a pair whose directions lie within one bucket of each other
519        // (width `2s`, wrapping at π) — the only pairs that can be nearer
520        // parallel than `s` — under the full padding as before. Visit order
521        // and the narrow phase are unchanged; the visited set still contains
522        // every pair the full padding could accept.
523        let width = 2.0 * DIRECTION_SINE;
524        let bucket_count = ((std::f64::consts::PI / width).ceil() as usize).max(1);
525        let mut buckets: FxHashMap<usize, Vec<usize>> = FxHashMap::default();
526        let bucket_of: Vec<usize> = segments
527            .iter()
528            .map(|segment| {
529                let angle = (segment.b.y - segment.a.y).atan2(segment.b.x - segment.a.x).rem_euclid(std::f64::consts::PI);
530                ((angle / width) as usize).min(bucket_count - 1)
531            })
532            .collect();
533        for (index, bucket) in bucket_of.iter().enumerate() {
534            buckets.entry(*bucket).or_default().push(index);
535        }
536        let near = |a: &Aabb, b: &Aabb| {
537            a.minimum.x - padding <= b.maximum.x
538                && b.minimum.x - padding <= a.maximum.x
539                && a.minimum.y - padding <= b.maximum.y
540                && b.minimum.y - padding <= a.maximum.y
541        };
542        for (first, &bounds) in boxes.iter().enumerate() {
543            candidates.clear();
544            match (&swept, &tree) {
545                (Some(lists), _) => candidates.extend_from_slice(&lists[first]),
546                (None, Some(tree)) => tree.overlapping(bounds, small_padding, &mut candidates),
547                (None, None) => unreachable!("the tree is built whenever the sweep is not"),
548            }
549            let bucket = bucket_of[first];
550            for neighbour in [(bucket + bucket_count - 1) % bucket_count, bucket, (bucket + 1) % bucket_count] {
551                if let Some(members) = buckets.get(&neighbour) {
552                    candidates.extend(members.iter().copied().filter(|&second| second > first && near(&bounds, &boxes[second])));
553                }
554                if bucket_count < 3 {
555                    break;
556                }
557            }
558            candidates.retain(|&second| second > first);
559            candidates.sort_unstable();
560            candidates.dedup();
561            for &second in &candidates {
562                visit(first, second);
563            }
564        }
565        return;
566    }
567    let Some(tree) = tree else { unreachable!("the sweep runs only under the direction tiers") };
568    for (first, &bounds) in boxes.iter().enumerate() {
569        candidates.clear();
570        tree.overlapping(bounds, padding, &mut candidates);
571        candidates.retain(|&second| second > first);
572        candidates.sort_unstable();
573        for &second in &candidates {
574            visit(first, second);
575        }
576    }
577}
578
579/// The direction sine above which [`visit_segment_pairs`] pads a pair with
580/// the small padding (see DIRECTION TIERS there).
581const DIRECTION_SINE: f64 = 1e-3;
582
583/// Lane O row 29 (2026-10-30, `BREP_ARRANGE_SWEEP`, default on since batch 12;
584/// `0`/`off` restores the tree): for each box `first`, every `second > first` whose box passes
585/// the tree's own leaf test `boxes[second].intersects(boxes[first], padding)`
586/// — the set [`Bvh::overlapping`] returns past `second > first`, since a node
587/// box contains its items' boxes — in ascending order. The candidates come
588/// from a sweep over the boxes sorted by their minimum on one axis, each
589/// scanning forward while the next minimum is within its maximum plus twice
590/// the padding: a pair the leaf test admits lies within the padding plus one
591/// rounding of either subtraction there, and the padding (at least
592/// 128 ε / DIRECTION_SINE of the largest coordinate) exceeds that rounding.
593///
594/// The axis is the one whose sweep windows (counted by binary search before
595/// any test runs) are fewer in total; when even those exceed 32 a box, the
596/// boxes overlap along both axes and `None` hands the query back to the tree,
597/// which prunes on both at once (a guard: of the D1, inward opposed and
598/// outward 3-adjacent shell cases probed, only D1 reaches the sweep, and
599/// never the fallback). D1's two 272-segment faces spent 0.38 ms a run
600/// building and querying the tree for 570 narrow-phase pairs that cost
601/// 0.04 ms.
602fn swept_pairs(boxes: &[Aabb], padding: f64) -> Option<Vec<Vec<usize>>> {
603    let reach = 2.0 * padding;
604    let low = |index: usize, axis: usize| if axis == 0 { boxes[index].minimum.x } else { boxes[index].minimum.y };
605    let high = |index: usize, axis: usize| if axis == 0 { boxes[index].maximum.x } else { boxes[index].maximum.y };
606    let mut best: Option<(usize, Vec<usize>, usize)> = None;
607    for axis in [0, 1] {
608        let mut order: Vec<usize> = (0..boxes.len()).collect();
609        order.sort_by(|&a, &b| low(a, axis).total_cmp(&low(b, axis)));
610        let lows: Vec<f64> = order.iter().map(|&index| low(index, axis)).collect();
611        let windows: usize = order
612            .iter()
613            .enumerate()
614            .map(|(position, &a)| {
615                let limit = high(a, axis) + reach;
616                lows.partition_point(|&value| value <= limit).saturating_sub(position + 1)
617            })
618            .sum();
619        if best.as_ref().is_none_or(|(least, _, _)| windows < *least) {
620            best = Some((windows, order, axis));
621        }
622    }
623    let (windows, order, axis) = best?;
624    if windows > 32 * boxes.len() {
625        return None;
626    }
627    let mut lists = vec![Vec::new(); boxes.len()];
628    for (position, &a) in order.iter().enumerate() {
629        let limit = high(a, axis) + reach;
630        for &b in &order[position + 1..] {
631            if low(b, axis) > limit {
632                break;
633            }
634            let (first, second) = if a < b { (a, b) } else { (b, a) };
635            if boxes[second].intersects(boxes[first], padding) {
636                lists[first].push(second);
637            }
638        }
639    }
640    for list in &mut lists {
641        list.sort_unstable();
642    }
643    Some(lists)
644}
645
646/// Row 29's switch ([`swept_pairs`]), read once.
647fn arrange_sweep_on() -> bool {
648    switch!("BREP_ARRANGE_SWEEP", true)
649}
650
651
652/// The direction tiers of [`visit_segment_pairs`], on unless
653/// `BREP_ARRANGE_DIRECTION_INDEX` is `0`/`off` (the A/B lever). Read once.
654fn direction_index_on() -> bool {
655    switch!("BREP_ARRANGE_DIRECTION_INDEX", true)
656}
657
658pub fn arrange_segments(
659    segments: &[Segment2],
660    tolerance: f64,
661) -> Result<Vec<ArrangementRegion>, String> {
662    arrange_segments_impl(segments, tolerance, true, true)
663}
664
665fn arrange_segments_impl(
666    segments: &[Segment2],
667    tolerance: f64,
668    indexed: bool,
669    indexed_nodes: bool,
670) -> Result<Vec<ArrangementRegion>, String> {
671    let defer_tags = switch!("BREP_ARRANGE_DEFER_TAGS", true);
672    let mut cuts = vec![Vec::<f64>::new(); segments.len()];
673    let mut intersect_pair = |first: usize, second: usize| {
674        let Some([first_parameter, second_parameter]) = segment_intersection(
675            segments[first].a,
676            segments[first].b,
677            segments[second].a,
678            segments[second].b,
679            tolerance,
680        ) else {
681            return;
682        };
683        let first_tolerance = tolerance_parameter(&segments[first], tolerance);
684        let second_tolerance = tolerance_parameter(&segments[second], tolerance);
685        if first_parameter > first_tolerance && first_parameter < 1.0 - first_tolerance {
686            cuts[first].push(first_parameter);
687        }
688        if second_parameter > second_tolerance && second_parameter < 1.0 - second_tolerance {
689            cuts[second].push(second_parameter);
690        }
691    };
692    if indexed {
693        visit_segment_pairs(segments, tolerance, &mut intersect_pair);
694    } else {
695        for first in 0..segments.len() {
696            for second in first + 1..segments.len() {
697                intersect_pair(first, second);
698            }
699        }
700    }
701
702    let mut pieces = Vec::new();
703    for (index, segment) in segments.iter().enumerate() {
704        let mut parameters = vec![0.0];
705        cuts[index].sort_by(f64::total_cmp);
706        parameters.extend(cuts[index].iter().copied());
707        parameters.push(1.0);
708        let parameter_tolerance = tolerance_parameter(segment, tolerance);
709        let mut deduplicated: Vec<f64> = Vec::new();
710        for parameter in parameters {
711            if deduplicated
712                .last()
713                .is_none_or(|previous| parameter - *previous > parameter_tolerance)
714            {
715                deduplicated.push(parameter);
716            } else if parameter == 1.0 {
717                *deduplicated.last_mut().unwrap() = 1.0;
718            }
719        }
720        for pair in deduplicated.windows(2) {
721            let a = interpolate(segment.a, segment.b, pair[0]);
722            let b = interpolate(segment.a, segment.b, pair[1]);
723            if a.distance(b) <= tolerance {
724                continue;
725            }
726            pieces.push(PieceInput {
727                a,
728                b,
729                parent: if defer_tags { std::borrow::Cow::Borrowed(segment) } else { std::borrow::Cow::Owned(segment.clone()) },
730            });
731        }
732    }
733
734    let mut nodes: Vec<Node> = Vec::new();
735    let mut lookup = NodeLookup::new(tolerance, indexed_nodes && pieces.len() > 64);
736    let mut piece_start = Vec::with_capacity(pieces.len());
737    let mut piece_end = Vec::with_capacity(pieces.len());
738    for piece in &pieces {
739        piece_start.push(lookup.find_or_insert(piece.a, &mut nodes));
740        piece_end.push(lookup.find_or_insert(piece.b, &mut nodes));
741    }
742
743    let mut alive = vec![true; pieces.len()];
744    loop {
745        let mut pruned = false;
746        let mut degree = vec![0usize; nodes.len()];
747        for index in 0..pieces.len() {
748            if !alive[index] {
749                continue;
750            }
751            if piece_start[index] == piece_end[index] {
752                alive[index] = false;
753                pruned = true;
754                continue;
755            }
756            degree[piece_start[index]] += 1;
757            degree[piece_end[index]] += 1;
758        }
759        for index in 0..pieces.len() {
760            if alive[index] && (degree[piece_start[index]] == 1 || degree[piece_end[index]] == 1) {
761                alive[index] = false;
762                pruned = true;
763            }
764        }
765        if !pruned {
766            break;
767        }
768    }
769
770    let half_tail = |half_edge: usize| {
771        if half_edge % 2 == 0 {
772            piece_start[half_edge >> 1]
773        } else {
774            piece_end[half_edge >> 1]
775        }
776    };
777    let half_head = |half_edge: usize| {
778        if half_edge % 2 == 0 {
779            piece_end[half_edge >> 1]
780        } else {
781            piece_start[half_edge >> 1]
782        }
783    };
784    for node in &mut nodes {
785        node.outgoing.clear();
786    }
787    for index in 0..pieces.len() {
788        if !alive[index] {
789            continue;
790        }
791        nodes[piece_start[index]].outgoing.push(index * 2);
792        nodes[piece_end[index]].outgoing.push(index * 2 + 1);
793    }
794    let angles: Vec<f64> = (0..pieces.len() * 2)
795        .map(|half_edge| {
796            let tail = nodes[half_tail(half_edge)].point;
797            let head = nodes[half_head(half_edge)].point;
798            (head.y - tail.y).atan2(head.x - tail.x)
799        })
800        .collect();
801    for node in &mut nodes {
802        node.outgoing
803            .sort_by(|a, b| angles[*a].total_cmp(&angles[*b]));
804    }
805
806    let mut visited = rustc_hash::FxHashSet::default();
807    let mut positive = Vec::new();
808    let mut negative = Vec::new();
809    for index in 0..pieces.len() {
810        if !alive[index] {
811            continue;
812        }
813        for start in [index * 2, index * 2 + 1] {
814            if visited.contains(&start) {
815                continue;
816            }
817            let mut uses = if defer_tags { CycleUses::Deferred(Vec::new()) } else { CycleUses::Eager(Vec::new()) };
818            let mut node_indices = Vec::new();
819            let mut area = 0.0;
820            let mut half_edge = start;
821            let mut guard = 0;
822            loop {
823                visited.insert(half_edge);
824                uses.push(half_edge, &pieces);
825                let tail_index = half_tail(half_edge);
826                let head_index = half_head(half_edge);
827                let tail = nodes[tail_index].point;
828                let head = nodes[head_index].point;
829                area += 0.5 * (tail.x * head.y - head.x * tail.y);
830                node_indices.push(tail_index);
831                let reverse = half_edge ^ 1;
832                let outgoing = &nodes[head_index].outgoing;
833                let reverse_index = outgoing
834                    .iter()
835                    .position(|candidate| *candidate == reverse)
836                    .ok_or_else(|| "arrangeSegments: reverse half-edge missing".to_string())?;
837                half_edge = outgoing[(reverse_index + outgoing.len() - 1) % outgoing.len()];
838                guard += 1;
839                if guard > pieces.len() * 4 + 8 {
840                    return Err("arrangeSegments: face walk did not terminate".into());
841                }
842                if half_edge == start {
843                    break;
844                }
845            }
846            let cycle = Cycle {
847                uses,
848                area,
849                node_indices,
850            };
851            if area > tolerance * tolerance {
852                positive.push(cycle);
853            } else if area < -tolerance * tolerance {
854                negative.push(cycle);
855            }
856        }
857    }
858
859    positive.sort_by(|a, b| a.area.total_cmp(&b.area));
860    let mut regions: Vec<(ArrangementRegion, Vec<Vec2>)> = positive
861        .into_iter()
862        .map(|cycle| {
863            let polygon = cycle
864                .node_indices
865                .iter()
866                .map(|index| nodes[*index].point)
867                .collect();
868            (
869                ArrangementRegion {
870                    outer: cycle.uses.into_uses(&pieces),
871                    holes: Vec::new(),
872                    area: cycle.area,
873                    outer_area: cycle.area,
874                },
875                polygon,
876            )
877        })
878        .collect();
879    let hole_boxes = hole_box_reject_enabled();
880    let boxes: Vec<[f64; 5]> = if hole_boxes {
881        regions.iter().map(|(_, polygon)| polygon_reject_box(polygon, tolerance)).collect()
882    } else {
883        Vec::new()
884    };
885    let mut bands: Vec<Option<BoundaryBand>> = (0..regions.len()).map(|_| None).collect();
886    for cycle in negative {
887        for (region_index, (region, polygon)) in regions.iter_mut().enumerate() {
888            let mut inside = false;
889            let mut on_boundary = false;
890            for node_index in &cycle.node_indices {
891                let point = nodes[*node_index].point;
892                let class = if hole_boxes && outside_reject_box(point, &boxes[region_index]) {
893                    PolygonClass::Outside
894                } else if hole_boxes {
895                    let band = bands[region_index].get_or_insert_with(|| BoundaryBand::new(polygon, tolerance));
896                    band.classify(point, polygon, tolerance)
897                } else {
898                    point_in_polygon_class(point, polygon, tolerance)
899                };
900                match class {
901                    PolygonClass::Boundary => {
902                        on_boundary = true;
903                        continue;
904                    }
905                    PolygonClass::Inside => {
906                        inside = true;
907                        on_boundary = false;
908                        break;
909                    }
910                    PolygonClass::Outside => {
911                        inside = false;
912                        on_boundary = false;
913                        break;
914                    }
915                }
916            }
917            if on_boundary {
918                continue;
919            }
920            if inside {
921                region.holes.push(cycle.uses.copy_uses(&pieces));
922                region.area += cycle.area;
923                break;
924            }
925        }
926    }
927    if crate::profile::profile_enabled() {
928        let holes: usize = regions.iter().flat_map(|(r, _)| r.holes.iter()).map(Vec::len).sum();
929        let returned: usize = holes + regions.iter().map(|(r, _)| r.outer.len()).sum::<usize>();
930        let clones = if defer_tags { returned } else { pieces.len() + visited.len() + holes };
931        crate::imprint::profile_emit(format_args!("arrange.tags segments={} pieces={} walked={} returned={returned} parent_clones={clones} deferred={defer_tags}", segments.len(), pieces.len(), visited.len()));
932    }
933    Ok(regions.into_iter().map(|(region, _)| region).collect())
934}
935