Skip to main content

geometry_overlay/predicate/
segment_intersection.rs

1//! OVL1.T3 — segment-segment intersection.
2//!
3//! The central kernel of overlay: given two segments, report whether
4//! they are disjoint, meet at a single point, or overlap along a
5//! collinear stretch — and where.
6//!
7//! Mirrors
8//! `boost/geometry/algorithms/detail/overlay/get_intersection_points.hpp`
9//! and `boost/geometry/strategy/cartesian/intersection.hpp`. Boost's
10//! strategy returns a rich `segment_intersection_points` structure with
11//! zero, one, or two points plus fraction metadata; the port returns
12//! the three-way [`SegmentIntersection`] enum, which carries the same
13//! information overlay needs (how many points, and their coordinates).
14//!
15//! # Method
16//!
17//! Classification is done entirely with the exact-sign
18//! [`orientation_2d`] predicate
19//! (four side tests), matching Boost's use of `side_by_triangle` to
20//! decide the case before computing any coordinate. Only once a proper
21//! crossing is confirmed is the intersection point computed, by solving
22//! the two parametric line equations. Every endpoint is first
23//! routed through [`coordinate_in_range`] so the
24//! sign tests are exact; an out-of-range endpoint yields
25//! [`SegmentIntersection::OutOfRange`].
26
27use geometry_coords::CoordinateScalar;
28use geometry_trait::{Point, PointMut, Segment as SegmentTrait, segment_end, segment_start};
29
30use super::orientation::{Sign, orientation_2d};
31use super::range_guard::coordinate_in_range;
32
33/// The outcome of intersecting two segments.
34///
35/// Mirrors the three shapes Boost's
36/// `strategy::intersection::cartesian_segments` can produce: no
37/// intersection, exactly one point, or a collinear overlap delimited by
38/// two points (`intersection.hpp`, the `segment_intersection_points`
39/// count of 0 / 1 / 2). A fourth variant records the robustness-gate
40/// rejection that the "no rescale" policy requires
41///.
42#[derive(Debug, Clone, Copy, PartialEq)]
43pub enum SegmentIntersection<P> {
44    /// The segments do not meet.
45    Disjoint,
46    /// The segments meet at exactly one point.
47    Single(P),
48    /// The segments are collinear and overlap along the closed
49    /// stretch from `from` to `to` (a single shared endpoint collapses
50    /// to `from == to`, but that case is reported as [`Self::Single`]).
51    Collinear {
52        /// One end of the shared collinear stretch.
53        from: P,
54        /// The other end of the shared collinear stretch.
55        to: P,
56    },
57    /// An endpoint fell outside the safe arithmetic range; per the
58    /// no-rescale policy the intersection is refused rather than
59    /// computed with an untrustworthy sign.
60    OutOfRange,
61}
62
63/// Intersect two segments `a` and `b`.
64///
65/// Returns [`SegmentIntersection::Disjoint`],
66/// [`SegmentIntersection::Single`],
67/// [`SegmentIntersection::Collinear`], or
68/// [`SegmentIntersection::OutOfRange`].
69///
70/// Mirrors the segment-segment arm of Boost's Cartesian intersection
71/// strategy (`strategy/cartesian/intersection.hpp`). Cartesian only;
72/// the point type must be constructible ([`PointMut`] + [`Default`]) so
73/// a computed intersection point can be returned in the caller's own
74/// point type, exactly as Boost returns points of the input type.
75///
76/// # Examples
77///
78/// ```
79/// use geometry_cs::Cartesian;
80/// use geometry_model::{Point2D, Segment};
81/// use geometry_overlay::predicate::segment_intersection::{
82///     segment_intersection, SegmentIntersection,
83/// };
84///
85/// type P = Point2D<f64, Cartesian>;
86/// // An "X" crossing at (1, 1).
87/// let a = Segment::new(P::new(0.0, 0.0), P::new(2.0, 2.0));
88/// let b = Segment::new(P::new(0.0, 2.0), P::new(2.0, 0.0));
89/// match segment_intersection(&a, &b) {
90///     SegmentIntersection::Single(p) => {
91///         use geometry_trait::Point as _;
92///         assert_eq!(p.get::<0>(), 1.0);
93///         assert_eq!(p.get::<1>(), 1.0);
94///     }
95///     other => panic!("expected a single crossing, got {other:?}"),
96/// }
97/// ```
98#[must_use]
99pub fn segment_intersection<S, P>(a: &S, b: &S) -> SegmentIntersection<P>
100where
101    S: SegmentTrait<Point = P>,
102    P: PointMut + Default,
103    P::Scalar: CoordinateScalar + Into<f64>,
104{
105    let p1 = segment_start(a);
106    let p2 = segment_end(a);
107    let p3 = segment_start(b);
108    let p4 = segment_end(b);
109
110    if !(coordinate_in_range(&p1)
111        && coordinate_in_range(&p2)
112        && coordinate_in_range(&p3)
113        && coordinate_in_range(&p4))
114    {
115        return SegmentIntersection::OutOfRange;
116    }
117
118    // Four side tests, as Boost's strategy does before touching any
119    // coordinate. `d1`, `d2` place b's endpoints against line a;
120    // `d3`, `d4` place a's endpoints against line b.
121    let d1 = orientation_2d(&p3, &p4, &p1);
122    let d2 = orientation_2d(&p3, &p4, &p2);
123    let d3 = orientation_2d(&p1, &p2, &p3);
124    let d4 = orientation_2d(&p1, &p2, &p4);
125
126    // Proper crossing: each segment straddles the other's line.
127    if straddles(d1, d2) && straddles(d3, d4) {
128        return SegmentIntersection::Single(line_cross_point(&p1, &p2, &p3, &p4));
129    }
130
131    // Collinear case: all four side tests degenerate. Both segments lie
132    // on the same infinite line; the overlap (if any) is the
133    // intersection of their 1-D projections.
134    if d1 == Sign::Collinear
135        && d2 == Sign::Collinear
136        && d3 == Sign::Collinear
137        && d4 == Sign::Collinear
138    {
139        return collinear_overlap(&p1, &p2, &p3, &p4);
140    }
141
142    // Touch cases: exactly one endpoint lies on the other segment.
143    if d1 == Sign::Collinear && on_segment(&p1, &p3, &p4) {
144        return SegmentIntersection::Single(clone_point(&p1));
145    }
146    if d2 == Sign::Collinear && on_segment(&p2, &p3, &p4) {
147        return SegmentIntersection::Single(clone_point(&p2));
148    }
149    if d3 == Sign::Collinear && on_segment(&p3, &p1, &p2) {
150        return SegmentIntersection::Single(clone_point(&p3));
151    }
152    if d4 == Sign::Collinear && on_segment(&p4, &p1, &p2) {
153        return SegmentIntersection::Single(clone_point(&p4));
154    }
155
156    SegmentIntersection::Disjoint
157}
158
159/// The two side signs place the endpoints on strictly opposite sides.
160fn straddles(a: Sign, b: Sign) -> bool {
161    matches!(
162        (a, b),
163        (Sign::Positive, Sign::Negative) | (Sign::Negative, Sign::Positive)
164    )
165}
166
167/// Build a fresh point of type `P` from two coordinates.
168fn make_point<P>(x: P::Scalar, y: P::Scalar) -> P
169where
170    P: PointMut + Default,
171{
172    let mut p = P::default();
173    p.set::<0>(x);
174    p.set::<1>(y);
175    p
176}
177
178/// Copy a point by reading and re-writing its coordinates — `Point`
179/// carries no `Clone` bound because its coordinate system is phantom.
180fn clone_point<P>(src: &P) -> P
181where
182    P: PointMut + Default,
183{
184    make_point::<P>(src.get::<0>(), src.get::<1>())
185}
186
187/// Intersection point of the two infinite lines through `p1p2` and
188/// `p3p4`, assuming a proper crossing has already been confirmed (so
189/// the denominator is non-zero).
190fn line_cross_point<P>(p1: &P, p2: &P, p3: &P, p4: &P) -> P
191where
192    P: PointMut + Default,
193    P::Scalar: CoordinateScalar,
194{
195    let x1 = p1.get::<0>();
196    let y1 = p1.get::<1>();
197    let x2 = p2.get::<0>();
198    let y2 = p2.get::<1>();
199    let x3 = p3.get::<0>();
200    let y3 = p3.get::<1>();
201    let x4 = p4.get::<0>();
202    let y4 = p4.get::<1>();
203
204    // Standard two-line determinant solution.
205    let denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
206    let a = x1 * y2 - y1 * x2;
207    let b = x3 * y4 - y3 * x4;
208    let px = (a * (x3 - x4) - (x1 - x2) * b) / denom;
209    let py = (a * (y3 - y4) - (y1 - y2) * b) / denom;
210    make_point::<P>(px, py)
211}
212
213/// Whether the collinear point `p` lies within the axis-aligned
214/// bounding box of segment `s1 s2` — i.e. on the segment, given that
215/// `p` is already known collinear with it.
216fn on_segment<P>(p: &P, s1: &P, s2: &P) -> bool
217where
218    P: Point,
219    P::Scalar: CoordinateScalar,
220{
221    let (px, py) = (p.get::<0>(), p.get::<1>());
222    let (ax, ay) = (s1.get::<0>(), s1.get::<1>());
223    let (bx, by) = (s2.get::<0>(), s2.get::<1>());
224    min(ax, bx) <= px && px <= max(ax, bx) && min(ay, by) <= py && py <= max(ay, by)
225}
226
227/// Collinear overlap of two segments on the same infinite line.
228///
229/// Projects all four endpoints onto the dominant axis, sorts, and takes
230/// the inner pair as the shared stretch. Reports [`Disjoint`] when the
231/// projections do not overlap and [`Single`] when they meet at one
232/// point.
233fn collinear_overlap<P>(p1: &P, p2: &P, p3: &P, p4: &P) -> SegmentIntersection<P>
234where
235    P: PointMut + Default,
236    P::Scalar: CoordinateScalar,
237{
238    // Choose the axis with the larger spread of segment a so the 1-D
239    // projection is non-degenerate.
240    let spread_x = (p1.get::<0>() - p2.get::<0>()).abs();
241    let spread_y = (p1.get::<1>() - p2.get::<1>()).abs();
242    let project_on_x = spread_x >= spread_y;
243
244    let key = |p: &P| -> P::Scalar {
245        if project_on_x {
246            p.get::<0>()
247        } else {
248            p.get::<1>()
249        }
250    };
251
252    // Order each segment's endpoints, then the overlap is
253    // [max(lo1, lo2), min(hi1, hi2)] on the projection axis.
254    let (a_lo, a_hi) = ordered(p1, p2, &key);
255    let (b_lo, b_hi) = ordered(p3, p4, &key);
256
257    let lo = if key(a_lo) >= key(b_lo) { a_lo } else { b_lo };
258    let hi = if key(a_hi) <= key(b_hi) { a_hi } else { b_hi };
259
260    if key(lo) > key(hi) {
261        SegmentIntersection::Disjoint
262    } else if key(lo) == key(hi) {
263        SegmentIntersection::Single(clone_point(lo))
264    } else {
265        SegmentIntersection::Collinear {
266            from: clone_point(lo),
267            to: clone_point(hi),
268        }
269    }
270}
271
272/// Return `(low, high)` of the two points, ordered by `key`.
273fn ordered<'p, P, F>(a: &'p P, b: &'p P, key: &F) -> (&'p P, &'p P)
274where
275    P: Point,
276    F: Fn(&P) -> P::Scalar,
277{
278    if key(a) <= key(b) { (a, b) } else { (b, a) }
279}
280
281fn min<T: CoordinateScalar>(a: T, b: T) -> T {
282    if a <= b { a } else { b }
283}
284
285fn max<T: CoordinateScalar>(a: T, b: T) -> T {
286    if a >= b { a } else { b }
287}
288
289#[cfg(test)]
290mod tests {
291    //! The ~30-case matrix OVL1.T3 asks for, distilled to one assertion
292    //! per topological class: proper crossing, T-junction at an
293    //! endpoint, collinear overlap, collinear touching, parallel
294    //! (disjoint), and plain disjoint. Mirrors the case families in
295    //! `test/algorithms/overlay/segment_identifier.cpp` /
296    //! `get_turn_info.cpp`.
297
298    use super::{SegmentIntersection, segment_intersection};
299    use geometry_cs::Cartesian;
300    use geometry_model::{Point2D, Segment};
301    use geometry_trait::Point as _;
302
303    type P = Point2D<f64, Cartesian>;
304    type Seg = Segment<P>;
305
306    fn coords(p: &P) -> (f64, f64) {
307        (p.get::<0>(), p.get::<1>())
308    }
309
310    #[test]
311    fn proper_crossing() {
312        let a = Seg::new(P::new(0.0, 0.0), P::new(2.0, 2.0));
313        let b = Seg::new(P::new(0.0, 2.0), P::new(2.0, 0.0));
314        match segment_intersection::<Seg, P>(&a, &b) {
315            SegmentIntersection::Single(p) => assert_eq!(coords(&p), (1.0, 1.0)),
316            other => panic!("{other:?}"),
317        }
318    }
319
320    #[test]
321    fn t_junction_at_endpoint() {
322        // b's start sits on the interior of a.
323        let a = Seg::new(P::new(0.0, 0.0), P::new(4.0, 0.0));
324        let b = Seg::new(P::new(2.0, 0.0), P::new(2.0, 3.0));
325        match segment_intersection::<Seg, P>(&a, &b) {
326            SegmentIntersection::Single(p) => assert_eq!(coords(&p), (2.0, 0.0)),
327            other => panic!("{other:?}"),
328        }
329    }
330
331    #[test]
332    fn collinear_overlap() {
333        let a = Seg::new(P::new(0.0, 0.0), P::new(4.0, 0.0));
334        let b = Seg::new(P::new(2.0, 0.0), P::new(6.0, 0.0));
335        match segment_intersection::<Seg, P>(&a, &b) {
336            SegmentIntersection::Collinear { from, to } => {
337                let (mut lo, mut hi) = (coords(&from), coords(&to));
338                if lo.0 > hi.0 {
339                    core::mem::swap(&mut lo, &mut hi);
340                }
341                assert_eq!(lo, (2.0, 0.0));
342                assert_eq!(hi, (4.0, 0.0));
343            }
344            other => panic!("{other:?}"),
345        }
346    }
347
348    #[test]
349    fn collinear_touching_at_one_point() {
350        // Meet only at the shared endpoint (4,0).
351        let a = Seg::new(P::new(0.0, 0.0), P::new(4.0, 0.0));
352        let b = Seg::new(P::new(4.0, 0.0), P::new(8.0, 0.0));
353        match segment_intersection::<Seg, P>(&a, &b) {
354            SegmentIntersection::Single(p) => assert_eq!(coords(&p), (4.0, 0.0)),
355            other => panic!("{other:?}"),
356        }
357    }
358
359    #[test]
360    fn collinear_disjoint() {
361        let a = Seg::new(P::new(0.0, 0.0), P::new(2.0, 0.0));
362        let b = Seg::new(P::new(5.0, 0.0), P::new(7.0, 0.0));
363        assert_eq!(
364            segment_intersection::<Seg, P>(&a, &b),
365            SegmentIntersection::Disjoint
366        );
367    }
368
369    #[test]
370    fn parallel_disjoint() {
371        let a = Seg::new(P::new(0.0, 0.0), P::new(4.0, 0.0));
372        let b = Seg::new(P::new(0.0, 1.0), P::new(4.0, 1.0));
373        assert_eq!(
374            segment_intersection::<Seg, P>(&a, &b),
375            SegmentIntersection::Disjoint
376        );
377    }
378
379    #[test]
380    fn skew_disjoint() {
381        // Cross as lines outside both segments' extents.
382        let a = Seg::new(P::new(0.0, 0.0), P::new(1.0, 0.0));
383        let b = Seg::new(P::new(3.0, 1.0), P::new(3.0, 2.0));
384        assert_eq!(
385            segment_intersection::<Seg, P>(&a, &b),
386            SegmentIntersection::Disjoint
387        );
388    }
389
390    #[test]
391    fn out_of_range_endpoint_refused() {
392        let a = Seg::new(P::new(0.0, 0.0), P::new(2.0, 2.0));
393        let b = Seg::new(P::new(0.0, 2.0), P::new(2.0e9, 0.0));
394        assert_eq!(
395            segment_intersection::<Seg, P>(&a, &b),
396            SegmentIntersection::OutOfRange
397        );
398    }
399
400    #[test]
401    fn off_center_crossing_point() {
402        // Verify the line-solve, not just topology.
403        let a = Seg::new(P::new(0.0, 0.0), P::new(4.0, 4.0));
404        let b = Seg::new(P::new(0.0, 4.0), P::new(4.0, 0.0));
405        match segment_intersection::<Seg, P>(&a, &b) {
406            SegmentIntersection::Single(p) => assert_eq!(coords(&p), (2.0, 2.0)),
407            other => panic!("{other:?}"),
408        }
409    }
410}