1use crate::madd::Madd;
42use crate::predicates::winding_number;
43use crate::vec::Point2;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum BooleanOp {
48 Union,
50 Intersection,
52 Difference,
54}
55
56#[derive(Debug, Clone, Default, PartialEq)]
68pub struct PolygonBooleanResult {
69 pub outer: Vec<Vec<Point2>>,
71 pub holes: Vec<Vec<Point2>>,
73}
74
75impl PolygonBooleanResult {
76 #[must_use]
78 pub fn is_empty(&self) -> bool {
79 self.outer.is_empty() && self.holes.is_empty()
80 }
81
82 #[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#[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#[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 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 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#[must_use]
185pub fn signed_area(polygon: &[Point2]) -> f64 {
186 let n = polygon.len();
187 if n < 3 {
188 return 0.0;
189 }
190 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
208fn 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
223fn 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#[derive(Clone, Copy)]
248struct Snapper {
249 inv: f64,
250 cell: f64,
251}
252
253impl Snapper {
254 fn new(tol: f64) -> Self {
255 let cell = tol.max(f64::MIN_POSITIVE);
258 Self {
259 inv: 1.0 / cell,
260 cell,
261 }
262 }
263
264 fn key(&self, p: Point2) -> (i64, i64) {
266 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 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
279struct Polygon {
285 verts: Vec<Point2>,
287}
288
289impl Polygon {
290 fn normalized(input: &[Point2], tol: f64) -> Option<Self> {
293 if input.len() < 3 {
294 return None;
295 }
296 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
342struct SubEdge {
348 start: Point2,
349 end: Point2,
350}
351
352fn 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 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 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 let mut prev = snapper.snap(a1);
378 let mut cuts: Vec<Point2> = Vec::with_capacity(params.len());
379 for &t in ¶ms {
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
396fn 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 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 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 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 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
447fn 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
459fn 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
486fn 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#[derive(Clone, Copy, PartialEq, Eq)]
510enum EdgeSource {
511 A,
512 B,
513}
514
515struct DirectedEdge {
517 start: Point2,
518 end: Point2,
519}
520
521enum MidClass {
523 Inside,
524 Outside,
525 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 (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 (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 (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
592fn 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 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 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 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
630fn trace_loops(edges: Vec<DirectedEdge>, snapper: &Snapper, tol: f64) -> Vec<Vec<Point2>> {
641 use std::collections::HashMap;
642
643 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 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 if current == start_idx {
702 break;
703 }
704 }
705
706 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
718fn 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
731fn 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
752fn 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 match op {
771 BooleanOp::Union | BooleanOp::Difference => single_outer(p),
772 BooleanOp::Intersection => PolygonBooleanResult::default(),
773 }
774 }
775 (None, Some(p)) => {
776 match op {
778 BooleanOp::Union => single_outer(p),
779 BooleanOp::Intersection | BooleanOp::Difference => PolygonBooleanResult::default(),
780 }
781 }
782 (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 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 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 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 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 let a = rect(0.0, 0.0, 10.0, 5.0);
912 let b = rect(0.0, 4.99, 10.0, 3.01); 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 assert_area_close(res.area(), 80.0, 0.2);
918 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 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 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 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 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 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 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 #[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 #[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 #[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 #[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 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 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 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}