section-properties 0.4.0

Structural cross-section properties: geometric/principal moments, section moduli, warping/torsion FEM, plastic, cold-formed, and fire analysis.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
use super::{Point, Polygon};
use crate::section::Section;

/// Axis selector for mirroring.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Axis {
    /// Reflect about the x-axis.
    X,
    /// Reflect about the y-axis.
    Y,
}

/// A rigid or affine transformation applied to a [`Geometry`]'s vertices.
///
/// Mirrors `sectionproperties.pre.geometry.Transform`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Transform {
    /// Translate by an offset (dx, dy).
    Translate { dx: f64, dy: f64 },
    /// Rotate counter-clockwise about the origin by `angle` radians.
    Rotate { angle: f64 },
    /// Uniform scale about the origin.
    Scale { factor: f64 },
    /// Reflect about the x-axis (y → -y).
    MirrorX,
    /// Reflect about the y-axis (x → -x).
    MirrorY,
}

impl Transform {
    /// Apply this transform to a point.
    pub fn apply(&self, p: Point) -> Point {
        match *self {
            Transform::Translate { dx, dy } => Point::new(p.x + dx, p.y + dy),
            Transform::Rotate { angle } => {
                let (s, c) = angle.sin_cos();
                Point::new(p.x * c - p.y * s, p.x * s + p.y * c)
            }
            Transform::Scale { factor } => Point::new(p.x * factor, p.y * factor),
            Transform::MirrorX => Point::new(p.x, -p.y),
            Transform::MirrorY => Point::new(-p.x, p.y),
        }
    }
}

/// A single connected region: an outer boundary plus optional holes,
/// optionally followed by a list of transforms.
///
/// Mirrors `sectionproperties.pre.geometry.Geometry`.
#[derive(Debug, Clone)]
pub struct Geometry {
    /// Outer boundary (normalised to CCW).
    pub outer: Polygon,
    /// Hole boundaries (each normalised to CW).
    pub holes: Vec<Polygon>,
    /// Geometric transforms applied in order (see [`Geometry`]).
    pub transforms: Vec<Transform>,
}

impl Geometry {
    /// Create a new geometry from an outer polygon and optional holes.
    ///
    /// The outer boundary is normalised to counter-clockwise orientation
    /// and each hole to clockwise orientation, matching the convention used
    /// by [`Section`](crate::section::Section).
    pub fn new(mut outer: Polygon, mut holes: Vec<Polygon>) -> Self {
        if outer.signed_area() < 0.0 {
            outer.vertices.reverse();
        }
        for hole in &mut holes {
            if hole.signed_area() > 0.0 {
                hole.vertices.reverse();
            }
        }
        Self {
            outer,
            holes,
            transforms: Vec::new(),
        }
    }

    /// Create a geometry from outer and hole point loops.
    ///
    /// Mirrors `Geometry.from_points(points, holes=...)`.
    pub fn from_points(points: Vec<Point>, holes: Vec<Vec<Point>>) -> Self {
        Self::new(
            Polygon::new(points),
            holes.into_iter().map(Polygon::new).collect(),
        )
    }

    /// Convert a single-boundary [`Section`](crate::section::Section) into a geometry.
    pub fn from_section(section: &crate::section::Section) -> Self {
        Self::new(section.outer.clone(), section.holes.clone())
    }

    /// Rotate counter-clockwise about the origin by `angle_degrees` degrees.
    ///
    /// Mirrors `Geometry.rotate(angle_degrees, rot_point)`.
    pub fn rotate(mut self, angle_degrees: f64) -> Self {
        self.transforms.push(Transform::Rotate {
            angle: angle_degrees.to_radians(),
        });
        self
    }

    /// Rotate about an explicit point.
    pub fn rotate_about(mut self, angle_degrees: f64, point: Point) -> Self {
        self.transforms.push(Transform::Translate {
            dx: -point.x,
            dy: -point.y,
        });
        self.transforms.push(Transform::Rotate {
            angle: angle_degrees.to_radians(),
        });
        self.transforms.push(Transform::Translate {
            dx: point.x,
            dy: point.y,
        });
        self
    }

    /// Reflect about the x or y axis.
    ///
    /// Mirrors `Geometry.mirror(axis, mirror_point)`; here reflection is always
    /// about the global axes.
    pub fn mirror(mut self, axis: Axis) -> Self {
        self.transforms.push(match axis {
            Axis::X => Transform::MirrorX,
            Axis::Y => Transform::MirrorY,
        });
        self
    }

    /// Translate by `(dx, dy)`.
    ///
    /// Mirrors `Geometry.shift(x_offset, y_offset)`.
    pub fn shift(mut self, dx: f64, dy: f64) -> Self {
        self.transforms.push(Transform::Translate { dx, dy });
        self
    }

    /// Return a copy translated so that the centroid sits at the origin.
    ///
    /// Mirrors `Geometry.align_center()`.
    pub fn align_center(&self) -> Self {
        let c = self.centroid();
        let mut g = self.clone();
        g.transforms
            .push(Transform::Translate { dx: -c.x, dy: -c.y });
        g
    }

