Skip to main content

lib_jsl_geometry/algorithms/
delaunay_triangulation.rs

1//! Delaunay triangulation of 2D point sets.
2//!
3//! See the book entry [Delaunay triangulations and Voronoi diagrams](https://jwkunz.github.io/lib_jsl/book/geometry/delaunay-voronoi.html#delaunay-triangulation).
4
5use std::collections::{HashMap, HashSet};
6
7fn orient(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> f64 {
8    (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
9}
10
11/// Positive if `d` is strictly inside the circumcircle of the counter-clockwise triangle `abc`.
12fn in_circle(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> f64 {
13    let (ax, ay, bx, by, cx, cy) = (a[0] - d[0], a[1] - d[1], b[0] - d[0], b[1] - d[1], c[0] - d[0], c[1] - d[1]);
14    (ax * ax + ay * ay) * (bx * cy - cx * by) - (bx * bx + by * by) * (ax * cy - cx * ay) + (cx * cx + cy * cy) * (ax * by - bx * ay)
15}
16
17/// A Delaunay triangulation: triangles (indices into the input points, counter-clockwise) such that
18/// no input point lies inside any triangle's circumcircle. Together the triangles tile the convex
19/// hull of the points.
20#[derive(Debug, Clone, PartialEq)]
21
22pub struct Triangulation {
23    pub triangles: Vec<[usize; 3]>,
24}
25
26/// Orientation with a rounding-error bound: the determinant and the sum of its terms' magnitudes.
27fn orient_bound(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> (f64, f64) {
28    let (l, r) = ((b[0] - a[0]) * (c[1] - a[1]), (b[1] - a[1]) * (c[0] - a[0]));
29    (l - r, l.abs() + r.abs())
30}
31
32/// The in-circle determinant and the sum of its terms' magnitudes (its rounding-error scale).
33fn in_circle_bound(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> (f64, f64) {
34    let (ax, ay, bx, by, cx, cy) = (a[0] - d[0], a[1] - d[1], b[0] - d[0], b[1] - d[1], c[0] - d[0], c[1] - d[1]);
35    let (a2, b2, c2) = (ax * ax + ay * ay, bx * bx + by * by, cx * cx + cy * cy);
36    let det = in_circle(a, b, c, d);
37    let scale = a2 * ((bx * cy).abs() + (cx * by).abs()) + b2 * ((ax * cy).abs() + (cx * ay).abs()) + c2 * ((ax * by).abs() + (bx * ay).abs());
38    (det, scale)
39}
40
41/// Relative slack for the predicates: determinants smaller than this times their term scale are
42/// treated as zero (collinear or cocircular), which keeps rounding from creating slivers or
43/// flipping an edge back and forth.
44const EPS: f64 = 1e-12;
45
46/// Triangulates `points` by a sweep with Lawson flips (`O(n log n)` typical): points are inserted
47/// in lexicographic order, so each lies outside the triangulation so far and is joined to the hull
48/// edges it can see; every new edge is then checked against the empty-circle test and flipped
49/// until the triangulation is Delaunay again.
50///
51/// Duplicate points are ignored (they appear in no triangle). Returns `None` for fewer than three
52/// distinct finite points or when all points are collinear. Points cocircular to rounding are
53/// triangulated in either valid way.
54pub fn delaunay_triangulation(points: &[[f64; 2]]) -> Option<Triangulation> {
55    let mut seen: HashSet<(u64, u64)> = HashSet::new();
56    let mut ids: Vec<usize> = (0..points.len())
57        .filter(|&i| points[i].iter().all(|v| v.is_finite()) && seen.insert(((points[i][0] + 0.0).to_bits(), (points[i][1] + 0.0).to_bits())))
58        .collect();
59    if ids.len() < 3 {
60        return None;
61    }
62    // Work in coordinates normalised to a unit box for well-conditioned predicates.
63    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
64    for &i in &ids {
65        for k in 0..2 {
66            lo[k] = lo[k].min(points[i][k]);
67            hi[k] = hi[k].max(points[i][k]);
68        }
69    }
70    let span = (hi[0] - lo[0]).max(hi[1] - lo[1]);
71    ids.sort_by(|&i, &j| points[i][0].total_cmp(&points[j][0]).then(points[i][1].total_cmp(&points[j][1])));
72    let p: Vec<[f64; 2]> = ids.iter().map(|&i| [(points[i][0] - lo[0]) / span, (points[i][1] - lo[1]) / span]).collect();
73    let n = p.len();
74    let left = |a: usize, b: usize, c: usize| {
75        let (d, s) = orient_bound(p[a], p[b], p[c]);
76        if d > EPS * s { 1 } else if d < -EPS * s { -1 } else { 0 }
77    };
78
79    // The first points may be collinear; the first point off their line closes a fan over them.
80    let mut k = 2;
81    while k < n && left(0, 1, k) == 0 {
82        k += 1;
83    }
84    if k == n {
85        return None;
86    }
87    let mut tris: Vec<[usize; 3]> = Vec::with_capacity(2 * n);
88    let mut edge: HashMap<(usize, usize), usize> = HashMap::with_capacity(6 * n);
89    let add = |tris: &mut Vec<[usize; 3]>, edge: &mut HashMap<(usize, usize), usize>, t: [usize; 3]| {
90        for j in 0..3 {
91            edge.insert((t[j], t[(j + 1) % 3]), tris.len());
92        }
93        tris.push(t);
94    };
95    // The hull is a counter-clockwise cycle of vertices.
96    let (mut next, mut prev) = (vec![usize::MAX; n], vec![usize::MAX; n]);
97    let side = left(0, 1, k);
98    let mut cycle: Vec<usize> = Vec::with_capacity(k + 1);
99    for j in 0..k - 1 {
100        add(&mut tris, &mut edge, if side > 0 { [j, j + 1, k] } else { [j + 1, j, k] });
101    }
102    if side > 0 {
103        cycle.extend(0..=k);
104    } else {
105        cycle.push(0);
106        cycle.push(k);
107        cycle.extend((1..k).rev());
108    }
109    for j in 0..cycle.len() {
110        next[cycle[j]] = cycle[(j + 1) % cycle.len()];
111        prev[cycle[(j + 1) % cycle.len()]] = cycle[j];
112    }
113
114    let mut stack: Vec<(usize, usize)> = Vec::new();
115    let mut last = k;
116    for i in k + 1..n {
117        // Find a hull edge a -> next[a] that sees p_i (p_i to its right), near the last insertion.
118        let sees = |a: usize, next: &[usize]| left(a, next[a], i) < 0;
119        let start = if sees(last, &next) {
120            Some(last)
121        } else if sees(prev[last], &next) {
122            Some(prev[last])
123        } else {
124            let mut a = next[last];
125            loop {
126                if sees(a, &next) {
127                    break Some(a);
128                }
129                if a == last {
130                    break None;
131                }
132                a = next[a];
133            }
134        };
135        let Some(start) = start else { continue };
136        // Extend to the whole visible chain first..=end (edges first -> ... -> end -> next[end]).
137        let (mut first, mut end) = (start, start);
138        while prev[first] != end && sees(prev[first], &next) {
139            first = prev[first];
140        }
141        while next[end] != first && sees(next[end], &next) {
142            end = next[end];
143        }
144        let mut a = first;
145        loop {
146            let b = next[a];
147            add(&mut tris, &mut edge, [b, a, i]);
148            stack.push((b, a));
149            if a == end {
150                break;
151            }
152            a = b;
153        }
154        let after = next[end];
155        next[first] = i;
156        prev[i] = first;
157        next[i] = after;
158        prev[after] = i;
159        last = i;
160
161        // ANCHOR: lawson
162        // Lawson flips: edge (a, b) of triangle (a, b, c) is illegal if the triangle (b, a, d)
163        // across it has d inside the circle through a, b, c.
164        while let Some((a, b)) = stack.pop() {
165            let (Some(&t), Some(&u)) = (edge.get(&(a, b)), edge.get(&(b, a))) else { continue };
166            let c = tris[t].into_iter().find(|&v| v != a && v != b).unwrap();
167            let d = tris[u].into_iter().find(|&v| v != a && v != b).unwrap();
168            let (det, scale) = in_circle_bound(p[a], p[b], p[c], p[d]);
169            if det <= EPS * scale || left(c, a, d) <= 0 || left(c, d, b) <= 0 {
170                continue;
171            }
172            edge.remove(&(a, b));
173            edge.remove(&(b, a));
174            tris[t] = [c, a, d];
175            tris[u] = [c, d, b];
176            for (x, y, tri) in [(c, a, t), (a, d, t), (d, c, t), (c, d, u), (d, b, u), (b, c, u)] {
177                edge.insert((x, y), tri);
178            }
179            stack.push((a, d));
180            stack.push((d, b));
181        }
182        // ANCHOR_END: lawson
183    }
184    let triangles = tris.into_iter().map(|t| [ids[t[0]], ids[t[1]], ids[t[2]]]).collect();
185    Some(Triangulation { triangles })
186}
187
188impl Triangulation {
189    /// The unique undirected edges as `(low, high)` index pairs, sorted.
190    pub fn edges(&self) -> Vec<(usize, usize)> {
191        let mut e: Vec<(usize, usize)> = self
192            .triangles
193            .iter()
194            .flat_map(|t| (0..3).map(move |k| (t[k].min(t[(k + 1) % 3]), t[k].max(t[(k + 1) % 3]))))
195            .collect();
196        e.sort_unstable();
197        e.dedup();
198        e
199    }
200
201    /// Index of a triangle containing `p` (boundary inclusive), if any.
202    pub fn locate(&self, points: &[[f64; 2]], p: [f64; 2]) -> Option<usize> {
203        self.triangles.iter().position(|t| (0..3).all(|k| orient(points[t[k]], points[t[(k + 1) % 3]], p) >= 0.0))
204    }
205
206    /// Circumcentre of triangle `t`.
207    pub fn circumcenter(&self, points: &[[f64; 2]], t: usize) -> [f64; 2] {
208        let [a, b, c] = self.triangles[t].map(|i| points[i]);
209        let d = 2.0 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]));
210        let (a2, b2, c2) = (a[0] * a[0] + a[1] * a[1], b[0] * b[0] + b[1] * b[1], c[0] * c[0] + c[1] * c[1]);
211        [(a2 * (b[1] - c[1]) + b2 * (c[1] - a[1]) + c2 * (a[1] - b[1])) / d, (a2 * (c[0] - b[0]) + b2 * (a[0] - c[0]) + c2 * (b[0] - a[0])) / d]
212    }
213
214    /// Total area of all triangles (equals the convex hull's area).
215    pub fn area(&self, points: &[[f64; 2]]) -> f64 {
216        self.triangles.iter().map(|t| 0.5 * orient(points[t[0]], points[t[1]], points[t[2]])).sum()
217    }
218
219    /// Checks the empty-circumcircle property against every input point (`O(n·t)`, for testing),
220    /// allowing `tol` relative slack for points that are cocircular to rounding.
221    pub fn is_delaunay(&self, points: &[[f64; 2]], tol: f64) -> bool {
222        self.triangles.iter().all(|t| {
223            let [a, b, c] = t.map(|i| points[i]);
224            let scale = orient(a, b, c).abs().max(f64::MIN_POSITIVE);
225            points.iter().enumerate().filter(|(i, _)| !t.contains(i)).all(|(_, &q)| in_circle(a, b, c, q) <= tol * scale)
226        })
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use crate::algorithms::convex_hull::{convex_hull_2d, polygon_area_2d};
234
235    fn lcg(seed: u64) -> impl FnMut() -> f64 {
236        let mut s = seed;
237        move || {
238            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
239            (s >> 11) as f64 / (1u64 << 53) as f64
240        }
241    }
242
243    #[test]
244    fn square_with_centre_gives_four_triangles() {
245        let pts = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [1.0, 1.0]];
246        let t = delaunay_triangulation(&pts).unwrap();
247        assert_eq!(t.triangles.len(), 4);
248        assert!((t.area(&pts) - 4.0).abs() < 1e-12);
249        assert_eq!(t.edges().len(), 8);
250        assert!(t.is_delaunay(&pts, 1e-9));
251        let c = t.circumcenter(&pts, 0);
252        assert!(c.iter().all(|v| v.is_finite()));
253    }
254
255    #[test]
256    fn random_points_tile_the_hull_and_satisfy_the_delaunay_property() {
257        let mut rnd = lcg(7);
258        let pts: Vec<[f64; 2]> = (0..200).map(|_| [rnd() * 100.0, rnd() * 50.0 - 25.0]).collect();
259        let t = delaunay_triangulation(&pts).unwrap();
260        assert!(t.is_delaunay(&pts, 1e-9));
261        let hull = convex_hull_2d(&pts);
262        let hull_area = polygon_area_2d(&pts, &hull);
263        assert!((t.area(&pts) - hull_area).abs() < 1e-6 * hull_area, "{} vs {}", t.area(&pts), hull_area);
264        assert!(t.triangles.iter().all(|tr| orient(pts[tr[0]], pts[tr[1]], pts[tr[2]]) > 0.0));
265        // Euler: for n points with h on the hull, triangles = 2n - h - 2.
266        assert_eq!(t.triangles.len(), 2 * pts.len() - hull.len() - 2);
267        assert!(t.locate(&pts, [50.0, 0.0]).is_some());
268        assert!(t.locate(&pts, [500.0, 0.0]).is_none());
269    }
270
271    #[test]
272    fn grid_with_cocircular_points_and_duplicates() {
273        let mut pts: Vec<[f64; 2]> = (0..6).flat_map(|i| (0..6).map(move |j| [i as f64, j as f64])).collect();
274        pts.push([2.0, 2.0]); // duplicate
275        let t = delaunay_triangulation(&pts).unwrap();
276        assert_eq!(t.triangles.len(), 2 * 25);
277        assert!((t.area(&pts) - 25.0).abs() < 1e-9);
278        assert!(t.triangles.iter().flatten().all(|&i| i != 36));
279        assert!(t.is_delaunay(&pts, 1e-9));
280    }
281
282    fn assert_tiles_hull(pts: &[[f64; 2]]) {
283        let t = delaunay_triangulation(pts).unwrap();
284        let hull = convex_hull_2d(pts);
285        let hull_area = polygon_area_2d(pts, &hull);
286        assert!((t.area(pts) - hull_area).abs() < 1e-9 * hull_area, "{} vs {}", t.area(pts), hull_area);
287        assert!(t.triangles.iter().all(|tr| orient(pts[tr[0]], pts[tr[1]], pts[tr[2]]) > 0.0));
288        assert!(t.is_delaunay(pts, 1e-9));
289    }
290
291    #[test]
292    fn nearly_cocircular_points_do_not_overlap() {
293        // Forty points on a shallow arc and one near its centre: almost every quadruple is
294        // cocircular, which made the earlier Bowyer-Watson version produce overlapping triangles.
295        let mut pts: Vec<[f64; 2]> = (0..40)
296            .map(|i| {
297                let t = -0.3 + 0.6 * i as f64 / 39.0;
298                [10.0 * f64::sin(t), 10.0 * f64::cos(t) - 9.0]
299            })
300            .collect();
301        pts.push([0.0, 0.0]);
302        assert_tiles_hull(&pts);
303        let circle: Vec<[f64; 2]> = (0..100).map(|i| [f64::cos(i as f64 * 0.0628), f64::sin(i as f64 * 0.0628)]).collect();
304        assert_tiles_hull(&circle);
305    }
306
307    #[test]
308    fn thin_point_sets_keep_their_hull_triangles() {
309        // Points close to a line: a finite super-triangle used to cut off the hull's sliver triangles.
310        let mut rnd = lcg(3);
311        let pts: Vec<[f64; 2]> = (0..100)
312            .map(|i| {
313                let x = i as f64 / 99.0;
314                [x, 1e-3 * x * (1.0 - x) + 1e-4 * rnd()]
315            })
316            .collect();
317        assert_tiles_hull(&pts);
318        let mut fan: Vec<[f64; 2]> = (0..10).map(|i| [0.0, i as f64]).collect();
319        fan.push([-1.0, 3.0]);
320        assert_tiles_hull(&fan);
321    }
322
323    #[test]
324    fn degenerate_inputs() {
325        assert!(delaunay_triangulation(&[]).is_none());
326        assert!(delaunay_triangulation(&[[0.0, 0.0], [1.0, 1.0]]).is_none());
327        assert!(delaunay_triangulation(&[[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]).is_none());
328        assert!(delaunay_triangulation(&[[1.0, 1.0]; 5]).is_none());
329        assert_eq!(delaunay_triangulation(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]).unwrap().triangles.len(), 1);
330    }
331}