hypergraph_rs/layout/hull.rs
1//! Convex hull via Andrew's monotone chain (replaces XGI's scipy ConvexHull).
2
3/// Compute the convex hull of a set of 2D points. Returns the hull vertices in
4/// counter-clockwise order, with collinear points removed. For 0, 1, or 2
5/// unique points the "hull" is those points themselves (a point or a segment);
6/// callers render degenerate hulls specially.
7///
8/// Deterministic: the input is sorted by (x, then y) before construction.
9pub fn convex_hull(points: &[(f64, f64)]) -> Vec<(f64, f64)> {
10 let mut pts: Vec<(f64, f64)> = points.to_vec();
11 // Deterministic total order on finite f64 (positions are always finite);
12 // NaN would compare Equal, which is acceptable for layout coordinates.
13 pts.sort_by(|a, b| {
14 a.0.partial_cmp(&b.0)
15 .unwrap_or(std::cmp::Ordering::Equal)
16 .then(a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
17 });
18 pts.dedup(); // exact duplicates are now adjacent after the sort
19 let n = pts.len();
20 if n <= 2 {
21 return pts;
22 }
23
24 // 2D cross product of (a-o) x (b-o).
25 fn cross(o: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
26 (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0)
27 }
28
29 let mut hull: Vec<(f64, f64)> = Vec::with_capacity(2 * n);
30 // Lower hull. The inner `while` is bounded: each pop strictly shrinks
31 // `hull`, and total pops across the whole build are <= total pushes (2n).
32 for &p in pts.iter() {
33 while hull.len() >= 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
34 hull.pop();
35 }
36 hull.push(p);
37 }
38 // Upper hull.
39 let lower_len = hull.len() + 1;
40 for &p in pts.iter().rev() {
41 while hull.len() >= lower_len && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0
42 {
43 hull.pop();
44 }
45 hull.push(p);
46 }
47 hull.pop(); // the last point duplicates the first point of the lower hull
48 hull
49}