    /// Translate this geometry so its bounding box aligns with `other`.
    ///
    /// For each axis independently the nearest bounding-box edge is moved onto
    /// the corresponding edge of `other`'s box, matching the behaviour of
    /// `Geometry.align_to(other, pt=(0, 0))`.
    pub fn align_to(&self, other: &Self) -> Self {
        let (l1, r1, b1, t1) = self.bounds();
        let (l2, r2, b2, t2) = other.bounds();

        let dx = if (l1 - l2).abs() < (r1 - r2).abs() {
            l2 - l1
        } else {
            r2 - r1
        };
        let dy = if (b1 - b2).abs() < (t1 - t2).abs() {
            b2 - b1
        } else {
            t2 - t1
        };

        if dx == 0.0 && dy == 0.0 {
            return self.clone();
        }
        let mut g = self.clone();
        g.transforms.push(Transform::Translate { dx, dy });
        g
    }

    /// Offset the geometry by `amount` using mitred corners.
    ///
    /// Positive amounts grow the geometry, negative amounts shrink it. The
    /// outer boundary is offset by `+amount` and each hole by `-amount`.
    /// Returns `None` if any boundary degenerates.
    ///
    /// Mirrors `Geometry.offset(amount)`.
    pub fn offset(&self, amount: f64) -> Option<Self> {
        let outer = self.apply_transforms().outer.offset(amount)?;
        let mut holes = Vec::with_capacity(self.holes.len());
        for h in &self.holes {
            holes.push(h.offset(-amount)?);
        }
        Some(Self {
            outer,
            holes,
            transforms: Vec::new(),
        })
    }

    /// Split the geometry into two halves either side of the line through
    /// points `a` and `b`.
    ///
    /// Mirrors `Geometry.split_section(point_a, point_b)`. Returns
    /// `(below, above)`; each side is `None` when empty.
    pub fn split_section(&self, a: Point, b: Point) -> (Option<Geometry>, Option<Geometry>) {
        let g = self.apply_transforms();
        let (below_outer, above_outer) = g.outer.split_by_line(a, b);

        // Clip each hole and attach the matching half to its side.
        let mut below_holes = Vec::new();
        let mut above_holes = Vec::new();
        for h in &g.holes {
            let (hb, ha) = h.split_by_line(a, b);
            if let Some(hb) = hb {
                below_holes.push(hb);
            }
            if let Some(ha) = ha {
                above_holes.push(ha);
            }
        }

        let below = below_outer.map(|o| Geometry {
            outer: o,
            holes: below_holes,
            transforms: Vec::new(),
        });
        let above = above_outer.map(|o| Geometry {
            outer: o,
            holes: above_holes,
            transforms: Vec::new(),
        });
        (below, above)
    }
    /// Boolean union with `other`.
    ///
    /// Mirrors `Geometry | other` (shapely `union`). Returns a
    /// `CompoundGeometry` that can represent multiple disconnected regions.
    pub fn union(&self, other: &Self) -> Result<CompoundGeometry, super::boolean::BooleanError> {
        self.boolean_op(other, super::boolean::BoolOp::Union)
    }

    /// Boolean intersection with `other`.
    ///
    /// Mirrors `Geometry & other` (shapely `intersection`). Returns a
    /// `CompoundGeometry` that can represent multiple disconnected regions.
    pub fn intersection(
        &self,
        other: &Self,
    ) -> Result<CompoundGeometry, super::boolean::BooleanError> {
        self.boolean_op(other, super::boolean::BoolOp::Intersection)
    }

    /// Boolean difference: this geometry minus `other`.
    ///
    /// Mirrors `Geometry - other` (shapely `difference`). Returns a
    /// `CompoundGeometry` that can represent multiple disconnected regions.
    pub fn subtract(&self, other: &Self) -> Result<CompoundGeometry, super::boolean::BooleanError> {
        self.boolean_op(other, super::boolean::BoolOp::Difference)
    }

    fn boolean_op(
        &self,
        other: &Self,
        op: super::boolean::BoolOp,
    ) -> Result<CompoundGeometry, super::boolean::BooleanError> {
        let a_trans = self.apply_transforms();
        let b_trans = other.apply_transforms();
        let a = Section::new(a_trans.outer, a_trans.holes);
        let b = Section::new(b_trans.outer, b_trans.holes);

        let results = match op {
            super::boolean::BoolOp::Union => super::boolean::section_union(&a, &b)?,
            super::boolean::BoolOp::Intersection => super::boolean::section_intersection(&a, &b)?,
            super::boolean::BoolOp::Difference => super::boolean::section_difference(&a, &b)?,
        };

        let geometries = results
            .into_iter()
            .map(|sec| Geometry::new(sec.outer, sec.holes))
            .collect();
        Ok(CompoundGeometry::new(geometries))
    }

    /// Return a copy of this geometry with the transforms applied to all vertices.
    ///
    /// Transforms are applied in the order they appear in [`Geometry::transforms`].
    pub fn apply_transforms(&self) -> Self {
        if self.transforms.is_empty() {
            return self.clone();
        }
        let map = |poly: &Polygon| -> Polygon {
            Polygon::new(
                poly.vertices
                    .iter()
                    .map(|&v| self.transforms.iter().fold(v, |p, t| t.apply(p)))
                    .collect(),
            )
        };
        Self {
            outer: map(&self.outer),
            holes: self.holes.iter().map(map).collect(),
            transforms: Vec::new(),
        }
    }

    /// Net area of the geometry (outer minus holes), after applying transforms.
    pub fn area(&self) -> f64 {
        let g = if self.transforms.is_empty() {
            self
        } else {
            &self.apply_transforms()
        };
        let mut a = g.outer.area();
        for h in &g.holes {
            a -= h.area();
        }
        a
    }

