Skip to main content

lib_jsl_geometry/algorithms/
intersection.rs

1//! Intersection tests and constructions between common primitives.
2//!
3//! Points and vectors are `[f64; 2]` / `[f64; 3]` arrays. Parallel and touching configurations
4//! are handled explicitly; tolerances are absolute and stated per function where they matter.
5//!
6//! See the book entry [Intersections and closest points](https://jwkunz.github.io/lib_jsl/book/geometry/intersections.html#intersection-tests).
7
8fn sub2(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
9    [a[0] - b[0], a[1] - b[1]]
10}
11fn cross2(a: [f64; 2], b: [f64; 2]) -> f64 {
12    a[0] * b[1] - a[1] * b[0]
13}
14fn dot2(a: [f64; 2], b: [f64; 2]) -> f64 {
15    a[0] * b[0] + a[1] * b[1]
16}
17fn sub3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
18    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
19}
20fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
21    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
22}
23fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
24    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
25}
26fn at3(o: [f64; 3], d: [f64; 3], t: f64) -> [f64; 3] {
27    [o[0] + t * d[0], o[1] + t * d[1], o[2] + t * d[2]]
28}
29
30/// Result of intersecting two segments or lines in the plane.
31#[derive(Debug, Clone, Copy, PartialEq)]
32
33pub enum Intersection2D {
34    /// No common point.
35    None,
36    /// A single common point.
37    Point([f64; 2]),
38    /// Collinear segments sharing a sub-segment from the first to the second point.
39    Overlap([f64; 2], [f64; 2]),
40}
41
42/// Intersection of segments `a`-`b` and `c`-`d`, including touching ends and collinear overlap.
43pub fn segment_segment_2d(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> Intersection2D {
44    let (r, s) = (sub2(b, a), sub2(d, c));
45    let denom = cross2(r, s);
46    let ca = sub2(c, a);
47    let scale = (dot2(r, r) * dot2(s, s)).sqrt();
48    if denom.abs() <= 1e-14 * scale {
49        // Parallel: intersect only if collinear.
50        if cross2(ca, r).abs() > 1e-12 * dot2(r, r).sqrt().max(dot2(s, s).sqrt()).max(f64::MIN_POSITIVE) * ca[0].abs().max(ca[1].abs()).max(1.0) {
51            return Intersection2D::None;
52        }
53        let rr = dot2(r, r);
54        if rr == 0.0 {
55            // First segment is a point: on the second?
56            let ss = dot2(s, s);
57            let on = ss == 0.0 && a == c || ss > 0.0 && cross2(sub2(a, c), s).abs() <= 1e-12 * ss.sqrt() && (0.0..=ss).contains(&dot2(sub2(a, c), s));
58            return if on { Intersection2D::Point(a) } else { Intersection2D::None };
59        }
60        let (t0, t1) = (dot2(ca, r) / rr, dot2(sub2(d, a), r) / rr);
61        let (lo, hi) = (t0.min(t1).max(0.0), t0.max(t1).min(1.0));
62        return if lo > hi {
63            Intersection2D::None
64        } else if lo == hi {
65            Intersection2D::Point([a[0] + lo * r[0], a[1] + lo * r[1]])
66        } else {
67            Intersection2D::Overlap([a[0] + lo * r[0], a[1] + lo * r[1]], [a[0] + hi * r[0], a[1] + hi * r[1]])
68        };
69    }
70    let t = cross2(ca, s) / denom;
71    let u = cross2(ca, r) / denom;
72    let eps = 1e-12;
73    if (-eps..=1.0 + eps).contains(&t) && (-eps..=1.0 + eps).contains(&u) {
74        Intersection2D::Point([a[0] + t * r[0], a[1] + t * r[1]])
75    } else {
76        Intersection2D::None
77    }
78}
79
80/// Intersection point of two infinite lines (point + direction); `None` if parallel.
81pub fn line_line_2d(p: [f64; 2], dp: [f64; 2], q: [f64; 2], dq: [f64; 2]) -> Option<[f64; 2]> {
82    let denom = cross2(dp, dq);
83    if denom.abs() <= 1e-14 * (dot2(dp, dp) * dot2(dq, dq)).sqrt() || denom == 0.0 {
84        return None;
85    }
86    let t = cross2(sub2(q, p), dq) / denom;
87    Some([p[0] + t * dp[0], p[1] + t * dp[1]])
88}
89
90/// The (up to two) intersection points of two circles, `(centre, radius)`. Coincident circles give
91/// `None`; tangent circles give one point (repeated).
92pub fn circle_circle(c1: [f64; 2], r1: f64, c2: [f64; 2], r2: f64) -> Option<[[f64; 2]; 2]> {
93    let d = sub2(c2, c1);
94    let dist = dot2(d, d).sqrt();
95    if dist == 0.0 || dist > r1 + r2 || dist < (r1 - r2).abs() {
96        return None;
97    }
98    let a = (r1 * r1 - r2 * r2 + dist * dist) / (2.0 * dist);
99    let h = (r1 * r1 - a * a).max(0.0).sqrt();
100    let m = [c1[0] + a * d[0] / dist, c1[1] + a * d[1] / dist];
101    let off = [-h * d[1] / dist, h * d[0] / dist];
102    Some([[m[0] + off[0], m[1] + off[1]], [m[0] - off[0], m[1] - off[1]]])
103}
104
105/// Where a ray (or line) meets a plane: the parameter `t` such that `origin + t dir` lies on the
106/// plane through `plane_point` with `normal`. `None` if parallel (including lying in the plane).
107pub fn line_plane_parameter(origin: [f64; 3], dir: [f64; 3], plane_point: [f64; 3], normal: [f64; 3]) -> Option<f64> {
108    let denom = dot3(dir, normal);
109    let scale = (dot3(dir, dir) * dot3(normal, normal)).sqrt();
110    if denom.abs() <= 1e-14 * scale || denom == 0.0 {
111        return None;
112    }
113    Some(dot3(sub3(plane_point, origin), normal) / denom)
114}
115
116/// Ray-plane intersection point (`t >= 0`).
117pub fn ray_plane(origin: [f64; 3], dir: [f64; 3], plane_point: [f64; 3], normal: [f64; 3]) -> Option<[f64; 3]> {
118    line_plane_parameter(origin, dir, plane_point, normal).filter(|&t| t >= 0.0).map(|t| at3(origin, dir, t))
119}
120
121/// Segment-plane intersection point, if the segment `a`-`b` crosses or touches the plane in a
122/// single point.
123pub fn segment_plane(a: [f64; 3], b: [f64; 3], plane_point: [f64; 3], normal: [f64; 3]) -> Option<[f64; 3]> {
124    let d = sub3(b, a);
125    line_plane_parameter(a, d, plane_point, normal).filter(|t| (0.0..=1.0).contains(t)).map(|t| at3(a, d, t))
126}
127
128/// The line where two planes meet, as `(point, unit direction)`; `None` if parallel.
129pub fn plane_plane(p1: [f64; 3], n1: [f64; 3], p2: [f64; 3], n2: [f64; 3]) -> Option<([f64; 3], [f64; 3])> {
130    let dir = cross3(n1, n2);
131    let d2 = dot3(dir, dir);
132    if d2 <= 1e-28 * dot3(n1, n1) * dot3(n2, n2) || d2 == 0.0 {
133        return None;
134    }
135    let (h1, h2) = (dot3(n1, p1), dot3(n2, p2));
136    // point = (h1 (n2 × dir) + h2 (dir × n1)) / |dir|²
137    let a = cross3(n2, dir);
138    let b = cross3(dir, n1);
139    let point = [(h1 * a[0] + h2 * b[0]) / d2, (h1 * a[1] + h2 * b[1]) / d2, (h1 * a[2] + h2 * b[2]) / d2];
140    let len = d2.sqrt();
141    Some((point, [dir[0] / len, dir[1] / len, dir[2] / len]))
142}
143
144/// A ray-triangle hit: distance along the ray and barycentric weights of the hit point.
145#[derive(Debug, Clone, Copy, PartialEq)]
146
147pub struct TriangleHit {
148    pub t: f64,
149    /// Weights `[wa, wb, wc]` of the triangle's vertices at the hit point.
150    pub barycentric: [f64; 3],
151}
152
153/// Ray-triangle intersection by the Möller-Trumbore algorithm. Both faces are hit; `t >= 0`.
154pub fn ray_triangle(origin: [f64; 3], dir: [f64; 3], a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Option<TriangleHit> {
155    let (e1, e2) = (sub3(b, a), sub3(c, a));
156    let h = cross3(dir, e2);
157    let det = dot3(e1, h);
158    if det.abs() < 1e-14 * (dot3(e1, e1) * dot3(e2, e2)).sqrt() * dot3(dir, dir).sqrt() || det == 0.0 {
159        return None;
160    }
161    let s = sub3(origin, a);
162    let u = dot3(s, h) / det;
163    let q = cross3(s, e1);
164    let v = dot3(dir, q) / det;
165    let t = dot3(e2, q) / det;
166    let eps = 1e-12;
167    (u >= -eps && v >= -eps && u + v <= 1.0 + eps && t >= 0.0).then_some(TriangleHit { t, barycentric: [1.0 - u - v, u, v] })
168}
169
170/// Segment-triangle intersection: the hit if the segment `p`-`q` reaches the triangle.
171pub fn segment_triangle(p: [f64; 3], q: [f64; 3], a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Option<TriangleHit> {
172    let d = sub3(q, p);
173    ray_triangle(p, d, a, b, c).filter(|h| h.t <= 1.0)
174}
175
176/// Ray-sphere intersection: the entry and exit parameters `(t_near, t_far)` with `t_far >= 0`
177/// (`t_near` is negative when the origin is inside).
178pub fn ray_sphere(origin: [f64; 3], dir: [f64; 3], centre: [f64; 3], radius: f64) -> Option<(f64, f64)> {
179    let m = sub3(origin, centre);
180    let a = dot3(dir, dir);
181    if a == 0.0 {
182        return None;
183    }
184    let b = dot3(m, dir);
185    let disc = b * b - a * (dot3(m, m) - radius * radius);
186    if disc < 0.0 {
187        return None;
188    }
189    let s = disc.sqrt();
190    let (t0, t1) = ((-b - s) / a, (-b + s) / a);
191    (t1 >= 0.0).then_some((t0, t1))
192}
193
194/// Ray-box intersection by the slab method: `(t_near, t_far)` with `t_far >= max(t_near, 0)`.
195pub fn ray_aabb(origin: [f64; 3], dir: [f64; 3], min: [f64; 3], max: [f64; 3]) -> Option<(f64, f64)> {
196    let (mut t0, mut t1) = (f64::NEG_INFINITY, f64::INFINITY);
197    for k in 0..3 {
198        if dir[k] == 0.0 {
199            if origin[k] < min[k] || origin[k] > max[k] {
200                return None;
201            }
202        } else {
203            let (a, b) = ((min[k] - origin[k]) / dir[k], (max[k] - origin[k]) / dir[k]);
204            t0 = t0.max(a.min(b));
205            t1 = t1.min(a.max(b));
206        }
207    }
208    (t1 >= t0.max(0.0)).then_some((t0, t1))
209}
210
211/// Whether two axis-aligned boxes overlap (touching counts).
212pub fn aabb_aabb<const D: usize>(min1: [f64; D], max1: [f64; D], min2: [f64; D], max2: [f64; D]) -> bool {
213    (0..D).all(|k| min1[k] <= max2[k] && min2[k] <= max1[k])
214}
215
216/// Whether two spheres/circles/balls overlap (touching counts).
217pub fn sphere_sphere<const D: usize>(c1: [f64; D], r1: f64, c2: [f64; D], r2: f64) -> bool {
218    let d2: f64 = (0..D).map(|k| (c1[k] - c2[k]) * (c1[k] - c2[k])).sum();
219    d2 <= (r1 + r2) * (r1 + r2)
220}
221
222/// The intersection of triangle `abc` with a plane as a segment `(p, q)`, if the plane cuts the
223/// triangle properly (crosses it, or contains exactly one of its edges). Triangles lying in the
224/// plane, or touching it at a single vertex, give `None`. Distances are signed against the plane
225/// through `plane_point` with `normal`; values within `tol` of zero count as on the plane.
226pub fn triangle_plane(a: [f64; 3], b: [f64; 3], c: [f64; 3], plane_point: [f64; 3], normal: [f64; 3], tol: f64) -> Option<([f64; 3], [f64; 3])> {
227    let v = [a, b, c];
228    let nlen = dot3(normal, normal).sqrt();
229    if nlen == 0.0 {
230        return None;
231    }
232    let d: Vec<f64> = v.iter().map(|&p| dot3(sub3(p, plane_point), normal) / nlen).map(|x| if x.abs() <= tol { 0.0 } else { x }).collect();
233    let (pos, neg, zero) = (d.iter().filter(|&&x| x > 0.0).count(), d.iter().filter(|&&x| x < 0.0).count(), d.iter().filter(|&&x| x == 0.0).count());
234    if (pos == 0 && neg == 0) || pos + zero == 3 && zero < 2 || neg + zero == 3 && zero < 2 {
235        return None; // coplanar, or touching at one vertex / entirely on one side
236    }
237    if zero == 2 {
238        let idx: Vec<usize> = (0..3).filter(|&i| d[i] == 0.0).collect();
239        return Some((v[idx[0]], v[idx[1]]));
240    }
241    // Collect the points where triangle edges cross the plane (zero vertices count as crossings).
242    let mut pts: Vec<[f64; 3]> = Vec::with_capacity(2);
243    for i in 0..3 {
244        let j = (i + 1) % 3;
245        if d[i] == 0.0 {
246            pts.push(v[i]);
247        } else if d[i] * d[j] < 0.0 {
248            let t = d[i] / (d[i] - d[j]);
249            pts.push(at3(v[i], sub3(v[j], v[i]), t));
250        }
251    }
252    pts.dedup();
253    (pts.len() == 2).then(|| (pts[0], pts[1]))
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    fn close<const D: usize>(a: [f64; D], b: [f64; D]) -> bool {
261        (0..D).all(|k| (a[k] - b[k]).abs() < 1e-12)
262    }
263
264    #[test]
265    fn segments_and_lines_2d() {
266        assert_eq!(segment_segment_2d([0.0, 0.0], [2.0, 2.0], [0.0, 2.0], [2.0, 0.0]), Intersection2D::Point([1.0, 1.0]));
267        assert_eq!(segment_segment_2d([0.0, 0.0], [1.0, 0.0], [2.0, 1.0], [3.0, -1.0]), Intersection2D::None);
268        // Touching at an endpoint (T junction).
269        assert_eq!(segment_segment_2d([0.0, 0.0], [2.0, 0.0], [1.0, 0.0], [1.0, 3.0]), Intersection2D::Point([1.0, 0.0]));
270        // Collinear: overlap, touching, and disjoint.
271        assert_eq!(segment_segment_2d([0.0, 0.0], [4.0, 0.0], [2.0, 0.0], [6.0, 0.0]), Intersection2D::Overlap([2.0, 0.0], [4.0, 0.0]));
272        assert_eq!(segment_segment_2d([0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [2.0, 0.0]), Intersection2D::Point([1.0, 0.0]));
273        assert_eq!(segment_segment_2d([0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]), Intersection2D::None);
274        assert_eq!(segment_segment_2d([0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]), Intersection2D::None);
275        assert!(close(line_line_2d([0.0, 0.0], [1.0, 1.0], [0.0, 2.0], [1.0, -1.0]).unwrap(), [1.0, 1.0]));
276        assert!(line_line_2d([0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [2.0, 0.0]).is_none());
277        let pts = circle_circle([0.0, 0.0], 5.0, [6.0, 0.0], 5.0).unwrap();
278        assert!(close(pts[0], [3.0, 4.0]) && close(pts[1], [3.0, -4.0]));
279        assert!(circle_circle([0.0, 0.0], 1.0, [5.0, 0.0], 1.0).is_none() && circle_circle([0.0, 0.0], 3.0, [1.0, 0.0], 1.0).is_none());
280        let tangent = circle_circle([0.0, 0.0], 1.0, [2.0, 0.0], 1.0).unwrap();
281        assert!(close(tangent[0], [1.0, 0.0]) && close(tangent[1], [1.0, 0.0]));
282    }
283
284    #[test]
285    fn planes() {
286        let (o, d) = ([0.0, 0.0, 5.0], [0.0, 0.0, -1.0]);
287        assert!(close(ray_plane(o, d, [0.0; 3], [0.0, 0.0, 1.0]).unwrap(), [0.0, 0.0, 0.0]));
288        assert!(ray_plane(o, [0.0, 0.0, 1.0], [0.0; 3], [0.0, 0.0, 1.0]).is_none()); // behind
289        assert!(ray_plane(o, [1.0, 0.0, 0.0], [0.0; 3], [0.0, 0.0, 1.0]).is_none()); // parallel
290        assert!(close(segment_plane([0.0, 0.0, -1.0], [2.0, 0.0, 3.0], [0.0; 3], [0.0, 0.0, 1.0]).unwrap(), [0.5, 0.0, 0.0]));
291        assert!(segment_plane([0.0, 0.0, 1.0], [0.0, 0.0, 2.0], [0.0; 3], [0.0, 0.0, 1.0]).is_none());
292        let (p, dir) = plane_plane([0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]).unwrap();
293        assert!(close(p, [0.0; 3]) && close([dir[0].abs(), dir[1].abs(), dir[2].abs()], [0.0, 1.0, 0.0]));
294        // Offset planes z = 1 and x = 2 meet along the line (2, y, 1).
295        let (p, dir) = plane_plane([0.0, 0.0, 1.0], [0.0, 0.0, 3.0], [2.0, 0.0, 0.0], [5.0, 0.0, 0.0]).unwrap();
296        assert!(close([p[0], p[2]], [2.0, 1.0]) && dir[0].abs() < 1e-12 && dir[2].abs() < 1e-12);
297        assert!(plane_plane([0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 2.0]).is_none());
298    }
299
300    #[test]
301    fn rays_against_triangles_spheres_and_boxes() {
302        let (a, b, c) = ([0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [0.0, 4.0, 0.0]);
303        let hit = ray_triangle([1.0, 1.0, 5.0], [0.0, 0.0, -1.0], a, b, c).unwrap();
304        assert!((hit.t - 5.0).abs() < 1e-12 && close(hit.barycentric, [0.5, 0.25, 0.25]));
305        assert!(ray_triangle([3.0, 3.0, 5.0], [0.0, 0.0, -1.0], a, b, c).is_none()); // outside
306        assert!(ray_triangle([1.0, 1.0, 5.0], [0.0, 0.0, 1.0], a, b, c).is_none()); // pointing away
307        assert!(ray_triangle([1.0, 1.0, 5.0], [1.0, 0.0, 0.0], a, b, c).is_none()); // parallel
308        assert!(segment_triangle([1.0, 1.0, 5.0], [1.0, 1.0, 1.0], a, b, c).is_none() && segment_triangle([1.0, 1.0, 5.0], [1.0, 1.0, -1.0], a, b, c).is_some());
309        let (n, f) = ray_sphere([0.0, 0.0, -5.0], [0.0, 0.0, 1.0], [0.0; 3], 2.0).unwrap();
310        assert!((n - 3.0).abs() < 1e-12 && (f - 7.0).abs() < 1e-12);
311        let (n, _) = ray_sphere([0.0; 3], [1.0, 0.0, 0.0], [0.0; 3], 2.0).unwrap();
312        assert!(n < 0.0);
313        assert!(ray_sphere([0.0, 3.0, -5.0], [0.0, 0.0, 1.0], [0.0; 3], 2.0).is_none() && ray_sphere([0.0, 0.0, 5.0], [0.0, 0.0, 1.0], [0.0; 3], 2.0).is_none());
314        let (n, f) = ray_aabb([-5.0, 0.5, 0.5], [1.0, 0.0, 0.0], [0.0; 3], [1.0; 3]).unwrap();
315        assert!((n - 5.0).abs() < 1e-12 && (f - 6.0).abs() < 1e-12);
316        assert!(ray_aabb([-5.0, 2.0, 0.5], [1.0, 0.0, 0.0], [0.0; 3], [1.0; 3]).is_none() && ray_aabb([5.0, 0.5, 0.5], [1.0, 0.0, 0.0], [0.0; 3], [1.0; 3]).is_none());
317        assert!(aabb_aabb([0.0, 0.0], [1.0, 1.0], [1.0, 1.0], [2.0, 2.0]) && !aabb_aabb([0.0; 3], [1.0; 3], [1.1; 3], [2.0; 3]));
318        assert!(sphere_sphere([0.0; 3], 1.0, [2.0, 0.0, 0.0], 1.0) && !sphere_sphere([0.0, 0.0], 1.0, [3.0, 0.0], 1.0));
319    }
320
321    #[test]
322    fn triangle_plane_cases() {
323        let (a, b, c) = ([0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [0.0, 0.0, 4.0]);
324        let n = [0.0, 1.0, 0.0];
325        // Plane y = 0 contains the whole triangle: no unique segment.
326        assert!(triangle_plane(a, b, c, [0.0; 3], n, 1e-12).is_none());
327        // Cutting through: vertices at y = -1, -1, +3 -> segment between two edge crossings.
328        let (p, q) = triangle_plane([0.0, -1.0, 0.0], [4.0, -1.0, 0.0], [0.0, 3.0, 0.0], [0.0; 3], n, 1e-12).unwrap();
329        assert!((p[1]).abs() < 1e-12 && (q[1]).abs() < 1e-12 && (p[0] - q[0]).abs() > 0.5);
330        // Plane through one vertex and the opposite edge.
331        let (p, q) = triangle_plane([0.0, 0.0, 0.0], [2.0, 1.0, 0.0], [2.0, -1.0, 0.0], [0.0; 3], n, 1e-12).unwrap();
332        assert!(close(p, [0.0; 3]) && close(q, [2.0, 0.0, 0.0]));
333        // Plane containing an edge, triangle on one side.
334        let (p, q) = triangle_plane([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0; 3], n, 1e-12).unwrap();
335        assert!(close(p, [0.0; 3]) && close(q, [1.0, 0.0, 0.0]));
336        // Touching at a single vertex, or entirely on one side.
337        assert!(triangle_plane([0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 1.0], [0.0; 3], n, 1e-12).is_none());
338        assert!(triangle_plane([0.0, 1.0, 0.0], [1.0, 2.0, 0.0], [0.0, 3.0, 1.0], [0.0; 3], n, 1e-12).is_none());
339    }
340}