Skip to main content

brepkit_math/
polygon_boolean.rs

1//! Robust 2D boolean operations on simple polygons (union, intersection,
2//! difference).
3//!
4//! # Approach
5//!
6//! Rather than weaving a doubly-linked list through coincident vertices
7//! (the classic Greiner–Hormann hazard), this implementation builds a planar
8//! arrangement and classifies *directed sub-edges* by their **midpoints**:
9//!
10//! 1. Every edge of `A` is split at all points where it meets `B` (proper
11//!    crossings, vertex-on-edge T-junctions, and the endpoints of any
12//!    collinear-overlap), and vice versa.
13//! 2. All split points are *snapped* to a tolerance grid so that points
14//!    arising independently from `A` and `B` collapse to bit-identical
15//!    coordinates. This is what eliminates sliver artifacts from
16//!    near-coincident edges.
17//! 3. Each resulting sub-edge is classified by sampling its midpoint against
18//!    the *other* polygon: `Outside`, `Inside`, or `OnBoundary` (with the
19//!    relative direction of the shared boundary recorded).
20//! 4. Sub-edges are selected per the operation, then traced into closed loops
21//!    by following snapped coordinates.
22//! 5. Loops are classified as outer (CCW) or hole (CW) by signed area and
23//!    assembled into a [`PolygonBooleanResult`].
24//!
25//! Deciding inside/outside on a midpoint — a point in the *relative interior*
26//! of a sub-edge, away from the singular intersection vertices — is what makes
27//! the degenerate cases (collinear overlap, T-junctions, shared edges, corner
28//! touches) robust: the classification never has to disambiguate behaviour
29//! *at* a shared vertex.
30//!
31//! # Tolerance model
32//!
33//! `tol` is an absolute linear tolerance in the polygons' coordinate units.
34//! Two points within `tol` of each other are treated as identical (snapped to
35//! a shared grid cell of size `tol`); a point within `tol` of an edge is
36//! treated as lying on it; an edge pair whose overlap exceeds `tol` in length
37//! is treated as collinear-shared. Pass the same `tol` you use elsewhere for
38//! the geometry in question (e.g. `Tolerance::default().linear`, or a looser
39//! value for coarse data).
40
41use crate::madd::Madd;
42use crate::predicates::winding_number;
43use crate::vec::Point2;
44
45/// Which boolean operation to perform.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum BooleanOp {
48    /// `A ∪ B` — points in either polygon.
49    Union,
50    /// `A ∩ B` — points in both polygons.
51    Intersection,
52    /// `A \ B` — points in `A` but not `B`.
53    Difference,
54}
55
56/// The result of a polygon boolean operation.
57///
58/// Winding convention: every `outer` loop is counter-clockwise (positive
59/// signed area) and every `hole` loop is clockwise (negative signed area).
60/// A point is "in" the result when it is inside an odd nesting of these loops
61/// per the even-odd rule; equivalently, inside some `outer` and not inside any
62/// `hole` contained by that outer.
63///
64/// A disjoint union yields multiple `outer` loops and no holes; a union that
65/// encloses a void yields one `outer` and one `hole`; a fully-degenerate or
66/// empty result yields both vectors empty.
67#[derive(Debug, Clone, Default, PartialEq)]
68pub struct PolygonBooleanResult {
69    /// Counter-clockwise outer boundary loops.
70    pub outer: Vec<Vec<Point2>>,
71    /// Clockwise hole loops (voids).
72    pub holes: Vec<Vec<Point2>>,
73}
74
75impl PolygonBooleanResult {
76    /// `true` when the operation produced no geometry.
77    #[must_use]
78    pub fn is_empty(&self) -> bool {
79        self.outer.is_empty() && self.holes.is_empty()
80    }
81
82    /// Total signed area: sum of outer-loop areas minus hole-loop areas.
83    ///
84    /// Because outers are CCW (positive) and holes CW (negative), this is the
85    /// plain sum of every loop's signed area, and equals the covered area.
86    #[must_use]
87    pub fn area(&self) -> f64 {
88        let mut total = 0.0;
89        for loop_pts in &self.outer {
90            total += signed_area(loop_pts);
91        }
92        for loop_pts in &self.holes {
93            total += signed_area(loop_pts);
94        }
95        total
96    }
97}
98
99/// Union of two simple polygons.
100///
101/// Both inputs should be simple (non-self-intersecting) polygons; orientation
102/// is normalized internally, so either winding is accepted. Returns the outer
103/// loop(s) of the union; holes (if the union encloses a void) are dropped from
104/// this convenience wrapper — use [`polygon_boolean`] if you need them.
105///
106/// Returns an empty `Vec` if either input is degenerate (fewer than 3
107/// non-collinear vertices) or the arrangement could not be traced.
108#[must_use]
109pub fn polygon_union(a: &[Point2], b: &[Point2], tol: f64) -> Vec<Vec<Point2>> {
110    polygon_boolean(a, b, BooleanOp::Union, tol).outer
111}
112
113/// General boolean of two simple polygons.
114///
115/// Orientation of the inputs is normalized internally (either winding is
116/// accepted). For [`BooleanOp::Difference`] the operation is `A \ B`.
117///
118/// Returns an empty [`PolygonBooleanResult`] if an input is degenerate or the
119/// arrangement could not be traced into closed loops; it never panics and
120/// never returns a silently-wrong partial result.
121#[must_use]
122#[allow(clippy::too_many_lines)]
123pub fn polygon_boolean(
124    a: &[Point2],
125    b: &[Point2],
126    op: BooleanOp,
127    tol: f64,
128) -> PolygonBooleanResult {
129    let tol = if tol > 0.0 && tol.is_finite() {
130        tol
131    } else {
132        return PolygonBooleanResult::default();
133    };
134
135    let poly_a = match Polygon::normalized(a, tol) {
136        Some(p) => p,
137        None => return degenerate_fallback(a, b, op, tol),
138    };
139    let poly_b = match Polygon::normalized(b, tol) {
140        Some(p) => p,
141        None => return degenerate_fallback(a, b, op, tol),
142    };
143
144    // Split each polygon's edges at every interaction with the other, snapping
145    // all split coordinates to a shared grid so coincident points merge.
146    let snapper = Snapper::new(tol);
147    let edges_a = split_polygon(&poly_a, &poly_b, &snapper, tol);
148    let edges_b = split_polygon(&poly_b, &poly_a, &snapper, tol);
149
150    // Classify and select directed sub-edges per the operation.
151    let mut selected: Vec<DirectedEdge> = Vec::new();
152    select_edges(
153        &edges_a,
154        &poly_b,
155        op,
156        EdgeSource::A,
157        &snapper,
158        tol,
159        &mut selected,
160    );
161    select_edges(
162        &edges_b,
163        &poly_a,
164        op,
165        EdgeSource::B,
166        &snapper,
167        tol,
168        &mut selected,
169    );
170
171    if selected.is_empty() {
172        return PolygonBooleanResult::default();
173    }
174
175    let loops = trace_loops(selected, &snapper, tol);
176    classify_loops(loops, tol)
177}
178
179// ===========================================================================
180// Geometry helpers
181// ===========================================================================
182
183/// Signed area via the shoelace formula. Positive for CCW, negative for CW.
184#[must_use]
185pub fn signed_area(polygon: &[Point2]) -> f64 {
186    let n = polygon.len();
187    if n < 3 {
188        return 0.0;
189    }
190    // Taken from the first vertex: far from the origin the products of raw
191    // coordinates round away a small polygon's whole area.
192    let origin = polygon[0];
193    let mut sum = 0.0;
194    for i in 0..n {
195        let p = polygon[i] - origin;
196        let q = polygon[(i + 1) % n] - origin;
197        sum += p.x().madd(q.y(), -(q.x() * p.y()));
198    }
199    sum * 0.5
200}
201
202fn dist_sq(a: Point2, b: Point2) -> f64 {
203    let dx = a.x() - b.x();
204    let dy = a.y() - b.y();
205    dx.madd(dx, dy * dy)
206}
207
208/// Distance squared from `p` to the *segment* `[a, b]` (clamped to the
209/// segment, unlike the infinite-line variant in `polygon2d`).
210fn point_segment_dist_sq(p: Point2, a: Point2, b: Point2) -> f64 {
211    let abx = b.x() - a.x();
212    let aby = b.y() - a.y();
213    let len_sq = abx.madd(abx, aby * aby);
214    if len_sq < f64::MIN_POSITIVE {
215        return dist_sq(p, a);
216    }
217    let t = (((p.x() - a.x()) * abx) + ((p.y() - a.y()) * aby)) / len_sq;
218    let t = t.clamp(0.0, 1.0);
219    let proj = Point2::new(a.x() + t * abx, a.y() + t * aby);
220    dist_sq(p, proj)
221}
222
223/// Parameter of the projection of `p` onto the infinite line through `[a, b]`,
224/// expressed in `[0, 1]` over the segment (may fall outside `[0, 1]`).
225fn project_param(p: Point2, a: Point2, b: Point2) -> f64 {
226    let abx = b.x() - a.x();
227    let aby = b.y() - a.y();
228    let len_sq = abx.madd(abx, aby * aby);
229    if len_sq < f64::MIN_POSITIVE {
230        return 0.0;
231    }
232    (((p.x() - a.x()) * abx) + ((p.y() - a.y()) * aby)) / len_sq
233}
234
235fn lerp(a: Point2, b: Point2, t: f64) -> Point2 {
236    Point2::new(a.x() + t * (b.x() - a.x()), a.y() + t * (b.y() - a.y()))
237}
238
239// ===========================================================================
240// Coordinate snapping
241// ===========================================================================
242
243/// Snaps coordinates to a grid of cell size `tol` so that points arising
244/// independently from the two polygons collapse to identical values. This is
245/// the mechanism that removes spurious micro-edges (slivers): two vertices
246/// closer than `tol` round to the same grid cell and therefore the same key.
247#[derive(Clone, Copy)]
248struct Snapper {
249    inv: f64,
250    cell: f64,
251}
252
253impl Snapper {
254    fn new(tol: f64) -> Self {
255        // Use a cell a touch larger than tol so that two points up to `tol`
256        // apart reliably land in the same cell after rounding.
257        let cell = tol.max(f64::MIN_POSITIVE);
258        Self {
259            inv: 1.0 / cell,
260            cell,
261        }
262    }
263
264    /// Integer grid key for a coordinate (used for equality / adjacency).
265    fn key(&self, p: Point2) -> (i64, i64) {
266        // round half away from zero, deterministic for finite inputs
267        let kx = (p.x() * self.inv).round();
268        let ky = (p.y() * self.inv).round();
269        (kx as i64, ky as i64)
270    }
271
272    /// Canonical snapped position for a coordinate.
273    fn snap(&self, p: Point2) -> Point2 {
274        let (kx, ky) = self.key(p);
275        Point2::new(kx as f64 * self.cell, ky as f64 * self.cell)
276    }
277}
278
279// ===========================================================================
280// Normalized polygon
281// ===========================================================================
282
283/// A CCW, duplicate-free simple polygon ready for arrangement.
284struct Polygon {
285    /// Vertices in CCW order, no two consecutive within `tol`.
286    verts: Vec<Point2>,
287}
288
289impl Polygon {
290    /// Clean and orient an input ring. Returns `None` if it is degenerate
291    /// (fewer than 3 distinct vertices or zero signed area).
292    fn normalized(input: &[Point2], tol: f64) -> Option<Self> {
293        if input.len() < 3 {
294            return None;
295        }
296        // Drop consecutive (and wrap-around) near-duplicates.
297        let mut verts: Vec<Point2> = Vec::with_capacity(input.len());
298        for &p in input {
299            if let Some(&last) = verts.last()
300                && dist_sq(p, last) <= tol * tol
301            {
302                continue;
303            }
304            verts.push(p);
305        }
306        while verts.len() >= 2 {
307            let first = verts[0];
308            let last = verts[verts.len() - 1];
309            if dist_sq(first, last) <= tol * tol {
310                verts.pop();
311            } else {
312                break;
313            }
314        }
315        if verts.len() < 3 {
316            return None;
317        }
318
319        let area = signed_area(&verts);
320        if area.abs() <= tol * tol {
321            return None;
322        }
323        if area < 0.0 {
324            verts.reverse();
325        }
326        Some(Self { verts })
327    }
328
329    fn len(&self) -> usize {
330        self.verts.len()
331    }
332
333    fn vert(&self, i: usize) -> Point2 {
334        self.verts[i % self.verts.len()]
335    }
336
337    fn as_slice(&self) -> &[Point2] {
338        &self.verts
339    }
340}
341
342// ===========================================================================
343// Edge splitting
344// ===========================================================================
345
346/// A directed sub-edge produced by splitting, before classification.
347struct SubEdge {
348    start: Point2,
349    end: Point2,
350}
351
352/// Split every edge of `subject` at all parameters where it interacts with any
353/// edge of `other` (crossings, T-junctions, collinear-overlap endpoints).
354/// Endpoints are snapped; zero-length results are dropped.
355fn split_polygon(subject: &Polygon, other: &Polygon, snapper: &Snapper, tol: f64) -> Vec<SubEdge> {
356    let mut out = Vec::new();
357    let n = subject.len();
358    for i in 0..n {
359        let a1 = subject.vert(i);
360        let a2 = subject.vert(i + 1);
361
362        // Collect split parameters in (0, 1) along this edge.
363        let mut params: Vec<f64> = Vec::new();
364        let m = other.len();
365        for j in 0..m {
366            let b1 = other.vert(j);
367            let b2 = other.vert(j + 1);
368            collect_edge_split_params(a1, a2, b1, b2, tol, &mut params);
369        }
370
371        // Snap-deduplicate parameters and clamp to the open interval.
372        params.retain(|&t| t > 0.0 && t < 1.0);
373        params.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
374        dedup_params(&mut params, a1, a2, tol);
375
376        // Emit sub-edges between consecutive break points.
377        let mut prev = snapper.snap(a1);
378        let mut cuts: Vec<Point2> = Vec::with_capacity(params.len());
379        for &t in &params {
380            cuts.push(snapper.snap(lerp(a1, a2, t)));
381        }
382        cuts.push(snapper.snap(a2));
383        for pt in cuts {
384            if dist_sq(prev, pt) > tol * tol {
385                out.push(SubEdge {
386                    start: prev,
387                    end: pt,
388                });
389            }
390            prev = pt;
391        }
392    }
393    out
394}
395
396/// Append the parameters along edge `[a1, a2]` (in `[0, 1]`) at which it should
397/// be split because of edge `[b1, b2]`: proper crossings, the projection of
398/// each `b` endpoint that lies on the segment (T-junction), and the endpoints
399/// of a collinear overlap.
400fn collect_edge_split_params(
401    a1: Point2,
402    a2: Point2,
403    b1: Point2,
404    b2: Point2,
405    tol: f64,
406    params: &mut Vec<f64>,
407) {
408    let tol_sq = tol * tol;
409
410    // Endpoints of B that lie on segment A → T-junctions / shared vertices.
411    for &bp in &[b1, b2] {
412        if point_segment_dist_sq(bp, a1, a2) <= tol_sq {
413            let t = project_param(bp, a1, a2);
414            if t > 0.0 && t < 1.0 {
415                params.push(t);
416            }
417        }
418    }
419
420    // Collinear overlap: if both B endpoints are on the *line* of A, the
421    // overlap interval's interior endpoints become split points. (Endpoint
422    // T-junctions above already cover the shared-vertex case; this adds the
423    // case where A extends past the overlap on one or both sides.)
424    let d_b1 = point_line_dist_sq(b1, a1, a2);
425    let d_b2 = point_line_dist_sq(b2, a1, a2);
426    if d_b1 <= tol_sq && d_b2 <= tol_sq {
427        // Both endpoints collinear with A; their projections clip the overlap.
428        let tb1 = project_param(b1, a1, a2);
429        let tb2 = project_param(b2, a1, a2);
430        for t in [tb1, tb2] {
431            if t > 0.0 && t < 1.0 {
432                params.push(t);
433            }
434        }
435        return;
436    }
437
438    // Proper (transversal) intersection in the interior of both segments.
439    if let Some((ta, _tb)) = segment_intersection_params(a1, a2, b1, b2)
440        && ta > 0.0
441        && ta < 1.0
442    {
443        params.push(ta);
444    }
445}
446
447/// Squared distance from `p` to the *infinite line* through `[a, b]`.
448fn point_line_dist_sq(p: Point2, a: Point2, b: Point2) -> f64 {
449    let dx = b.x() - a.x();
450    let dy = b.y() - a.y();
451    let len_sq = dx.madd(dx, dy * dy);
452    if len_sq < f64::MIN_POSITIVE {
453        return dist_sq(p, a);
454    }
455    let cross = (p.x() - a.x()).madd(dy, -((p.y() - a.y()) * dx));
456    (cross * cross) / len_sq
457}
458
459/// Parameters `(ta, tb)` of a proper line-line intersection, or `None` when
460/// the segments are parallel/collinear (handled separately).
461fn segment_intersection_params(
462    a1: Point2,
463    a2: Point2,
464    b1: Point2,
465    b2: Point2,
466) -> Option<(f64, f64)> {
467    let dax = a2.x() - a1.x();
468    let day = a2.y() - a1.y();
469    let dbx = b2.x() - b1.x();
470    let dby = b2.y() - b1.y();
471    let denom = dax.madd(dby, -(day * dbx));
472    if denom.abs() < f64::MIN_POSITIVE {
473        return None;
474    }
475    let rx = b1.x() - a1.x();
476    let ry = b1.y() - a1.y();
477    let ta = rx.madd(dby, -(ry * dbx)) / denom;
478    let tb = rx.madd(day, -(ry * dax)) / denom;
479    if (0.0..=1.0).contains(&tb) {
480        Some((ta, tb))
481    } else {
482        None
483    }
484}
485
486/// Remove parameters whose snapped 3D positions coincide within `tol`.
487fn dedup_params(params: &mut Vec<f64>, a1: Point2, a2: Point2, tol: f64) {
488    if params.is_empty() {
489        return;
490    }
491    let tol_sq = tol * tol;
492    let mut kept: Vec<f64> = Vec::with_capacity(params.len());
493    for &t in params.iter() {
494        let pt = lerp(a1, a2, t);
495        let is_dup = kept
496            .last()
497            .is_some_and(|&pt_t| dist_sq(lerp(a1, a2, pt_t), pt) <= tol_sq);
498        if !is_dup {
499            kept.push(t);
500        }
501    }
502    *params = kept;
503}
504
505// ===========================================================================
506// Edge classification + selection
507// ===========================================================================
508
509#[derive(Clone, Copy, PartialEq, Eq)]
510enum EdgeSource {
511    A,
512    B,
513}
514
515/// A selected directed edge feeding the loop tracer.
516struct DirectedEdge {
517    start: Point2,
518    end: Point2,
519}
520
521/// Position of a sub-edge midpoint relative to the other polygon.
522enum MidClass {
523    Inside,
524    Outside,
525    /// The sub-edge lies on the other polygon's boundary; `same_dir` is true
526    /// when both boundaries run in the same direction along this sub-edge.
527    OnBoundary {
528        same_dir: bool,
529    },
530}
531
532#[allow(clippy::too_many_arguments)]
533fn select_edges(
534    edges: &[SubEdge],
535    other: &Polygon,
536    op: BooleanOp,
537    source: EdgeSource,
538    snapper: &Snapper,
539    tol: f64,
540    out: &mut Vec<DirectedEdge>,
541) {
542    for e in edges {
543        let class = classify_midpoint(e, other, snapper, tol);
544        let keep = match (op, source, &class) {
545            // --- Union: boundary of A∪B = parts of each outside the other,
546            // plus each shared edge once (counted on A, same direction). ---
547            (BooleanOp::Union, _, MidClass::Outside) => Keep::Forward,
548            (BooleanOp::Union, EdgeSource::A, MidClass::OnBoundary { same_dir: true }) => {
549                Keep::Forward
550            }
551            (BooleanOp::Union, _, _) => Keep::Drop,
552
553            // --- Intersection: boundary = parts of each inside the other,
554            // plus each shared (same-direction) edge once (on A). ---
555            (BooleanOp::Intersection, _, MidClass::Inside) => Keep::Forward,
556            (BooleanOp::Intersection, EdgeSource::A, MidClass::OnBoundary { same_dir: true }) => {
557                Keep::Forward
558            }
559            (BooleanOp::Intersection, _, _) => Keep::Drop,
560
561            // --- Difference A\B: A's parts outside B (forward), B's parts
562            // inside A (reversed, so the hole winds CW), plus opposite-
563            // direction shared edges (on A, forward). ---
564            (BooleanOp::Difference, EdgeSource::A, MidClass::Outside) => Keep::Forward,
565            (BooleanOp::Difference, EdgeSource::B, MidClass::Inside) => Keep::Reverse,
566            (BooleanOp::Difference, EdgeSource::A, MidClass::OnBoundary { same_dir: false }) => {
567                Keep::Forward
568            }
569            (BooleanOp::Difference, _, _) => Keep::Drop,
570        };
571
572        match keep {
573            Keep::Forward => out.push(DirectedEdge {
574                start: e.start,
575                end: e.end,
576            }),
577            Keep::Reverse => out.push(DirectedEdge {
578                start: e.end,
579                end: e.start,
580            }),
581            Keep::Drop => {}
582        }
583    }
584}
585
586enum Keep {
587    Forward,
588    Reverse,
589    Drop,
590}
591
592/// Classify a sub-edge by its midpoint against `other`.
593fn classify_midpoint(e: &SubEdge, other: &Polygon, snapper: &Snapper, tol: f64) -> MidClass {
594    let mid = Point2::new(
595        f64::midpoint(e.start.x(), e.end.x()),
596        f64::midpoint(e.start.y(), e.end.y()),
597    );
598
599    // On-boundary test: is the midpoint within tol of some edge of `other`,
600    // collinear with it? If so the whole sub-edge is a shared boundary segment
601    // (it was split precisely so that it does not straddle a boundary vertex).
602    let tol_sq = tol * tol;
603    let edir = e.end - e.start;
604    let mut on_boundary: Option<bool> = None;
605    let m = other.len();
606    for j in 0..m {
607        let b1 = other.vert(j);
608        let b2 = other.vert(j + 1);
609        if point_segment_dist_sq(mid, b1, b2) <= tol_sq {
610            // Same direction iff the dot of edge directions is positive.
611            let bdir = b2 - b1;
612            let dot = edir.x().madd(bdir.x(), edir.y() * bdir.y());
613            on_boundary = Some(dot >= 0.0);
614            break;
615        }
616    }
617    if let Some(same_dir) = on_boundary {
618        return MidClass::OnBoundary { same_dir };
619    }
620
621    // Interior test by winding number on the snapped ring (consistent keys).
622    let snapped: Vec<Point2> = other.as_slice().iter().map(|&p| snapper.snap(p)).collect();
623    if winding_number(snapper.snap(mid), &snapped) != 0 {
624        MidClass::Inside
625    } else {
626        MidClass::Outside
627    }
628}
629
630// ===========================================================================
631// Loop tracing
632// ===========================================================================
633
634/// Trace selected directed edges into closed loops by following snapped
635/// coordinates. At a junction shared by several outgoing edges (a pinch
636/// vertex, e.g. two polygons touching at a corner) the next edge is chosen by
637/// the most counter-clockwise turn from the incoming direction; this hugs one
638/// face at a time and separates the faces meeting at the pinch instead of
639/// weaving them into a figure-eight.
640fn trace_loops(edges: Vec<DirectedEdge>, snapper: &Snapper, tol: f64) -> Vec<Vec<Point2>> {
641    use std::collections::HashMap;
642
643    // Adjacency: snapped start key → list of edge indices leaving it.
644    let mut adjacency: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
645    for (idx, e) in edges.iter().enumerate() {
646        adjacency.entry(snapper.key(e.start)).or_default().push(idx);
647    }
648
649    let mut used = vec![false; edges.len()];
650    let mut loops: Vec<Vec<Point2>> = Vec::new();
651
652    for start_idx in 0..edges.len() {
653        if used[start_idx] {
654            continue;
655        }
656        let mut loop_pts: Vec<Point2> = Vec::new();
657        let mut current = start_idx;
658        let mut guard = 0usize;
659        let max_steps = edges.len() + 1;
660
661        loop {
662            if used[current] {
663                break;
664            }
665            used[current] = true;
666            let e = &edges[current];
667            loop_pts.push(e.start);
668            let end_key = snapper.key(e.end);
669
670            // Find the best unused outgoing edge from `end`.
671            let Some(candidates) = adjacency.get(&end_key) else {
672                break;
673            };
674            let incoming_dir = e.end - e.start;
675            let mut best: Option<usize> = None;
676            let mut best_score = f64::NEG_INFINITY;
677            for &cand in candidates {
678                if used[cand] {
679                    continue;
680                }
681                let ce = &edges[cand];
682                let out_dir = ce.end - ce.start;
683                let score = turn_score(incoming_dir, out_dir);
684                if score > best_score {
685                    best_score = score;
686                    best = Some(cand);
687                }
688            }
689
690            match best {
691                Some(next) => current = next,
692                None => break,
693            }
694
695            guard += 1;
696            if guard > max_steps {
697                break;
698            }
699
700            // Closed the loop: arrived back at the first edge of this walk.
701            if current == start_idx {
702                break;
703            }
704        }
705
706        // Accept only genuinely closed, non-degenerate loops.
707        if loop_pts.len() >= 3 {
708            let area = signed_area(&loop_pts);
709            if area.abs() > tol * tol {
710                loops.push(loop_pts);
711            }
712        }
713    }
714
715    loops
716}
717
718/// Signed turn angle (radians, in `(-pi, pi]`) from the `incoming` direction to
719/// the `outgoing` direction. Larger = more counter-clockwise; the tracer picks
720/// the maximum so it consistently takes the leftmost branch at a junction.
721fn turn_score(incoming: crate::vec::Vec2, outgoing: crate::vec::Vec2) -> f64 {
722    let inx = incoming.x();
723    let iny = incoming.y();
724    let outx = outgoing.x();
725    let outy = outgoing.y();
726    let dot = inx.madd(outx, iny * outy);
727    let cross = inx.madd(outy, -(iny * outx));
728    cross.atan2(dot)
729}
730
731// ===========================================================================
732// Loop classification
733// ===========================================================================
734
735/// Split traced loops into CCW outers and CW holes per their signed area.
736fn classify_loops(loops: Vec<Vec<Point2>>, tol: f64) -> PolygonBooleanResult {
737    let mut result = PolygonBooleanResult::default();
738    for loop_pts in loops {
739        let area = signed_area(&loop_pts);
740        if area.abs() <= tol * tol {
741            continue;
742        }
743        if area > 0.0 {
744            result.outer.push(loop_pts);
745        } else {
746            result.holes.push(loop_pts);
747        }
748    }
749    result
750}
751
752// ===========================================================================
753// Degenerate fallbacks
754// ===========================================================================
755
756/// When one input is degenerate (collapses to < 3 vertices / zero area), the
757/// boolean reduces to a trivial case rather than failing outright.
758fn degenerate_fallback(
759    a: &[Point2],
760    b: &[Point2],
761    op: BooleanOp,
762    tol: f64,
763) -> PolygonBooleanResult {
764    let pa = Polygon::normalized(a, tol);
765    let pb = Polygon::normalized(b, tol);
766    match (pa, pb) {
767        (None, None) => PolygonBooleanResult::default(),
768        (Some(p), None) => {
769            // B is empty: A∪∅ = A, A∩∅ = ∅, A\∅ = A.
770            match op {
771                BooleanOp::Union | BooleanOp::Difference => single_outer(p),
772                BooleanOp::Intersection => PolygonBooleanResult::default(),
773            }
774        }
775        (None, Some(p)) => {
776            // A is empty: ∅∪B = B, ∅∩B = ∅, ∅\B = ∅.
777            match op {
778                BooleanOp::Union => single_outer(p),
779                BooleanOp::Intersection | BooleanOp::Difference => PolygonBooleanResult::default(),
780            }
781        }
782        // Both valid: caller should not have routed here, but be safe.
783        (Some(_), Some(_)) => PolygonBooleanResult::default(),
784    }
785}
786
787fn single_outer(p: Polygon) -> PolygonBooleanResult {
788    PolygonBooleanResult {
789        outer: vec![p.verts],
790        holes: Vec::new(),
791    }
792}
793
794#[cfg(test)]
795#[allow(clippy::unwrap_used, clippy::expect_used, clippy::float_cmp)]
796mod tests {
797    use super::*;
798
799    fn sq(x0: f64, y0: f64, s: f64) -> Vec<Point2> {
800        vec![
801            Point2::new(x0, y0),
802            Point2::new(x0 + s, y0),
803            Point2::new(x0 + s, y0 + s),
804            Point2::new(x0, y0 + s),
805        ]
806    }
807
808    fn rect(x0: f64, y0: f64, w: f64, h: f64) -> Vec<Point2> {
809        vec![
810            Point2::new(x0, y0),
811            Point2::new(x0 + w, y0),
812            Point2::new(x0 + w, y0 + h),
813            Point2::new(x0, y0 + h),
814        ]
815    }
816
817    const TOL: f64 = 1e-9;
818
819    fn assert_area_close(got: f64, expected: f64, eps: f64) {
820        assert!(
821            (got - expected).abs() <= eps,
822            "area mismatch: got {got}, expected {expected}"
823        );
824    }
825
826    #[test]
827    fn overlapping_squares_union_area() {
828        // A = [0,2]^2, B = [1,3]^2; overlap = [1,2]^2 (area 1).
829        let a = sq(0.0, 0.0, 2.0);
830        let b = sq(1.0, 1.0, 2.0);
831        let res = polygon_boolean(&a, &b, BooleanOp::Union, TOL);
832        assert_eq!(res.outer.len(), 1, "expected one merged outer loop");
833        assert!(res.holes.is_empty(), "no holes expected");
834        assert_area_close(res.area(), 4.0 + 4.0 - 1.0, 1e-7);
835    }
836
837    #[test]
838    fn overlapping_squares_intersection_area() {
839        let a = sq(0.0, 0.0, 2.0);
840        let b = sq(1.0, 1.0, 2.0);
841        let res = polygon_boolean(&a, &b, BooleanOp::Intersection, TOL);
842        assert_eq!(res.outer.len(), 1);
843        assert_area_close(res.area(), 1.0, 1e-7);
844    }
845
846    #[test]
847    fn overlapping_squares_difference_area() {
848        let a = sq(0.0, 0.0, 2.0);
849        let b = sq(1.0, 1.0, 2.0);
850        let res = polygon_boolean(&a, &b, BooleanOp::Difference, TOL);
851        // A minus the overlap [1,2]^2 → area 4 - 1 = 3, L-shaped, no hole.
852        assert!(res.holes.is_empty());
853        assert_area_close(res.area(), 3.0, 1e-7);
854    }
855
856    #[test]
857    fn disjoint_squares_union_two_loops() {
858        let a = sq(0.0, 0.0, 1.0);
859        let b = sq(5.0, 5.0, 1.0);
860        let res = polygon_boolean(&a, &b, BooleanOp::Union, TOL);
861        assert_eq!(res.outer.len(), 2, "disjoint union → two outer loops");
862        assert!(res.holes.is_empty());
863        assert_area_close(res.area(), 2.0, 1e-7);
864    }
865
866    #[test]
867    fn disjoint_squares_intersection_empty() {
868        let a = sq(0.0, 0.0, 1.0);
869        let b = sq(5.0, 5.0, 1.0);
870        let res = polygon_boolean(&a, &b, BooleanOp::Intersection, TOL);
871        assert!(res.is_empty(), "disjoint intersection is empty");
872    }
873
874    #[test]
875    fn nested_union_is_outer() {
876        // B fully inside A; union = A.
877        let a = sq(0.0, 0.0, 10.0);
878        let b = sq(3.0, 3.0, 2.0);
879        let res = polygon_boolean(&a, &b, BooleanOp::Union, TOL);
880        assert_eq!(res.outer.len(), 1);
881        assert!(res.holes.is_empty());
882        assert_area_close(res.area(), 100.0, 1e-6);
883    }
884
885    #[test]
886    fn nested_intersection_is_inner() {
887        let a = sq(0.0, 0.0, 10.0);
888        let b = sq(3.0, 3.0, 2.0);
889        let res = polygon_boolean(&a, &b, BooleanOp::Intersection, TOL);
890        assert_eq!(res.outer.len(), 1);
891        assert_area_close(res.area(), 4.0, 1e-7);
892    }
893
894    #[test]
895    fn nested_difference_makes_hole() {
896        // A with B punched out → outer = A, hole = B, net area 96.
897        let a = sq(0.0, 0.0, 10.0);
898        let b = sq(3.0, 3.0, 2.0);
899        let res = polygon_boolean(&a, &b, BooleanOp::Difference, TOL);
900        assert_eq!(res.outer.len(), 1, "outer boundary preserved");
901        assert_eq!(res.holes.len(), 1, "punched void is a hole");
902        assert_area_close(res.area(), 96.0, 1e-6);
903    }
904
905    #[test]
906    fn shared_partial_edge_sliver_no_artifacts() {
907        // The snapClip case: two rectangles sharing a partial edge with a
908        // ~0.01 overlap. A = [0,10]x[0,5]; B = [0,10]x[5,8] but lifted down by
909        // 0.01 so its bottom edge y=4.99 overlaps A's top region by a sliver.
910        // The union must be a single clean polygon with no micro-edges.
911        let a = rect(0.0, 0.0, 10.0, 5.0);
912        let b = rect(0.0, 4.99, 10.0, 3.01); // top at y=8.0
913        let res = polygon_boolean(&a, &b, BooleanOp::Union, 0.02);
914        assert_eq!(res.outer.len(), 1, "sliver overlap → one merged rectangle");
915        assert!(res.holes.is_empty(), "no sliver holes");
916        // Merged rectangle is [0,10]x[0,8] = 80; overlap area ~0.1 removed once.
917        assert_area_close(res.area(), 80.0, 0.2);
918        // No degenerate micro-edges in the output.
919        for loop_pts in &res.outer {
920            for i in 0..loop_pts.len() {
921                let p = loop_pts[i];
922                let q = loop_pts[(i + 1) % loop_pts.len()];
923                assert!(
924                    dist_sq(p, q) > (0.02 * 0.02),
925                    "found a sliver micro-edge of length {}",
926                    dist_sq(p, q).sqrt()
927                );
928            }
929        }
930    }
931
932    #[test]
933    fn shared_full_edge_union() {
934        // Two unit squares sharing a full edge (x=1) exactly → merged 1x2.
935        let a = sq(0.0, 0.0, 1.0);
936        let b = sq(1.0, 0.0, 1.0);
937        let res = polygon_boolean(&a, &b, BooleanOp::Union, TOL);
938        assert_eq!(res.outer.len(), 1, "shared-edge union is one rectangle");
939        assert!(res.holes.is_empty());
940        assert_area_close(res.area(), 2.0, 1e-7);
941    }
942
943    #[test]
944    fn t_junction_vertex_on_edge() {
945        // B's bottom edge midpoint vertex sits on A's top edge (T-junction):
946        // A = [0,4]x[0,2]; B = [1,3]x[2,4] shares the segment y=2, x∈[1,3].
947        let a = rect(0.0, 0.0, 4.0, 2.0);
948        let b = rect(1.0, 2.0, 2.0, 2.0);
949        let res = polygon_boolean(&a, &b, BooleanOp::Union, TOL);
950        assert_eq!(res.outer.len(), 1, "T-junction union is one polygon");
951        assert!(res.holes.is_empty());
952        assert_area_close(res.area(), 8.0 + 4.0, 1e-7);
953    }
954
955    #[test]
956    fn touching_at_corner_union() {
957        // Squares meeting only at the corner (2,2). Topologically they join
958        // at a pinch point; the covered area is simply the sum, and no
959        // spurious hole is introduced at the pinch.
960        let a = sq(0.0, 0.0, 2.0);
961        let b = sq(2.0, 2.0, 2.0);
962        let res = polygon_boolean(&a, &b, BooleanOp::Union, TOL);
963        assert_area_close(res.area(), 8.0, 1e-7);
964        assert!(
965            res.holes.is_empty(),
966            "corner pinch must not fabricate a hole"
967        );
968        // Every returned outer must enclose positive area (no zero-area pinch
969        // loops leaking through).
970        for loop_pts in &res.outer {
971            assert!(
972                signed_area(loop_pts) > 1e-7,
973                "degenerate outer loop emitted"
974            );
975        }
976    }
977
978    #[test]
979    fn identical_polygons_union_is_same() {
980        let a = sq(0.0, 0.0, 3.0);
981        let res = polygon_boolean(&a, &a, BooleanOp::Union, TOL);
982        assert_eq!(res.outer.len(), 1, "self-union is the polygon");
983        assert!(res.holes.is_empty());
984        assert_area_close(res.area(), 9.0, 1e-7);
985    }
986
987    #[test]
988    fn identical_polygons_intersection_is_same() {
989        let a = sq(0.0, 0.0, 3.0);
990        let res = polygon_boolean(&a, &a, BooleanOp::Intersection, TOL);
991        assert_eq!(res.outer.len(), 1);
992        assert_area_close(res.area(), 9.0, 1e-7);
993    }
994
995    #[test]
996    fn identical_polygons_difference_is_empty() {
997        let a = sq(0.0, 0.0, 3.0);
998        let res = polygon_boolean(&a, &a, BooleanOp::Difference, TOL);
999        assert!(res.is_empty(), "A \\ A is empty");
1000    }
1001
1002    #[test]
1003    fn degenerate_input_too_few_points() {
1004        let a = vec![Point2::new(0.0, 0.0), Point2::new(1.0, 0.0)];
1005        let b = sq(0.0, 0.0, 1.0);
1006        let res = polygon_boolean(&a, &b, BooleanOp::Union, TOL);
1007        // A is empty → union is just B.
1008        assert_eq!(res.outer.len(), 1);
1009        assert_area_close(res.area(), 1.0, 1e-9);
1010    }
1011
1012    #[test]
1013    fn degenerate_zero_tolerance_rejected() {
1014        let a = sq(0.0, 0.0, 1.0);
1015        let b = sq(0.5, 0.5, 1.0);
1016        let res = polygon_boolean(&a, &b, BooleanOp::Union, 0.0);
1017        assert!(res.is_empty(), "non-positive tolerance returns empty");
1018    }
1019
1020    #[test]
1021    fn union_wrapper_returns_outer_only() {
1022        let a = sq(0.0, 0.0, 2.0);
1023        let b = sq(1.0, 1.0, 2.0);
1024        let loops = polygon_union(&a, &b, TOL);
1025        assert_eq!(loops.len(), 1);
1026        assert_area_close(signed_area(&loops[0]), 7.0, 1e-7);
1027    }
1028
1029    #[test]
1030    fn cw_input_is_normalized() {
1031        // A clockwise square should be accepted (orientation normalized).
1032        let a_cw = vec![
1033            Point2::new(0.0, 0.0),
1034            Point2::new(0.0, 2.0),
1035            Point2::new(2.0, 2.0),
1036            Point2::new(2.0, 0.0),
1037        ];
1038        let b = sq(1.0, 1.0, 2.0);
1039        let res = polygon_boolean(&a_cw, &b, BooleanOp::Union, TOL);
1040        assert_eq!(res.outer.len(), 1);
1041        assert_area_close(res.area(), 7.0, 1e-7);
1042    }
1043
1044    use proptest::prelude::*;
1045
1046    proptest! {
1047        #![proptest_config(ProptestConfig::with_cases(200))]
1048
1049        /// Union area never exceeds the sum of the parts (overlap is not
1050        /// double-counted) and is at least the larger of the two.
1051        #[test]
1052        fn prop_union_area_bounded(
1053            ax in -3.0f64..3.0, ay in -3.0f64..3.0, asz in 0.5f64..4.0,
1054            bx in -3.0f64..3.0, by in -3.0f64..3.0, bsz in 0.5f64..4.0,
1055        ) {
1056            let a = sq(ax, ay, asz);
1057            let b = sq(bx, by, bsz);
1058            let area_a = asz * asz;
1059            let area_b = bsz * bsz;
1060            let res = polygon_boolean(&a, &b, BooleanOp::Union, 1e-9);
1061            if !res.is_empty() {
1062                let u = res.area();
1063                prop_assert!(
1064                    u <= area_a + area_b + 1e-6,
1065                    "union {u} exceeds sum {}", area_a + area_b
1066                );
1067                prop_assert!(
1068                    u >= area_a.max(area_b) - 1e-6,
1069                    "union {u} smaller than larger part {}", area_a.max(area_b)
1070                );
1071            }
1072        }
1073
1074        /// Intersection area never exceeds either part.
1075        #[test]
1076        fn prop_intersection_area_bounded(
1077            ax in -3.0f64..3.0, ay in -3.0f64..3.0, asz in 0.5f64..4.0,
1078            bx in -3.0f64..3.0, by in -3.0f64..3.0, bsz in 0.5f64..4.0,
1079        ) {
1080            let a = sq(ax, ay, asz);
1081            let b = sq(bx, by, bsz);
1082            let area_a = asz * asz;
1083            let area_b = bsz * bsz;
1084            let res = polygon_boolean(&a, &b, BooleanOp::Intersection, 1e-9);
1085            let i = res.area();
1086            prop_assert!(
1087                i <= area_a.min(area_b) + 1e-6,
1088                "intersection {i} exceeds smaller part {}", area_a.min(area_b)
1089            );
1090        }
1091
1092        /// Inclusion–exclusion: |A∪B| + |A∩B| == |A| + |B| for axis-aligned
1093        /// squares (areas are exact regardless of overlap topology).
1094        #[test]
1095        fn prop_inclusion_exclusion(
1096            ax in -3.0f64..3.0, ay in -3.0f64..3.0, asz in 0.5f64..4.0,
1097            bx in -3.0f64..3.0, by in -3.0f64..3.0, bsz in 0.5f64..4.0,
1098        ) {
1099            let a = sq(ax, ay, asz);
1100            let b = sq(bx, by, bsz);
1101            let area_a = asz * asz;
1102            let area_b = bsz * bsz;
1103            let u = polygon_boolean(&a, &b, BooleanOp::Union, 1e-9);
1104            let i = polygon_boolean(&a, &b, BooleanOp::Intersection, 1e-9);
1105            if !u.is_empty() {
1106                let lhs = u.area() + i.area();
1107                prop_assert!(
1108                    (lhs - (area_a + area_b)).abs() <= 1e-4,
1109                    "inclusion-exclusion off: {lhs} vs {}", area_a + area_b
1110                );
1111            }
1112        }
1113
1114        /// Difference partition: |A\B| + |A∩B| == |A| for axis-aligned squares.
1115        #[test]
1116        fn prop_difference_partitions_a(
1117            ax in -3.0f64..3.0, ay in -3.0f64..3.0, asz in 0.5f64..4.0,
1118            bx in -3.0f64..3.0, by in -3.0f64..3.0, bsz in 0.5f64..4.0,
1119        ) {
1120            let a = sq(ax, ay, asz);
1121            let b = sq(bx, by, bsz);
1122            let area_a = asz * asz;
1123            let d = polygon_boolean(&a, &b, BooleanOp::Difference, 1e-9);
1124            let i = polygon_boolean(&a, &b, BooleanOp::Intersection, 1e-9);
1125            let lhs = d.area() + i.area();
1126            prop_assert!(
1127                (lhs - area_a).abs() <= 1e-4,
1128                "difference partition off: {lhs} vs {area_a}"
1129            );
1130        }
1131    }
1132
1133    #[test]
1134    fn diagonal_triangle_square_intersection() {
1135        // A triangle overlapping a square with genuinely diagonal edges, so the
1136        // arrangement must cut edges off the snapping grid (not just at integer
1137        // coordinates). Square [0,4]^2; triangle (2,-1)-(6,3)-(2,7) — a
1138        // rightward wedge whose left vertex sits inside the square.
1139        let square = sq(0.0, 0.0, 4.0);
1140        let tri = vec![
1141            Point2::new(2.0, -1.0),
1142            Point2::new(6.0, 3.0),
1143            Point2::new(2.0, 7.0),
1144        ];
1145        let inter = polygon_boolean(&square, &tri, BooleanOp::Intersection, TOL);
1146        assert!(!inter.is_empty(), "diagonal overlap must intersect");
1147        // Cross-check against the convex-clip result (both convex here).
1148        let clipped = crate::polygon2d::sutherland_hodgman_clip(&square, &tri);
1149        let expected = signed_area(&clipped).abs();
1150        assert!(expected > 0.0, "sanity: clip area positive");
1151        assert_area_close(inter.area(), expected, 1e-6);
1152    }
1153
1154    #[test]
1155    fn rotated_square_overlap_union_intersection() {
1156        // A 45-degree diamond overlapping an axis-aligned square: every
1157        // intersection lands at a non-integer coordinate. Verify inclusion-
1158        // exclusion holds, proving the off-grid arrangement is exact.
1159        let square = sq(0.0, 0.0, 4.0);
1160        let diamond = vec![
1161            Point2::new(2.0, -1.0),
1162            Point2::new(5.0, 2.0),
1163            Point2::new(2.0, 5.0),
1164            Point2::new(-1.0, 2.0),
1165        ];
1166        let area_sq = 16.0;
1167        let area_di = signed_area(&diamond).abs();
1168        let u = polygon_boolean(&square, &diamond, BooleanOp::Union, TOL);
1169        let i = polygon_boolean(&square, &diamond, BooleanOp::Intersection, TOL);
1170        assert!(!u.is_empty() && !i.is_empty());
1171        assert_area_close(u.area() + i.area(), area_sq + area_di, 1e-6);
1172    }
1173
1174    #[test]
1175    fn a_small_polygon_far_from_the_origin_keeps_its_area() {
1176        let far = 1e8;
1177        let triangle = [
1178            Point2::new(far, far),
1179            Point2::new(far + 1.0, far),
1180            Point2::new(far, far + 1.0),
1181        ];
1182        assert_area_close(signed_area(&triangle), 0.5, 1e-12);
1183        let mut clockwise = triangle;
1184        clockwise.reverse();
1185        assert_area_close(signed_area(&clockwise), -0.5, 1e-12);
1186    }
1187}