Skip to main content

lib_jsl_geometry/algorithms/
convex_hull.rs

1//! Convex hulls of point sets in two and three dimensions.
2//!
3//! See the book entry [Convex hulls and polygon booleans](https://jwkunz.github.io/lib_jsl/book/geometry/hulls-booleans.html).
4
5use std::collections::HashMap;
6
7fn cross2(o: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
8    (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
9}
10
11/// The convex hull of 2D points by Andrew's monotone chain, `O(n log n)`.
12///
13/// Returns indices into `points` of the hull vertices in counter-clockwise order, starting from
14/// the lexicographically smallest point. Collinear points on hull edges and duplicate points are
15/// excluded. Fewer than three distinct points, or all-collinear input, yields the extreme points
16/// only (zero, one or two indices).
17pub fn convex_hull_2d(points: &[[f64; 2]]) -> Vec<usize> {
18    let mut order: Vec<usize> = (0..points.len()).filter(|&i| points[i].iter().all(|v| v.is_finite())).collect();
19    order.sort_by(|&a, &b| points[a][0].total_cmp(&points[b][0]).then(points[a][1].total_cmp(&points[b][1])));
20    order.dedup_by(|a, b| points[*a] == points[*b]);
21    if order.len() < 3 {
22        return order;
23    }
24    let chain = |iter: &mut dyn Iterator<Item = usize>| {
25        let mut half: Vec<usize> = Vec::new();
26        for i in iter {
27            while half.len() >= 2 && cross2(points[half[half.len() - 2]], points[half[half.len() - 1]], points[i]) <= 0.0 {
28                half.pop();
29            }
30            half.push(i);
31        }
32        half
33    };
34    let mut lower = chain(&mut order.iter().copied());
35    let mut upper = chain(&mut order.iter().rev().copied());
36    // Each chain ends at the other's starting point, so drop the duplicated last vertex of each.
37    lower.pop();
38    upper.pop();
39    let mut hull = lower;
40    hull.append(&mut upper);
41    hull
42}
43
44/// Area enclosed by a polygon given by `indices` into `points` (shoelace formula; positive for
45/// counter-clockwise order).
46pub fn polygon_area_2d(points: &[[f64; 2]], indices: &[usize]) -> f64 {
47    let n = indices.len();
48    0.5 * (0..n)
49        .map(|k| {
50            let (a, b) = (points[indices[k]], points[indices[(k + 1) % n]]);
51            a[0] * b[1] - a[1] * b[0]
52        })
53        .sum::<f64>()
54}
55
56/// Whether `p` lies inside or on a convex counter-clockwise polygon.
57pub fn convex_polygon_contains_2d(points: &[[f64; 2]], hull: &[usize], p: [f64; 2]) -> bool {
58    let n = hull.len();
59    n >= 3 && (0..n).all(|k| cross2(points[hull[k]], points[hull[(k + 1) % n]], p) >= 0.0)
60}
61
62/// A convex polyhedron: triangular faces indexing into the input points, with counter-clockwise
63/// winding when seen from outside (normals point outward).
64#[derive(Debug, Clone, PartialEq)]
65
66pub struct Hull3D {
67    pub faces: Vec<[usize; 3]>,
68}
69
70fn sub3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
71    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
72}
73fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
74    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
75}
76fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
77    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
78}
79
80impl Hull3D {
81    /// Sorted indices of the points used by the faces: every extreme point, plus any points on a
82    /// face or edge that the construction kept (see [`convex_hull_3d`]).
83    pub fn vertices(&self) -> Vec<usize> {
84        let mut v: Vec<usize> = self.faces.iter().flatten().copied().collect();
85        v.sort_unstable();
86        v.dedup();
87        v
88    }
89
90    /// Enclosed volume.
91    pub fn volume(&self, points: &[[f64; 3]]) -> f64 {
92        let origin = points[self.faces[0][0]];
93        self.faces
94            .iter()
95            .map(|f| {
96                let (a, b, c) = (sub3(points[f[0]], origin), sub3(points[f[1]], origin), sub3(points[f[2]], origin));
97                dot3(a, cross3(b, c)) / 6.0
98            })
99            .sum()
100    }
101
102    /// Total surface area.
103    pub fn surface_area(&self, points: &[[f64; 3]]) -> f64 {
104        self.faces
105            .iter()
106            .map(|f| {
107                let n = cross3(sub3(points[f[1]], points[f[0]]), sub3(points[f[2]], points[f[0]]));
108                0.5 * dot3(n, n).sqrt()
109            })
110            .sum()
111    }
112
113    /// Whether `p` is inside or on the hull, within `tol` of every face plane.
114    pub fn contains(&self, points: &[[f64; 3]], p: [f64; 3], tol: f64) -> bool {
115        self.faces.iter().all(|f| {
116            let n = cross3(sub3(points[f[1]], points[f[0]]), sub3(points[f[2]], points[f[0]]));
117            let len = dot3(n, n).sqrt();
118            dot3(n, sub3(p, points[f[0]])) <= tol * len
119        })
120    }
121}
122
123/// The 3D convex hull by Quickhull (Barber, Dobkin and Huhdanpaa): starting from a tetrahedron,
124/// each face keeps the points outside it, and the point farthest above a face is added by
125/// replacing the faces it sees with a cone to their horizon. `O(n log n)` expected for typical
126/// inputs, `O(n²)` in the worst case.
127///
128/// Returns `None` if there are fewer than four points or they are all coplanar (within a tolerance
129/// relative to the extent of the data) or contain non-finite values. Points strictly inside the
130/// hull and duplicates are never vertices of the result, and nor, usually, are points lying on a
131/// face or edge of the hull (a 5×5×5 grid gives its 8 corners). Such a point can still become a
132/// vertex of coplanar triangles if it is the farthest point above some intermediate face, so
133/// [`Hull3D::vertices`] is guaranteed to contain the extreme points but may, for degenerate
134/// inputs, contain a few more. The volume and surface area are unaffected.
135pub fn convex_hull_3d(points: &[[f64; 3]]) -> Option<Hull3D> {
136    let n = points.len();
137    if n < 4 || points.iter().flatten().any(|v| !v.is_finite()) {
138        return None;
139    }
140    let scale = points.iter().flatten().fold(0.0f64, |m, v| m.max(v.abs())).max(f64::MIN_POSITIVE);
141    let eps = 1e-12 * scale;
142
143    // Initial tetrahedron: extreme points along x, then the farthest from that line, then plane.
144    let i0 = (0..n).min_by(|&a, &b| points[a][0].total_cmp(&points[b][0]))?;
145    let i1 = (0..n).max_by(|&a, &b| dot3(sub3(points[a], points[i0]), sub3(points[a], points[i0])).total_cmp(&dot3(sub3(points[b], points[i0]), sub3(points[b], points[i0]))))?;
146    if dot3(sub3(points[i1], points[i0]), sub3(points[i1], points[i0])).sqrt() <= eps {
147        return None;
148    }
149    let d01 = sub3(points[i1], points[i0]);
150    let line_dist = |i: usize| {
151        let c = cross3(d01, sub3(points[i], points[i0]));
152        dot3(c, c).sqrt() / dot3(d01, d01).sqrt()
153    };
154    let i2 = (0..n).max_by(|&a, &b| line_dist(a).total_cmp(&line_dist(b)))?;
155    if line_dist(i2) <= eps {
156        return None;
157    }
158    let normal = cross3(d01, sub3(points[i2], points[i0]));
159    let nlen = dot3(normal, normal).sqrt();
160    let plane_dist = |i: usize| dot3(normal, sub3(points[i], points[i0])) / nlen;
161    let i3 = (0..n).max_by(|&a, &b| plane_dist(a).abs().total_cmp(&plane_dist(b).abs()))?;
162    if plane_dist(i3).abs() <= eps {
163        return None;
164    }
165
166    // Orient faces outward: the fourth vertex must be on the negative side of every face.
167    let faces: Vec<[usize; 3]> = if plane_dist(i3) > 0.0 {
168        vec![[i0, i2, i1], [i0, i1, i3], [i1, i2, i3], [i2, i0, i3]]
169    } else {
170        vec![[i0, i1, i2], [i0, i3, i1], [i1, i3, i2], [i2, i3, i0]]
171    };
172    // Each face caches its unit normal and offset, and owns the "outside set" of unprocessed
173    // points that see it; a point is in at most one set, and points in none are inside.
174    let plane = |f: &[usize; 3]| {
175        let n = cross3(sub3(points[f[1]], points[f[0]]), sub3(points[f[2]], points[f[0]]));
176        let len = dot3(n, n).sqrt();
177        let n = [n[0] / len, n[1] / len, n[2] / len];
178        (n, dot3(n, points[f[0]]))
179    };
180    struct Face {
181        vertices: [usize; 3],
182        normal: [f64; 3],
183        offset: f64,
184        outside: Vec<usize>,
185        alive: bool,
186    }
187    let height = |f: &Face, p: usize| dot3(f.normal, points[p]) - f.offset;
188    let mut slots: Vec<Face> = faces.iter().map(|f| { let (normal, offset) = plane(f); Face { vertices: *f, normal, offset, outside: Vec::new(), alive: true } }).collect();
189    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
190    for (k, f) in slots.iter().enumerate() {
191        for j in 0..3 {
192            owner.insert((f.vertices[j], f.vertices[(j + 1) % 3]), k);
193        }
194    }
195    for p in (0..n).filter(|p| ![i0, i1, i2, i3].contains(p)) {
196        if let Some(k) = (0..4).find(|&k| height(&slots[k], p) > eps) {
197            slots[k].outside.push(p);
198        }
199    }
200    let mut pending: Vec<usize> = (0..4).collect();
201    while let Some(k) = pending.pop() {
202        if !slots[k].alive || slots[k].outside.is_empty() {
203            continue;
204        }
205        // ANCHOR: quickhull
206        // Quickhull: add the point farthest above this face, which is certainly a hull vertex.
207        let apex = *slots[k].outside.iter().max_by(|&&a, &&b| height(&slots[k], a).total_cmp(&height(&slots[k], b))).unwrap();
208        // The faces it sees form a connected cap around face k: find them across shared edges.
209        let mut visible = vec![k];
210        let mut seen = std::collections::HashSet::from([k]);
211        let mut horizon: Vec<(usize, usize)> = Vec::new();
212        let mut i = 0;
213        while i < visible.len() {
214            let f = slots[visible[i]].vertices;
215            for j in 0..3 {
216                let (a, b) = (f[j], f[(j + 1) % 3]);
217                let across = owner[&(b, a)];
218                if seen.contains(&across) {
219                    continue;
220                }
221                if height(&slots[across], apex) > eps {
222                    seen.insert(across);
223                    visible.push(across);
224                } else {
225                    horizon.push((a, b));
226                }
227            }
228            i += 1;
229        }
230        // Remove the cap, keeping its outside points to hand on to the new faces.
231        let mut orphans = Vec::new();
232        for &v in &visible {
233            let f = &mut slots[v];
234            f.alive = false;
235            orphans.append(&mut f.outside);
236            for j in 0..3 {
237                owner.remove(&(f.vertices[j], f.vertices[(j + 1) % 3]));
238            }
239        }
240        // Cone the horizon to the apex, skipping any edge that rounding has left inconsistent
241        // (its face across was removed after all).
242        let first_new = slots.len();
243        for (a, b) in horizon {
244            if owner.contains_key(&(a, b)) || !owner.contains_key(&(b, a)) {
245                continue;
246            }
247            let vertices = [a, b, apex];
248            let (normal, offset) = plane(&vertices);
249            for j in 0..3 {
250                owner.insert((vertices[j], vertices[(j + 1) % 3]), slots.len());
251            }
252            slots.push(Face { vertices, normal, offset, outside: Vec::new(), alive: true });
253        }
254        for p in orphans.into_iter().filter(|&p| p != apex) {
255            if let Some(f) = (first_new..slots.len()).find(|&f| height(&slots[f], p) > eps) {
256                slots[f].outside.push(p);
257            }
258        }
259        pending.extend(first_new..slots.len());
260        // ANCHOR_END: quickhull
261    }
262    let faces: Vec<[usize; 3]> = slots.into_iter().filter(|f| f.alive).map(|f| f.vertices).collect();
263    Some(Hull3D { faces })
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn square_with_interior_collinear_and_duplicate_points() {
272        let pts = [[0.0, 0.0], [2.0, 0.0], [1.0, 0.0], [2.0, 2.0], [0.0, 2.0], [1.0, 1.0], [0.0, 0.0], [2.0, 1.0]];
273        let hull = convex_hull_2d(&pts);
274        assert_eq!(hull.len(), 4);
275        let corners: Vec<[f64; 2]> = hull.iter().map(|&i| pts[i]).collect();
276        assert_eq!(corners, vec![[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]); // CCW from the smallest point
277        assert!((polygon_area_2d(&pts, &hull) - 4.0).abs() < 1e-12);
278        assert!(convex_polygon_contains_2d(&pts, &hull, [1.0, 1.9]));
279        assert!(convex_polygon_contains_2d(&pts, &hull, [2.0, 2.0]));
280        assert!(!convex_polygon_contains_2d(&pts, &hull, [2.1, 1.0]));
281    }
282
283    #[test]
284    fn degenerate_2d_inputs() {
285        assert!(convex_hull_2d(&[]).is_empty());
286        assert_eq!(convex_hull_2d(&[[1.0, 1.0], [1.0, 1.0]]).len(), 1);
287        assert_eq!(convex_hull_2d(&[[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]).len(), 2);
288        assert_eq!(convex_hull_2d(&[[0.0, 0.0], [f64::NAN, 1.0], [1.0, 0.0], [0.0, 1.0]]).len(), 3);
289    }
290
291    #[test]
292    fn random_2d_hull_contains_everything_and_is_convex() {
293        let mut s = 12345u64;
294        let mut rnd = || {
295            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
296            (s >> 11) as f64 / (1u64 << 53) as f64
297        };
298        let pts: Vec<[f64; 2]> = (0..500).map(|_| [rnd() * 10.0 - 5.0, rnd() * 10.0 - 5.0]).collect();
299        let hull = convex_hull_2d(&pts);
300        assert!(pts.iter().all(|&p| convex_polygon_contains_2d(&pts, &hull, p)));
301        let n = hull.len();
302        assert!((0..n).all(|k| cross2(pts[hull[k]], pts[hull[(k + 1) % n]], pts[hull[(k + 2) % n]]) > 0.0));
303        assert!(polygon_area_2d(&pts, &hull) > 0.0);
304    }
305
306    fn cube_corners() -> Vec<[f64; 3]> {
307        (0..8).map(|i| [(i & 1) as f64, ((i >> 1) & 1) as f64, ((i >> 2) & 1) as f64]).collect()
308    }
309
310    #[test]
311    fn cube_hull_has_unit_volume_and_closed_surface() {
312        let mut pts = cube_corners();
313        pts.extend([[0.5, 0.5, 0.5], [0.2, 0.7, 0.4], [0.5, 0.5, 0.0], [0.0, 0.0, 0.0]]); // interior, on a face, duplicate
314        let hull = convex_hull_3d(&pts).unwrap();
315        assert_eq!(hull.vertices(), (0..8).collect::<Vec<_>>());
316        assert!((hull.volume(&pts) - 1.0).abs() < 1e-12);
317        assert!((hull.surface_area(&pts) - 6.0).abs() < 1e-12);
318        // Closed manifold: every directed edge has exactly one opposite partner.
319        let mut count: HashMap<(usize, usize), i32> = HashMap::new();
320        for f in &hull.faces {
321            for k in 0..3 {
322                *count.entry((f[k], f[(k + 1) % 3])).or_default() += 1;
323            }
324        }
325        assert!(count.iter().all(|(&(a, b), &c)| c == 1 && count.get(&(b, a)) == Some(&1)));
326        assert!(hull.contains(&pts, [0.9, 0.1, 0.5], 1e-12) && !hull.contains(&pts, [1.1, 0.5, 0.5], 1e-12));
327    }
328
329    #[test]
330    fn sphere_samples_form_a_valid_hull() {
331        let mut s = 99u64;
332        let mut rnd = || {
333            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
334            (s >> 11) as f64 / (1u64 << 53) as f64
335        };
336        let pts: Vec<[f64; 3]> = (0..300)
337            .map(|_| {
338                let (z, t) = (2.0 * rnd() - 1.0, 2.0 * std::f64::consts::PI * rnd());
339                let r = (1.0 - z * z).sqrt();
340                [r * t.cos(), r * t.sin(), z]
341            })
342            .collect();
343        let hull = convex_hull_3d(&pts).unwrap();
344        assert!(pts.iter().all(|&p| hull.contains(&pts, p, 1e-9)));
345        let (v, f) = (hull.vertices().len() as i64, hull.faces.len() as i64);
346        assert_eq!(v - 3 * f / 2 + f, 2, "Euler characteristic");
347        assert!(hull.volume(&pts) > 0.0 && hull.volume(&pts) < 4.18879);
348        assert!(hull.volume(&pts) > 3.9, "volume {}", hull.volume(&pts));
349    }
350
351    #[test]
352    fn grid_hull_keeps_its_volume_and_all_corners() {
353        let grid: Vec<[f64; 3]> = (0..125).map(|i| [(i % 5) as f64, ((i / 5) % 5) as f64, (i / 25) as f64]).collect();
354        let hull = convex_hull_3d(&grid).unwrap();
355        assert!((hull.volume(&grid) - 64.0).abs() < 1e-12);
356        assert!((hull.surface_area(&grid) - 96.0).abs() < 1e-12);
357        let vertices = hull.vertices();
358        let corners = (0..125).filter(|&i| grid[i].iter().all(|&v| v == 0.0 || v == 4.0));
359        assert!(corners.into_iter().all(|c| vertices.contains(&c)));
360        // Points interior to the cube are never vertices, and Quickhull keeps only the corners.
361        assert!(vertices.iter().all(|&i| grid[i].iter().any(|&v| v == 0.0 || v == 4.0)));
362        assert_eq!(vertices.len(), 8);
363    }
364
365    #[test]
366    fn degenerate_3d_inputs_return_none() {
367        assert!(convex_hull_3d(&[[0.0; 3]; 3]).is_none());
368        let planar: Vec<[f64; 3]> = (0..10).map(|i| [i as f64, (i * i) as f64 % 7.0, 0.0]).collect();
369        assert!(convex_hull_3d(&planar).is_none());
370        let line: Vec<[f64; 3]> = (0..10).map(|i| [i as f64, 2.0 * i as f64, 3.0 * i as f64]).collect();
371        assert!(convex_hull_3d(&line).is_none());
372        assert!(convex_hull_3d(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [f64::NAN, 0.0, 1.0]]).is_none());
373    }
374}