    /// Centroid of the geometry using the composite area formula.
    pub fn centroid(&self) -> Point {
        let g = if self.transforms.is_empty() {
            self
        } else {
            &self.apply_transforms()
        };
        let mut sum_x = 0.0;
        let mut sum_y = 0.0;
        let mut total = 0.0;

        let outer_c = g.outer.centroid();
        let outer_a = g.outer.area();
        sum_x += outer_c.x * outer_a;
        sum_y += outer_c.y * outer_a;
        total += outer_a;

        for h in &g.holes {
            let a = h.area();
            let c = h.centroid();
            sum_x -= c.x * a;
            sum_y -= c.y * a;
            total -= a;
        }

        Point::new(sum_x / total, sum_y / total)
    }

    /// Bounding box of the geometry: (min_x, max_x, min_y, max_y).
    pub fn bounds(&self) -> (f64, f64, f64, f64) {
        let g = if self.transforms.is_empty() {
            self
        } else {
            &self.apply_transforms()
        };
        let mut min_x = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_y = f64::NEG_INFINITY;
        for poly in std::iter::once(&g.outer).chain(g.holes.iter()) {
            for v in &poly.vertices {
                min_x = min_x.min(v.x);
                max_x = max_x.max(v.x);
                min_y = min_y.min(v.y);
                max_y = max_y.max(v.y);
            }
        }
        (min_x, max_x, min_y, max_y)
    }

    /// Perimeter of the geometry (outer + holes), after applying transforms.
    pub fn perimeter(&self) -> f64 {
        let g = if self.transforms.is_empty() {
            self
        } else {
            &self.apply_transforms()
        };
        g.outer.perimeter() + g.holes.iter().map(|h| h.perimeter()).sum::<f64>()
    }
}

/// A collection of independent regions, e.g. two parallel rectangles,
/// an angle bolted to a plate, or a built-up girder.
///
/// Mirrors `sectionproperties.pre.geometry.CompoundGeometry`.
///
/// # Invariant
/// Regions are assumed to be **material-disjoint**: no part of one region's
/// material may overlap another region's material. Properties (`area`,
/// inertia, ...) are computed by simple summation, which is only correct
/// under this assumption.
///
/// Use [`CompoundGeometry::validate`] to check the invariant, and
/// [`CompoundGeometry::dissolved_outer_only`] to merge overlapping inputs into a valid
/// compound.
#[derive(Debug, Clone)]
pub struct CompoundGeometry {
    /// The individual regions that make up the compound section.
    pub geometries: Vec<Geometry>,
}

/// Errors from compound-geometry topology validation.
#[derive(Debug, Clone, PartialEq)]
pub enum CompoundError {
    /// Material of region `a` overlaps material of region `b`.
    OverlappingRegions { a: usize, b: usize },
    /// Hole `hole` of `region` is not fully inside the region's outer
    /// boundary.
    HoleNotInsideOuter { region: usize, hole: usize },
    /// Hole `b` of `region` is nested inside hole `a` (a hole-within-a-hole).
    /// A single region cannot represent an island of material inside a void,
    /// so nested holes are rejected.
    NestedHoles { region: usize, a: usize, b: usize },
}

impl std::fmt::Display for CompoundError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CompoundError::OverlappingRegions { a, b } => {
                write!(f, "regions {a} and {b} have overlapping material")
            }
            CompoundError::HoleNotInsideOuter { region, hole } => {
                write!(
                    f,
                    "hole {hole} of region {region} is not fully inside its outer boundary"
                )
            }
            CompoundError::NestedHoles { region, a, b } => {
                write!(
                    f,
                    "region {region} has hole {b} nested inside hole {a} (holes cannot nest)"
                )
            }
        }
    }
}

impl std::error::Error for CompoundError {}

/// Bounding-box relation between two polygons for quick rejection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BBoxRelation {
    /// No overlap, not even touching
    Disjoint,
    /// Touching at boundary but no area overlap
    Touch,
    /// Positive area overlap
    Overlap,
}

/// Quick outer-boundary bounding-box relation test for two polygons.
/// Returns Disjoint if separated, Touch if only boundaries touch, Overlap if interiors overlap.
/// Note: This checks OUTER boundaries only, not material (outer minus holes).
fn outer_bbox_relation(a: &Polygon, b: &Polygon) -> BBoxRelation {
    let bbox = |pts: &[Point]| {
        pts.iter().fold(
            (
                f64::INFINITY,
                f64::NEG_INFINITY,
                f64::INFINITY,
                f64::NEG_INFINITY,
            ),
            |(l, r, b, t), p| (l.min(p.x), r.max(p.x), b.min(p.y), t.max(p.y)),
        )
    };
    let (al, ar, ab, at) = bbox(&a.vertices);
    let (bl, br, bb, bt) = bbox(&b.vertices);

    // Check for disjoint (no overlap, not even touching)
    if ar < bl || br < al || at < bb || bt < ab {
        return BBoxRelation::Disjoint;
    }

    // Check for touch (boundaries touch but interiors don't overlap)
    // This means at least one dimension has equality at the boundary
    let x_touch = ar == bl || br == al;
    let y_touch = at == bb || bt == ab;
    if x_touch || y_touch {
        return BBoxRelation::Touch;
    }

    // Otherwise there is positive area overlap
    BBoxRelation::Overlap
}

impl CompoundGeometry {
    /// Create a compound geometry from its constituent regions.
    ///
    /// # Invariant
    /// The caller guarantees that region materials are **disjoint**.
    /// Overlapping inputs silently double-count area/inertia in property
    /// computations. Use [`CompoundGeometry::validate`] to check, or
    /// [`CompoundGeometry::dissolved_outer_only`] to merge overlapping inputs.
    pub fn new(geometries: Vec<Geometry>) -> Self {
        Self { geometries }
    }

