Skip to main content

lib_jsl_geometry/algorithms/
nearest_point_finding.rs

1//! Closest-point queries: the point of a primitive nearest to a query point.
2//!
3//! Points and vectors are plain `[f64; D]` arrays. Every query returns the closest point together
4//! with whatever parameterisation is natural for the primitive (a segment parameter, barycentric
5//! coordinates, ...), and distances are Euclidean. For nearest neighbours *within a large point
6//! set*, build a [`KdTree`](super::kd_trees::KdTree) instead.
7//!
8//! See the book entry [Intersections and closest points](https://jwkunz.github.io/lib_jsl/book/geometry/intersections.html#closest-points).
9
10fn sub<const D: usize>(a: [f64; D], b: [f64; D]) -> [f64; D] {
11    std::array::from_fn(|k| a[k] - b[k])
12}
13fn add_scaled<const D: usize>(a: [f64; D], b: [f64; D], s: f64) -> [f64; D] {
14    std::array::from_fn(|k| a[k] + s * b[k])
15}
16fn dot<const D: usize>(a: [f64; D], b: [f64; D]) -> f64 {
17    (0..D).map(|k| a[k] * b[k]).sum()
18}
19fn distance<const D: usize>(a: [f64; D], b: [f64; D]) -> f64 {
20    let d = sub(a, b);
21    dot(d, d).sqrt()
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}
26
27/// A closest point and its distance from the query.
28#[derive(Debug, Clone, Copy, PartialEq)]
29
30pub struct Closest<const D: usize> {
31    pub point: [f64; D],
32    pub distance: f64,
33}
34
35impl<const D: usize> Closest<D> {
36    fn new(query: [f64; D], point: [f64; D]) -> Self {
37        Closest { point, distance: distance(query, point) }
38    }
39}
40
41/// The closest point on segment `a`-`b`, and its parameter `t` in `[0, 1]` (`a + t (b - a)`).
42/// A degenerate segment (`a == b`) returns `a` with `t = 0`.
43pub fn closest_point_on_segment<const D: usize>(p: [f64; D], a: [f64; D], b: [f64; D]) -> (Closest<D>, f64) {
44    let ab = sub(b, a);
45    let len2 = dot(ab, ab);
46    let t = if len2 == 0.0 { 0.0 } else { (dot(sub(p, a), ab) / len2).clamp(0.0, 1.0) };
47    (Closest::new(p, add_scaled(a, ab, t)), t)
48}
49
50/// The closest point on the infinite line through `origin` with direction `dir`, and its
51/// (unclamped) parameter. A zero direction returns `origin`.
52pub fn closest_point_on_line<const D: usize>(p: [f64; D], origin: [f64; D], dir: [f64; D]) -> (Closest<D>, f64) {
53    let len2 = dot(dir, dir);
54    let t = if len2 == 0.0 { 0.0 } else { dot(sub(p, origin), dir) / len2 };
55    (Closest::new(p, add_scaled(origin, dir, t)), t)
56}
57
58/// The closest point on the ray from `origin` along `dir` (parameter `t >= 0`).
59pub fn closest_point_on_ray<const D: usize>(p: [f64; D], origin: [f64; D], dir: [f64; D]) -> (Closest<D>, f64) {
60    let (c, t) = closest_point_on_line(p, origin, dir);
61    if t >= 0.0 { (c, t) } else { (Closest::new(p, origin), 0.0) }
62}
63
64/// The closest point on a plane given by a point on it and a normal (need not be unit); also the
65/// signed distance (positive on the side the normal points to). `None` for a zero normal.
66pub fn closest_point_on_plane(p: [f64; 3], plane_point: [f64; 3], normal: [f64; 3]) -> Option<(Closest<3>, f64)> {
67    let n2 = dot(normal, normal);
68    if n2 == 0.0 {
69        return None;
70    }
71    let signed = dot(sub(p, plane_point), normal) / n2.sqrt();
72    let point = add_scaled(p, normal, -signed / n2.sqrt());
73    Some((Closest { point, distance: signed.abs() }, signed))
74}
75
76/// The closest point on the (filled) triangle `abc` in 3D, with its barycentric coordinates
77/// `[wa, wb, wc]` (non-negative, summing to 1). Works for degenerate triangles too.
78// ANCHOR: closest_triangle
79pub fn closest_point_on_triangle(p: [f64; 3], a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> (Closest<3>, [f64; 3]) {
80    // Ericson, Real-Time Collision Detection, 5.1.5: classify p by Voronoi region.
81    let (ab, ac, ap) = (sub(b, a), sub(c, a), sub(p, a));
82    let (d1, d2) = (dot(ab, ap), dot(ac, ap));
83    if d1 <= 0.0 && d2 <= 0.0 {
84        return (Closest::new(p, a), [1.0, 0.0, 0.0]);
85    }
86    let bp = sub(p, b);
87    let (d3, d4) = (dot(ab, bp), dot(ac, bp));
88    if d3 >= 0.0 && d4 <= d3 {
89        return (Closest::new(p, b), [0.0, 1.0, 0.0]);
90    }
91    let vc = d1 * d4 - d3 * d2;
92    if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
93        let v = d1 / (d1 - d3);
94        return (Closest::new(p, add_scaled(a, ab, v)), [1.0 - v, v, 0.0]);
95    }
96    let cp = sub(p, c);
97    let (d5, d6) = (dot(ab, cp), dot(ac, cp));
98    if d6 >= 0.0 && d5 <= d6 {
99        return (Closest::new(p, c), [0.0, 0.0, 1.0]);
100    }
101    let vb = d5 * d2 - d1 * d6;
102    if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
103        let w = d2 / (d2 - d6);
104        return (Closest::new(p, add_scaled(a, ac, w)), [1.0 - w, 0.0, w]);
105    }
106    let va = d3 * d6 - d5 * d4;
107    if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
108        let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
109        return (Closest::new(p, add_scaled(b, sub(c, b), w)), [0.0, 1.0 - w, w]);
110    }
111    let denom = va + vb + vc;
112    if denom == 0.0 {
113        // Degenerate (collinear) triangle: fall back to the nearest of its three edges.
114        let best = [(a, b), (b, c), (c, a)]
115            .into_iter()
116            .map(|(u, v)| closest_point_on_segment(p, u, v).0)
117            .min_by(|x, y| x.distance.total_cmp(&y.distance))
118            .expect("three edges");
119        return (best, [f64::NAN; 3]);
120    }
121    let (v, w) = (vb / denom, vc / denom);
122    (Closest::new(p, add_scaled(add_scaled(a, ab, v), ac, w)), [1.0 - v - w, v, w])
123}
124// ANCHOR_END: closest_triangle
125
126/// The closest point in the axis-aligned box `[min, max]` (the point itself if inside).
127pub fn closest_point_on_aabb<const D: usize>(p: [f64; D], min: [f64; D], max: [f64; D]) -> Closest<D> {
128    Closest::new(p, std::array::from_fn(|k| p[k].clamp(min[k], max[k])))
129}
130
131/// The closest point on the surface of a sphere (the centre direction is arbitrary if `p` is at
132/// the centre: the +x pole is returned).
133pub fn closest_point_on_sphere<const D: usize>(p: [f64; D], centre: [f64; D], radius: f64) -> Closest<D> {
134    let d = sub(p, centre);
135    let len = dot(d, d).sqrt();
136    let dir: [f64; D] = if len == 0.0 { std::array::from_fn(|k| if k == 0 { 1.0 } else { 0.0 }) } else { std::array::from_fn(|k| d[k] / len) };
137    Closest::new(p, add_scaled(centre, dir, radius))
138}
139
140/// The closest point on a polyline's segments, with the index of the segment it lies on and the
141/// parameter along it. `None` if there are fewer than two vertices.
142pub fn closest_point_on_polyline<const D: usize>(p: [f64; D], vertices: &[[f64; D]]) -> Option<(Closest<D>, usize, f64)> {
143    vertices
144        .windows(2)
145        .enumerate()
146        .map(|(i, w)| {
147            let (c, t) = closest_point_on_segment(p, w[0], w[1]);
148            (c, i, t)
149        })
150        .min_by(|x, y| x.0.distance.total_cmp(&y.0.distance))
151}
152
153/// The closest point on the boundary of a closed polygon (its last vertex joins the first).
154pub fn closest_point_on_polygon_boundary<const D: usize>(p: [f64; D], vertices: &[[f64; D]]) -> Option<(Closest<D>, usize, f64)> {
155    if vertices.len() < 2 {
156        return None;
157    }
158    let mut closed = vertices.to_vec();
159    closed.push(vertices[0]);
160    closest_point_on_polyline(p, &closed)
161}
162
163/// The closest point on a triangle mesh (brute force over triangles) with the triangle index.
164/// Triangles index into `vertices`; `None` for an empty mesh or out-of-range indices.
165pub fn closest_point_on_mesh(p: [f64; 3], vertices: &[[f64; 3]], triangles: &[[usize; 3]]) -> Option<(Closest<3>, usize)> {
166    triangles
167        .iter()
168        .enumerate()
169        .map(|(i, t)| {
170            let [a, b, c] = [*vertices.get(t[0])?, *vertices.get(t[1])?, *vertices.get(t[2])?];
171            Some((closest_point_on_triangle(p, a, b, c).0, i))
172        })
173        .collect::<Option<Vec<_>>>()?
174        .into_iter()
175        .min_by(|x, y| x.0.distance.total_cmp(&y.0.distance))
176}
177
178/// The closest points between segments `p1`-`q1` and `p2`-`q2`: `(point on first, point on
179/// second, distance)`; the segments may be degenerate (points). Ericson 5.1.9.
180pub fn closest_points_between_segments<const D: usize>(p1: [f64; D], q1: [f64; D], p2: [f64; D], q2: [f64; D]) -> ([f64; D], [f64; D], f64) {
181    let (d1, d2, r) = (sub(q1, p1), sub(q2, p2), sub(p1, p2));
182    let (a, e, f) = (dot(d1, d1), dot(d2, d2), dot(d2, r));
183    let (s, t);
184    if a <= 1e-300 && e <= 1e-300 {
185        (s, t) = (0.0, 0.0);
186    } else if a <= 1e-300 {
187        s = 0.0;
188        t = (f / e).clamp(0.0, 1.0);
189    } else {
190        let c = dot(d1, r);
191        if e <= 1e-300 {
192            t = 0.0;
193            s = (-c / a).clamp(0.0, 1.0);
194        } else {
195            let b = dot(d1, d2);
196            let denom = a * e - b * b;
197            let mut s_ = if denom > 1e-14 * a * e { ((b * f - c * e) / denom).clamp(0.0, 1.0) } else { 0.0 };
198            let mut t_ = (b * s_ + f) / e;
199            if t_ < 0.0 {
200                t_ = 0.0;
201                s_ = (-c / a).clamp(0.0, 1.0);
202            } else if t_ > 1.0 {
203                t_ = 1.0;
204                s_ = ((b - c) / a).clamp(0.0, 1.0);
205            }
206            (s, t) = (s_, t_);
207        }
208    }
209    let (c1, c2) = (add_scaled(p1, d1, s), add_scaled(p2, d2, t));
210    (c1, c2, distance(c1, c2))
211}
212
213/// The distance from `p` to the infinite 3D line through `a` and `b` (the point distance to `a`
214/// if they coincide).
215pub fn distance_point_to_line_3d(p: [f64; 3], a: [f64; 3], b: [f64; 3]) -> f64 {
216    let ab = sub(b, a);
217    let len = dot(ab, ab).sqrt();
218    if len == 0.0 {
219        return distance(p, a);
220    }
221    let c = cross3(sub(p, a), ab);
222    dot(c, c).sqrt() / len
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    fn close<const D: usize>(a: [f64; D], b: [f64; D]) -> bool {
230        (0..D).all(|k| (a[k] - b[k]).abs() < 1e-12)
231    }
232
233    #[test]
234    fn segment_line_ray() {
235        let (c, t) = closest_point_on_segment([1.0, 2.0], [0.0, 0.0], [4.0, 0.0]);
236        assert!(close(c.point, [1.0, 0.0]) && (c.distance - 2.0).abs() < 1e-12 && (t - 0.25).abs() < 1e-12);
237        let (c, t) = closest_point_on_segment([9.0, 3.0], [0.0, 0.0], [4.0, 0.0]);
238        assert!(close(c.point, [4.0, 0.0]) && t == 1.0);
239        assert_eq!(closest_point_on_segment([1.0, 1.0], [2.0, 2.0], [2.0, 2.0]).1, 0.0);
240        let (c, t) = closest_point_on_line([9.0, 3.0], [0.0, 0.0], [1.0, 0.0]);
241        assert!(close(c.point, [9.0, 0.0]) && t == 9.0);
242        let (c, t) = closest_point_on_ray([-5.0, 1.0], [0.0, 0.0], [1.0, 0.0]);
243        assert!(close(c.point, [0.0, 0.0]) && t == 0.0);
244        assert!((distance_point_to_line_3d([0.0, 3.0, 4.0], [0.0; 3], [1.0, 0.0, 0.0]) - 5.0).abs() < 1e-12);
245    }
246
247    #[test]
248    fn plane_box_sphere() {
249        let (c, signed) = closest_point_on_plane([1.0, 2.0, 5.0], [0.0; 3], [0.0, 0.0, 2.0]).unwrap();
250        assert!(close(c.point, [1.0, 2.0, 0.0]) && signed == 5.0 && c.distance == 5.0);
251        assert_eq!(closest_point_on_plane([0.0; 3], [0.0; 3], [0.0; 3]), None);
252        assert!(close(closest_point_on_aabb([5.0, -1.0], [0.0, 0.0], [2.0, 2.0]).point, [2.0, 0.0]));
253        let inside = closest_point_on_aabb([1.0, 1.0], [0.0, 0.0], [2.0, 2.0]);
254        assert!(inside.distance == 0.0);
255        let s = closest_point_on_sphere([3.0, 0.0, 4.0], [0.0; 3], 1.0);
256        assert!(close(s.point, [0.6, 0.0, 0.8]) && (s.distance - 4.0).abs() < 1e-12);
257        assert!(close(closest_point_on_sphere([0.0; 3], [0.0; 3], 2.0).point, [2.0, 0.0, 0.0]));
258    }
259
260    #[test]
261    fn triangle_regions() {
262        let (a, b, c) = ([0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [0.0, 4.0, 0.0]);
263        // Face, vertices, edges (including the hypotenuse), all with consistent barycentrics.
264        for (p, want) in [
265            ([1.0, 1.0, 3.0], [1.0, 1.0, 0.0]),
266            ([-1.0, -1.0, 2.0], a),
267            ([6.0, -1.0, 0.0], b),
268            ([-1.0, 6.0, 0.0], c),
269            ([2.0, -3.0, 1.0], [2.0, 0.0, 0.0]),
270            ([-2.0, 2.0, 0.0], [0.0, 2.0, 0.0]),
271            ([4.0, 4.0, 0.0], [2.0, 2.0, 0.0]),
272        ] {
273            let (cp, bary) = closest_point_on_triangle(p, a, b, c);
274            assert!(close(cp.point, want), "{p:?} -> {:?}", cp.point);
275            let rebuilt = [0, 1, 2].map(|k| bary[0] * a[k] + bary[1] * b[k] + bary[2] * c[k]);
276            assert!(close(rebuilt, want) && (bary.iter().sum::<f64>() - 1.0).abs() < 1e-12);
277        }
278        // Degenerate triangle behaves like its edges.
279        let (cp, _) = closest_point_on_triangle([1.0, 1.0, 0.0], [0.0; 3], [2.0, 0.0, 0.0], [4.0, 0.0, 0.0]);
280        assert!(close(cp.point, [1.0, 0.0, 0.0]));
281    }
282
283    #[test]
284    fn polylines_meshes_and_segment_pairs() {
285        let square = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]];
286        let (c, seg, _) = closest_point_on_polygon_boundary([1.0, 1.9], &square).unwrap();
287        assert!(close(c.point, [1.0, 2.0]) && seg == 2);
288        assert!(closest_point_on_polyline([0.0, 0.0], &[[1.0, 1.0]]).is_none());
289        let verts = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 5.0]];
290        let (c, tri) = closest_point_on_mesh([0.2, 0.2, 4.0], &verts, &[[0, 1, 2], [0, 1, 3]]).unwrap();
291        assert_eq!(tri, 1);
292        assert!(c.distance < 0.21);
293        assert!(closest_point_on_mesh([0.0; 3], &verts, &[[0, 1, 9]]).is_none());
294        // Skew segments: x axis vs a segment above the y axis.
295        let (c1, c2, d) = closest_points_between_segments([-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 2.0], [0.0, 1.0, 2.0]);
296        assert!(close(c1, [0.0, 0.0, 0.0]) && close(c2, [0.0, 0.0, 2.0]) && (d - 2.0).abs() < 1e-12);
297        // Parallel and end-point-limited cases.
298        let (_, _, d) = closest_points_between_segments([0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]);
299        assert!((d - 1.0).abs() < 1e-12);
300        let (_, _, d) = closest_points_between_segments([0.0, 0.0], [1.0, 0.0], [3.0, 4.0], [5.0, 4.0]);
301        assert!((d - (2.0f64.powi(2) + 16.0).sqrt()).abs() < 1e-12);
302        let (_, _, d) = closest_points_between_segments([1.0, 1.0], [1.0, 1.0], [0.0, 1.0], [0.0, 1.0]);
303        assert!((d - 1.0).abs() < 1e-12);
304    }
305}