    /// Validating constructor: returns an error if any two regions have
    /// overlapping material or a hole escapes its outer boundary.
    pub fn new_validated(geometries: Vec<Geometry>) -> Result<Self, CompoundError> {
        let compound = Self { geometries };
        compound.validate()?;
        Ok(compound)
    }

    /// Merge overlapping inputs into a valid (material-disjoint) compound by
    /// dissolving overlaps with the boolean union. **Holes are dropped during
    /// dissolution** (the merged outline is exact; re-derive holes afterwards
    /// if required). This is a union of outer boundaries only.
    ///
    /// Prefer [`Self::dissolved_outer_only`] for explicit naming.
    #[deprecated(
        since = "0.1.0",
        note = "Use dissolved_outer_only() for explicit naming; holes are dropped"
    )]
    pub fn dissolved(geometries: Vec<Geometry>) -> Self {
        Self::dissolved_outer_only(geometries)
    }

    /// Merge overlapping inputs into a valid (material-disjoint) compound by
    /// dissolving overlaps with the boolean union. **Holes are dropped** –
    /// only outer boundaries are united. This is a union of outer boundaries
    /// only; holes must be re-derived afterwards if required.
    pub fn dissolved_outer_only(geometries: Vec<Geometry>) -> Self {
        use super::boolean::{BoolOp, polygon_boolean};

        let mut acc: Vec<Polygon> = geometries
            .iter()
            .map(|g| g.apply_transforms().outer)
            .collect();

        loop {
            let mut merged: Option<(usize, usize, Vec<Polygon>)> = None;
            'outer: for i in 0..acc.len() {
                for j in (i + 1)..acc.len() {
                    if matches!(
                        outer_bbox_relation(&acc[i], &acc[j]),
                        BBoxRelation::Disjoint
                    ) {
                        continue;
                    }
                    let u = polygon_boolean(&acc[i], &acc[j], BoolOp::Union);
                    let u_area: f64 = u.iter().map(|p| p.area().abs()).sum();
                    let sum_area = acc[i].area().abs() + acc[j].area().abs();
                    if u_area < sum_area - 1e-9 {
                        merged = Some((i, j, u));
                        break 'outer;
                    }
                }
            }
            match merged {
                Some((i, j, u)) => {
                    let last = acc.len() - 1;
                    acc[j] = acc[last].clone();
                    acc.swap_remove(last);
                    acc.splice(i..i + 1, u);
                }
                None => break,
            }
        }

        let geometries = acc
            .into_iter()
            .map(|p| Geometry {
                outer: p,
                holes: Vec::new(),
                transforms: Vec::new(),
            })
            .collect();
        Self { geometries }
    }

    /// Check the material-disjoint invariant.
    ///
    /// * every hole must lie fully inside its own outer boundary,
    /// * no two regions may claim the same material point (verified with
    ///   deterministic edge–edge and containment checks).
    pub fn validate(&self) -> Result<(), CompoundError> {
        // Hole containment within its own outer boundary.
        for (ri, g) in self.geometries.iter().enumerate() {
            let g = g.apply_transforms();
            for (hi, hole) in g.holes.iter().enumerate() {
                // 1. All hole vertices must be inside outer.
                let vertices_inside = hole.vertices.iter().all(|v| g.outer.contains_point(*v));
                if !vertices_inside {
                    return Err(CompoundError::HoleNotInsideOuter {
                        region: ri,
                        hole: hi,
                    });
                }
                // 2. No hole edge may cross outer boundary edge.
                for i in 0..hole.vertices.len() {
                    let h1 = hole.vertices[i];
                    let h2 = hole.vertices[(i + 1) % hole.vertices.len()];
                    for j in 0..g.outer.vertices.len() {
                        let o1 = g.outer.vertices[j];
                        let o2 = g.outer.vertices[(j + 1) % g.outer.vertices.len()];
                        if segments_interact(h1, h2, o1, o2) {
                            return Err(CompoundError::HoleNotInsideOuter {
                                region: ri,
                                hole: hi,
                            });
                        }
                    }
                }
            }

            // 3. No hole may be nested inside another hole of the same region.
            // A hole-within-a-hole is an island of material inside a void, which
            // a single region (one outer + holes) cannot represent.
            for a in 0..g.holes.len() {
                for b in (a + 1)..g.holes.len() {
                    let ha = &g.holes[a];
                    let hb = &g.holes[b];
                    let a_contains_b = hb.vertices.iter().all(|v| ha.contains_point(*v));
                    let b_contains_a = ha.vertices.iter().all(|v| hb.contains_point(*v));
                    if a_contains_b || b_contains_a {
                        return Err(CompoundError::NestedHoles { region: ri, a, b });
                    }
                }
            }
        }

        // Cross-region material overlap via deterministic checks.
        //
        // For each pair of regions, we verify the "material-disjoint"
        // invariant by checking:
        //  1. Edge–edge intersections between outer boundaries.
        //  2. Vertex containment: any vertex of region A inside region B's
        //     material (outer minus holes) or vice versa.
        //  3. Full containment: one outer fully inside the other, with the
        //     intersection not fully absorbed by holes.
        let n = self.geometries.len();
        if n < 2 {
            return Ok(());
        }

        let applied: Vec<Geometry> = self
            .geometries
            .iter()
            .map(|g| g.apply_transforms())
            .collect();

        for i in 0..n {
            for j in (i + 1)..n {
                let gi = &applied[i];
                let gj = &applied[j];
                if regions_overlap_deterministic(gi, gj) {
                    return Err(CompoundError::OverlappingRegions { a: i, b: j });
                }
            }
        }
        Ok(())
    }

    /// Build a compound geometry from a slice of [`Section`](crate::section::Section).
    pub fn from_sections(sections: &[crate::section::Section]) -> Self {
        Self {
            geometries: sections.iter().map(Geometry::from_section).collect(),
        }
    }

    /// Boolean operation across compound geometries.
    ///
    /// Mirrors `CompoundGeometry.combine(other, operation)`:
    /// - Union: all regions of both compounds unioned pairwise into one
    ///   accumulated set (dissolves internal overlaps).
    /// - Intersection: every region pair intersected, keeping non-empty
    ///   results.
    /// - Difference: each region of `self` reduced by every region of
    ///   `other` in sequence.
    pub fn boolean(
        &self,
        other: &Self,
        op: super::boolean::BoolOp,
    ) -> Result<Self, super::boolean::BooleanError> {
        match op {
            super::boolean::BoolOp::Intersection => {
                // Intersection: pairwise intersection of all region pairs
                // Use Geometry::boolean_op which properly uses section_intersection
                // and preserves holes
                let mut out = Vec::new();
                for ga in &self.geometries {
                    for gb in &other.geometries {
                        let inter = ga.boolean_op(gb, op)?;
                        out.extend(inter.geometries);
                    }
                }
                Ok(Self { geometries: out })
            }
            super::boolean::BoolOp::Difference => {
                // Start with all self regions
                let mut current: Vec<Geometry> = self.geometries.clone();

                // Subtract each other region from all current regions
                for gb in &other.geometries {
                    let mut next = Vec::new();
                    for ga in &current {
                        let diff = ga.boolean_op(gb, op)?;
                        next.extend(diff.geometries);
                    }
                    current = next;
                    if current.is_empty() {
                        break;
                    }
                }
                let geometries = current
                    .into_iter()
                    .map(|g| Geometry {
                        outer: g.outer,
                        holes: g.holes,
                        transforms: Vec::new(),
                    })
                    .collect();
                Ok(Self { geometries })
            }
            super::boolean::BoolOp::Union => {
                // Collect every region from both compounds
                let mut acc: Vec<Geometry> = self
                    .geometries
                    .iter()
                    .chain(other.geometries.iter())
                    .cloned()
                    .collect();

                // Merge overlapping regions iteratively
                loop {
                    let mut merged: Option<(usize, usize, Vec<Geometry>)> = None;
                    'outer: for i in 0..acc.len() {
                        for j in (i + 1)..acc.len() {
                            if matches!(
                                outer_bbox_relation(&acc[i].outer, &acc[j].outer),
                                BBoxRelation::Disjoint
                            ) {
                                continue;
                            }
                            let union_result =
                                acc[i].boolean_op(&acc[j], super::boolean::BoolOp::Union)?;
                            // Only merge if the union actually produced a SINGLE region.
                            // If it returns 2+ regions, the inputs were material-disjoint
                            // (e.g. same outer bbox but holes isolate materials) and
                            // merging would not reduce the set — it would cause an infinite loop.
                            if union_result.geometries.len() == 1 {
                                merged = Some((i, j, union_result.geometries));
                                break 'outer;
                            }
                        }
                    }
                    match merged {
                        Some((i, j, new_geometries)) => {
                            let last = acc.len() - 1;
                            acc[j] = acc[last].clone();
                            acc.swap_remove(last);
                            acc.splice(i..i + 1, new_geometries);
                        }
                        None => break,
                    }
                }

                let geometries = acc;
                Ok(Self { geometries })
            }
        }
    }

    /// Boolean union with `other`.
    pub fn union(&self, other: &Self) -> Result<Self, super::boolean::BooleanError> {
        self.boolean(other, super::boolean::BoolOp::Union)
    }

    /// Boolean intersection with `other`.
    pub fn intersection(&self, other: &Self) -> Result<Self, super::boolean::BooleanError> {
        self.boolean(other, super::boolean::BoolOp::Intersection)
    }

    /// Boolean difference: this compound minus `other`.
    pub fn subtract(&self, other: &Self) -> Result<Self, super::boolean::BooleanError> {
        self.boolean(other, super::boolean::BoolOp::Difference)
    }
    /// Total net area across all regions.
    pub fn area(&self) -> f64 {
        self.geometries.iter().map(|g| g.area()).sum()
    }

    /// Centroid of the compound section via the composite area formula.
    pub fn centroid(&self) -> Point {
        let mut sum_x = 0.0;
        let mut sum_y = 0.0;
        let mut total = 0.0;
        for g in &self.geometries {
            let a = g.area();
            let c = g.centroid();
            sum_x += c.x * a;
            sum_y += c.y * a;
            total += a;
        }
        assert!(
            total.abs() > f64::EPSILON,
            "CompoundGeometry has zero total area"
        );
        Point::new(sum_x / total, sum_y / total)
    }

    /// Bounding box of the compound geometry: (min_x, max_x, min_y, max_y).
    pub fn bounds(&self) -> (f64, f64, f64, f64) {
        let mut min_x = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_y = f64::NEG_INFINITY;
        for g in &self.geometries {
            let (l, r, b, t) = g.bounds();
            min_x = min_x.min(l);
            max_x = max_x.max(r);
            min_y = min_y.min(b);
            max_y = max_y.max(t);
        }
        (min_x, max_x, min_y, max_y)
    }

    /// Total perimeter across all regions (outer + holes).
    pub fn perimeter(&self) -> f64 {
        self.geometries.iter().map(|g| g.perimeter()).sum()
    }

    /// Return all polygons (outer first, then holes) across every region,
    /// with any transforms already applied.
    pub fn polygons(&self) -> Vec<Polygon> {
        let mut out = Vec::new();
        for g in &self.geometries {
            let g = g.apply_transforms();
            out.push(g.outer);
            out.extend(g.holes);
        }
        out
    }
}

/// Convert a [`Section`](crate::section::Section) into a single-geometry compound.
impl From<crate::section::Section> for CompoundGeometry {
    fn from(section: crate::section::Section) -> Self {
        Self::new(vec![Geometry::new(section.outer, section.holes)])
    }
}

/// Deterministic check whether two regions share any material area.
///
/// A region's material is its outer boundary minus its holes.
/// Two regions overlap if and only if there exists a point that lies in
/// both materials.  This is checked by:
///
/// 1. **Edge–edge intersection** – if any outer-boundary edge of `a`
///    crosses any outer-boundary edge of `b`, the interiors overlap.
/// 2. **Vertex containment** – if a vertex of one outer lies inside the
///    other region's material (outer minus holes), there is overlap.
/// 3. **Full containment** – if all vertices of one outer lie inside the
///    other outer, the intersection polygon is non-empty *and* not
///    entirely absorbed by the union of all holes.
fn intersection_point(a1: Point, a2: Point, b1: Point, b2: Point) -> Point {
    // Line segment intersection using parametric form.
    // a1 + t*(a2-a1) = b1 + u*(b2-b1)
    let dx1 = a2.x - a1.x;
    let dy1 = a2.y - a1.y;
    let dx2 = b2.x - b1.x;
    let dy2 = b2.y - b1.y;

    let det = dx1 * dy2 - dy1 * dx2;
    if det.abs() < 1e-12 {
        // Parallel or collinear - compute midpoint of overlapping interval.
        // Project all endpoints onto the line (a1->a2) and find overlap.
        // Use parameter t along segment a1-a2.
        let len2 = dx1 * dx1 + dy1 * dy1;
        if len2 < 1e-24 {
            // Degenerate segment - return a1
            return a1;
        }
        // Project b1 and b2 onto a1-a2 line
        let t_b1 = ((b1.x - a1.x) * dx1 + (b1.y - a1.y) * dy1) / len2;
        let t_b2 = ((b2.x - a1.x) * dx1 + (b2.y - a1.y) * dy1) / len2;
        // Segment a is [0, 1], segment b is [t_b1, t_b2] (may be reversed)
        let b_lo = t_b1.min(t_b2);
        let b_hi = t_b1.max(t_b2);
        // Overlap interval
        let lo = 0.0f64.max(b_lo);
        let hi = 1.0f64.min(b_hi);
        if lo <= hi {
            // Overlap exists - return midpoint of overlap
            let t_mid = (lo + hi) * 0.5;
            return Point::new(a1.x + t_mid * dx1, a1.y + t_mid * dy1);
        }
        // No overlap - return midpoint of a (shouldn't happen if segments_interact returned true)
        return Point::new((a1.x + a2.x) * 0.5, (a1.y + a2.y) * 0.5);
    }

    let t = ((b1.x - a1.x) * dy2 - (b1.y - a1.y) * dx2) / det;
    // Clamp to segment
    let t = t.clamp(0.0, 1.0);
    Point::new(a1.x + t * dx1, a1.y + t * dy1)
}

fn regions_overlap_deterministic(a: &Geometry, b: &Geometry) -> bool {
    let a_outer = &a.outer;
    let b_outer = &b.outer;

    // 1. Edge–edge intersection between the two outer boundaries.
    //    Only counts if the intersection point is in the MATERIAL
    //    of both regions (not inside any hole).
    for i in 0..a_outer.vertices.len() {
        let a1 = a_outer.vertices[i];
        let a2 = a_outer.vertices[(i + 1) % a_outer.vertices.len()];
        for j in 0..b_outer.vertices.len() {
            let b1 = b_outer.vertices[j];
            let b2 = b_outer.vertices[(j + 1) % b_outer.vertices.len()];
            if segments_overlap(a1, a2, b1, b2) {
                // Compute a representative point on the overlap.
                // Use the midpoint of the overlapping segment or the
                // intersection point itself.
                let pt = intersection_point(a1, a2, b1, b2);
                // Check if this point is in material of BOTH regions
                let in_a_material =
                    a_outer.contains_point(pt) && !a.holes.iter().any(|h| h.contains_point(pt));
                let in_b_material =
                    b_outer.contains_point(pt) && !b.holes.iter().any(|h| h.contains_point(pt));
                if in_a_material && in_b_material {
                    return true;
                }
            }
        }
    }

    // 2. Vertex containment: any vertex of `a` inside `b`'s material?
    for v in &a_outer.vertices {
        if b_outer.contains_point(*v) && !b.holes.iter().any(|h| h.contains_point(*v)) {
            return true;
        }
    }
    // Any vertex of `b` inside `a`'s material?
    for v in &b_outer.vertices {
        if a_outer.contains_point(*v) && !a.holes.iter().any(|h| h.contains_point(*v)) {
            return true;
        }
    }

    // 3. Full containment: one outer fully contains the other, but no
    //    vertex lies on the wrong side.  In this case the two outers
    //    overlap as regions, but we must verify the overlap is not
    //    entirely absorbed by holes.
    let a_in_b = a_outer.vertices.iter().all(|v| b_outer.contains_point(*v));
    let b_in_a = b_outer.vertices.iter().all(|v| a_outer.contains_point(*v));

    if a_in_b || b_in_a {
        // Compute the boolean intersection of the two outer polygons.
        let inter =
            super::boolean::polygon_boolean(a_outer, b_outer, super::boolean::BoolOp::Intersection);
        if inter.is_empty() {
            return false;
        }
        // Subtract every hole from both regions.  If anything survives, the
        // regions overlap in material.
        let mut remaining = inter;
        for hole in a.holes.iter().chain(b.holes.iter()) {
            let mut next = Vec::new();
            for p in &remaining {
                let diff =
                    super::boolean::polygon_boolean(p, hole, super::boolean::BoolOp::Difference);
                next.extend(diff);
            }
            remaining = next;
            if remaining.is_empty() {
                break;
            }
        }
        return !remaining.is_empty();
    }

    false
}

/// Segment-segment relation for robust topology checks.
#[derive(Debug, Clone, Copy, PartialEq)]
enum SegmentRelation {
    /// No intersection (disjoint, no shared points)
    Disjoint,
    /// Touching at a single endpoint (shared vertex)
    Touch,
    /// Proper interior intersection (crossing)
    ProperCross,
    /// Collinear and overlapping with positive-length intersection
    CollinearOverlap,
}

/// Determine the topological relation between two segments A1→A2 and B1→B2.
/// Uses orientation tests with epsilon for numerical robustness.
fn segment_relation(a1: Point, a2: Point, b1: Point, b2: Point) -> SegmentRelation {
    const EPS: f64 = 1e-12;

    fn orient(p: Point, q: Point, r: Point) -> f64 {
        (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x)
    }

    fn on_segment(p: Point, q: Point, r: Point) -> bool {
        // q lies on segment pr (assuming collinear)
        q.x >= p.x.min(r.x) - EPS
            && q.x <= p.x.max(r.x) + EPS
            && q.y >= p.y.min(r.y) - EPS
            && q.y <= p.y.max(r.y) + EPS
    }

    fn points_equal(p: Point, q: Point) -> bool {
        (p.x - q.x).abs() <= EPS && (p.y - q.y).abs() <= EPS
    }

    let o1 = orient(a1, a2, b1);
    let o2 = orient(a1, a2, b2);
    let o3 = orient(b1, b2, a1);
    let o4 = orient(b1, b2, a2);

    // General case: proper crossing (endpoints straddle each other's line)
    let o1_pos = o1 > EPS;
    let o1_neg = o1 < -EPS;
    let o2_pos = o2 > EPS;
    let o2_neg = o2 < -EPS;
    let o3_pos = o3 > EPS;
    let o3_neg = o3 < -EPS;
    let o4_pos = o4 > EPS;
    let o4_neg = o4 < -EPS;

    if (o1_pos != o2_pos || o1_neg != o2_neg) && (o3_pos != o4_pos || o3_neg != o4_neg) {
        return SegmentRelation::ProperCross;
    }

    // Special cases: check for collinear overlap
    // All orientations are near zero -> segments are collinear
    if o1.abs() <= EPS && o2.abs() <= EPS && o3.abs() <= EPS && o4.abs() <= EPS {
        // Check if projections on x or y overlap
        let a_min_x = a1.x.min(a2.x);
        let a_max_x = a1.x.max(a2.x);
        let b_min_x = b1.x.min(b2.x);
        let b_max_x = b1.x.max(b2.x);
        let a_min_y = a1.y.min(a2.y);
        let a_max_y = a1.y.max(a2.y);
        let b_min_y = b1.y.min(b2.y);
        let b_max_y = b1.y.max(b2.y);

        let overlap_x = a_max_x >= b_min_x - EPS && b_max_x >= a_min_x - EPS;
        let overlap_y = a_max_y >= b_min_y - EPS && b_max_y >= a_min_y - EPS;

        if overlap_x && overlap_y {
            // They overlap - now distinguish between Touch (point contact)
            // and CollinearOverlap (positive-length overlap)
            // For collinear segments, overlap length is the intersection of intervals
            // on the line. We can compute the overlap length parameter.
            // If the overlap is just a single point, it's Touch.
            let len_a2 = (a2.x - a1.x).powi(2) + (a2.y - a1.y).powi(2);
            let _len_b2 = (b2.x - b1.x).powi(2) + (b2.y - b1.y).powi(2);

            // Project b1, b2 onto segment a's line (parameter t in [0,1])
            let t_b1 = if len_a2 > EPS {
                ((b1.x - a1.x) * (a2.x - a1.x) + (b1.y - a1.y) * (a2.y - a1.y)) / len_a2
            } else {
                0.0
            };
            let t_b2 = if len_a2 > EPS {
                ((b2.x - a1.x) * (a2.x - a1.x) + (b2.y - a1.y) * (a2.y - a1.y)) / len_a2
            } else {
                0.0
            };

            let b_lo = t_b1.min(t_b2);
            let b_hi = t_b1.max(t_b2);

            // Overlap interval on segment a's parameter space
            let lo = 0.0f64.max(b_lo);
            let hi = 1.0f64.min(b_hi);

            if lo <= hi {
                let overlap_len = (hi - lo) * len_a2.sqrt();
                if overlap_len > EPS {
                    return SegmentRelation::CollinearOverlap;
                } else {
                    // Overlap is just a point
                    return SegmentRelation::Touch;
                }
            }
        }
        return SegmentRelation::Disjoint;
    }

    // Check for endpoint touching (shared vertex) - this is Touch, not Disjoint
    // b1 on a
    if o1.abs() <= EPS && on_segment(a1, b1, a2) {
        return if points_equal(b1, a1) || points_equal(b1, a2) {
            SegmentRelation::Touch
        } else {
            SegmentRelation::Disjoint
        };
    }
    // b2 on a
    if o2.abs() <= EPS && on_segment(a1, b2, a2) {
        return if points_equal(b2, a1) || points_equal(b2, a2) {
            SegmentRelation::Touch
        } else {
            SegmentRelation::Disjoint
        };
    }
    // a1 on b
    if o3.abs() <= EPS && on_segment(b1, a1, b2) {
        return if points_equal(a1, b1) || points_equal(a1, b2) {
            SegmentRelation::Touch
        } else {
            SegmentRelation::Disjoint
        };
    }
    // a2 on b
    if o4.abs() <= EPS && on_segment(b1, a2, b2) {
        return if points_equal(a2, b1) || points_equal(a2, b2) {
            SegmentRelation::Touch
        } else {
            SegmentRelation::Disjoint
        };
    }

    SegmentRelation::Disjoint
}

/// Check if two segments have any topological interaction (crossing, touching, or collinear overlap).
/// Returns true for ProperCross, CollinearOverlap, and Touch.
pub fn segments_interact(a1: Point, a2: Point, b1: Point, b2: Point) -> bool {
    !matches!(segment_relation(a1, a2, b1, b2), SegmentRelation::Disjoint)
}

/// Check if two segments have positive-length overlap or proper crossing (area overlap).
/// Returns true for ProperCross and CollinearOverlap only.
/// Returns false for Touch (endpoint contact) and Disjoint.
pub fn segments_overlap(a1: Point, a2: Point, b1: Point, b2: Point) -> bool {
    matches!(
        segment_relation(a1, a2, b1, b2),
        SegmentRelation::ProperCross | SegmentRelation::CollinearOverlap
    )
}

#[cfg(test)]
mod tests {
    use super::{Point, SegmentRelation, segment_relation, segments_interact, segments_overlap};

    #[test]
    fn segment_relation_proper_cross() {
        // Crossing segments
        let a1 = Point::new(0.0, 0.0);
        let a2 = Point::new(10.0, 10.0);
        let b1 = Point::new(0.0, 10.0);
        let b2 = Point::new(10.0, 0.0);
        assert_eq!(
            segment_relation(a1, a2, b1, b2),
            SegmentRelation::ProperCross
        );
        assert!(segments_overlap(a1, a2, b1, b2));
        assert!(segments_interact(a1, a2, b1, b2));
    }

    #[test]
    fn segment_relation_touch_endpoint() {
        // Segments touching at endpoint
        let a1 = Point::new(0.0, 0.0);
        let a2 = Point::new(5.0, 0.0);
        let b1 = Point::new(5.0, 0.0);
        let b2 = Point::new(10.0, 0.0);
        assert_eq!(segment_relation(a1, a2, b1, b2), SegmentRelation::Touch);
        assert!(!segments_overlap(a1, a2, b1, b2));
        assert!(segments_interact(a1, a2, b1, b2));
    }

    #[test]
    fn segment_relation_collinear_overlap() {
        // Collinear overlapping segments
        let a1 = Point::new(0.0, 0.0);
        let a2 = Point::new(10.0, 0.0);
        let b1 = Point::new(5.0, 0.0);
        let b2 = Point::new(15.0, 0.0);
        assert_eq!(
            segment_relation(a1, a2, b1, b2),
            SegmentRelation::CollinearOverlap
        );
        assert!(segments_overlap(a1, a2, b1, b2));
        assert!(segments_interact(a1, a2, b1, b2));
    }

    #[test]
    fn segment_relation_collinear_touch() {
        // Collinear segments touching at endpoint
        let a1 = Point::new(0.0, 0.0);
        let a2 = Point::new(5.0, 0.0);
        let b1 = Point::new(5.0, 0.0);
        let b2 = Point::new(10.0, 0.0);
        // This is Touch, not CollinearOverlap, because overlap is just a point
        assert_eq!(segment_relation(a1, a2, b1, b2), SegmentRelation::Touch);
        assert!(!segments_overlap(a1, a2, b1, b2));
        assert!(segments_interact(a1, a2, b1, b2));
    }

    #[test]
    fn segment_relation_disjoint() {
        // Disjoint segments
        let a1 = Point::new(0.0, 0.0);
        let a2 = Point::new(5.0, 0.0);
        let b1 = Point::new(6.0, 0.0);
        let b2 = Point::new(10.0, 0.0);
        assert_eq!(segment_relation(a1, a2, b1, b2), SegmentRelation::Disjoint);
        assert!(!segments_overlap(a1, a2, b1, b2));
        assert!(!segments_interact(a1, a2, b1, b2));
    }

    #[test]
    fn segment_relation_cross_near_endpoint() {
        // Proper cross very near endpoint but still crossing
        let a1 = Point::new(0.0, 0.0);
        let a2 = Point::new(10.0, 10.0);
        let b1 = Point::new(0.0, 10.0);
        let b2 = Point::new(10.0, 0.0);
        assert_eq!(
            segment_relation(a1, a2, b1, b2),
            SegmentRelation::ProperCross
        );
        assert!(segments_overlap(a1, a2, b1, b2));
    }
}