brepkit-math 3.2.9

Vector math, transforms, NURBS, and geometric predicates for brepkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! 3D convex hull via incremental Quickhull algorithm.
//!
//! Builds a convex polyhedron from a point cloud. Returns indexed triangle
//! faces suitable for conversion to B-Rep topology.
//!
//! # Algorithm
//!
//! 1. Find an initial tetrahedron from 4 non-coplanar points.
//! 2. For each remaining point, find visible faces (point is above the face plane).
//! 3. Remove visible faces, leaving a horizon ridge.
//! 4. Connect the new point to each horizon edge to form new faces.
//! 5. Repeat until no points remain above any face.
//!
//! # References
//!
//! Barber, Dobkin, Huhdanpaa — "The Quickhull Algorithm for Convex Hulls" (1996)

use crate::vec::{Point3, Vec3};

/// A convex hull result: vertices and triangular faces (CCW winding).
#[derive(Debug, Clone)]
pub struct ConvexHull {
    /// Vertex positions.
    pub vertices: Vec<Point3>,
    /// Triangle faces as index triples (indices into `vertices`).
    pub faces: Vec<[usize; 3]>,
}

/// Compute the 3D convex hull of a point cloud.
///
/// # Errors
///
/// Returns `None` if fewer than 4 non-coplanar points are provided.
#[must_use]
pub fn convex_hull_3d(points: &[Point3]) -> Option<ConvexHull> {
    if points.len() < 4 {
        return None;
    }

    let tol = 1e-10;
    let mut pts: Vec<Point3> = Vec::with_capacity(points.len());
    for &p in points {
        let dominated = pts.iter().any(|q| (*q - p).length() < tol);
        if !dominated {
            pts.push(p);
        }
    }
    if pts.len() < 4 {
        return None;
    }

    let tet = find_initial_tetrahedron(&pts)?;

    let mut faces: Vec<HullFace> = Vec::new();
    let tet_faces = [
        [tet[0], tet[1], tet[2]],
        [tet[0], tet[2], tet[3]],
        [tet[0], tet[3], tet[1]],
        [tet[1], tet[3], tet[2]],
    ];

    for &[a, b, c] in &tet_faces {
        let normal = face_normal(&pts, a, b, c);
        let d = -(normal.x() * pts[a].x() + normal.y() * pts[a].y() + normal.z() * pts[a].z());
        faces.push(HullFace {
            verts: [a, b, c],
            normal,
            d,
            alive: true,
        });
    }

    // Ensure all faces point outward (centroid test).
    let centroid = Point3::new(
        (pts[tet[0]].x() + pts[tet[1]].x() + pts[tet[2]].x() + pts[tet[3]].x()) / 4.0,
        (pts[tet[0]].y() + pts[tet[1]].y() + pts[tet[2]].y() + pts[tet[3]].y()) / 4.0,
        (pts[tet[0]].z() + pts[tet[1]].z() + pts[tet[2]].z() + pts[tet[3]].z()) / 4.0,
    );
    for face in &mut faces {
        let signed = signed_distance(face, centroid);
        if signed > 0.0 {
            // Normal points inward — flip.
            face.normal = -face.normal;
            face.d = -face.d;
            face.verts.swap(1, 2);
        }
    }

    let tet_set: std::collections::HashSet<usize> = tet.iter().copied().collect();

    for (pi, &point) in pts.iter().enumerate() {
        if tet_set.contains(&pi) {
            continue;
        }

        let mut visible: Vec<usize> = Vec::new();
        for (fi, face) in faces.iter().enumerate() {
            if face.alive && signed_distance(face, point) > tol {
                visible.push(fi);
            }
        }

        if visible.is_empty() {
            continue; // Point is inside the hull.
        }

        // Horizon edges are shared by exactly one visible face.
        let mut horizon: Vec<[usize; 2]> = Vec::new();
        for &fi in &visible {
            let f = &faces[fi];
            for edge_idx in 0..3 {
                let e = [f.verts[edge_idx], f.verts[(edge_idx + 1) % 3]];
                // Check if the opposite face (sharing reversed edge) is NOT visible.
                let twin_visible = visible
                    .iter()
                    .any(|&fj| fj != fi && faces[fj].has_edge(e[1], e[0]));
                if !twin_visible {
                    horizon.push(e);
                }
            }
        }

        for &fi in &visible {
            faces[fi].alive = false;
        }

        for &[a, b] in &horizon {
            let normal = face_normal(&pts, a, b, pi);
            let d = -(normal.x() * pts[a].x() + normal.y() * pts[a].y() + normal.z() * pts[a].z());
            let mut new_face = HullFace {
                verts: [a, b, pi],
                normal,
                d,
                alive: true,
            };
            // Ensure outward orientation.
            if signed_distance(&new_face, centroid) > 0.0 {
                new_face.normal = Vec3::new(
                    -new_face.normal.x(),
                    -new_face.normal.y(),
                    -new_face.normal.z(),
                );
                new_face.d = -new_face.d;
                new_face.verts.swap(0, 1);
            }
            faces.push(new_face);
        }
    }

    let alive_faces: Vec<[usize; 3]> = faces.iter().filter(|f| f.alive).map(|f| f.verts).collect();

    if alive_faces.is_empty() {
        return None;
    }

    Some(ConvexHull {
        vertices: pts,
        faces: alive_faces,
    })
}

// ---------------------------------------------------------------------------
// Internal types
// ---------------------------------------------------------------------------

struct HullFace {
    verts: [usize; 3],
    normal: Vec3,
    d: f64,
    alive: bool,
}

impl HullFace {
    fn has_edge(&self, a: usize, b: usize) -> bool {
        for i in 0..3 {
            if self.verts[i] == a && self.verts[(i + 1) % 3] == b {
                return true;
            }
        }
        false
    }
}

fn signed_distance(face: &HullFace, point: Point3) -> f64 {
    face.normal.x() * point.x() + face.normal.y() * point.y() + face.normal.z() * point.z() + face.d
}

fn face_normal(pts: &[Point3], a: usize, b: usize, c: usize) -> Vec3 {
    let ab = pts[b] - pts[a];
    let ac = pts[c] - pts[a];
    let n = ab.cross(ac);
    let len = n.length();
    if len < 1e-15 {
        Vec3::new(0.0, 0.0, 1.0)
    } else {
        Vec3::new(n.x() / len, n.y() / len, n.z() / len)
    }
}

/// Find 4 non-coplanar points for the initial tetrahedron.
fn find_initial_tetrahedron(pts: &[Point3]) -> Option<[usize; 4]> {
    let n = pts.len();

    // Find two points that are farthest apart.
    let mut i0 = 0;
    let mut i1 = 1;
    let mut max_dist = 0.0_f64;
    for i in 0..n {
        for j in (i + 1)..n {
            let d = (pts[j] - pts[i]).length();
            if d > max_dist {
                max_dist = d;
                i0 = i;
                i1 = j;
            }
        }
    }
    if max_dist < 1e-12 {
        return None;
    }

    // Find a third point farthest from the line i0-i1.
    let dir = pts[i1] - pts[i0];
    let dir_len = dir.length();
    let dir_n = Vec3::new(dir.x() / dir_len, dir.y() / dir_len, dir.z() / dir_len);
    let mut i2 = 0;
    let mut max_dist2 = 0.0_f64;
    for i in 0..n {
        if i == i0 || i == i1 {
            continue;
        }
        let v = pts[i] - pts[i0];
        let proj = v.x() * dir_n.x() + v.y() * dir_n.y() + v.z() * dir_n.z();
        let perp = Vec3::new(
            v.x() - proj * dir_n.x(),
            v.y() - proj * dir_n.y(),
            v.z() - proj * dir_n.z(),
        );
        let d = perp.length();
        if d > max_dist2 {
            max_dist2 = d;
            i2 = i;
        }
    }
    if max_dist2 < 1e-12 {
        return None;
    }

    // Find a fourth point farthest from the plane i0-i1-i2.
    let plane_n = face_normal(pts, i0, i1, i2);
    let plane_d =
        -(plane_n.x() * pts[i0].x() + plane_n.y() * pts[i0].y() + plane_n.z() * pts[i0].z());
    let mut i3 = 0;
    let mut max_dist3 = 0.0_f64;
    for i in 0..n {
        if i == i0 || i == i1 || i == i2 {
            continue;
        }
        let d = (plane_n.x() * pts[i].x()
            + plane_n.y() * pts[i].y()
            + plane_n.z() * pts[i].z()
            + plane_d)
            .abs();
        if d > max_dist3 {
            max_dist3 = d;
            i3 = i;
        }
    }
    if max_dist3 < 1e-12 {
        return None;
    }

    Some([i0, i1, i2, i3])
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]
    use super::*;

    #[test]
    fn hull_of_cube_vertices() {
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 0.0),
            Point3::new(0.0, 0.0, 1.0),
            Point3::new(1.0, 0.0, 1.0),
            Point3::new(0.0, 1.0, 1.0),
            Point3::new(1.0, 1.0, 1.0),
        ];
        let hull = convex_hull_3d(&points).expect("hull should succeed");
        // Cube has 8 vertices and 12 triangular faces (6 quads, each split into 2 triangles).
        assert_eq!(hull.vertices.len(), 8);
        assert_eq!(hull.faces.len(), 12);
    }

    #[test]
    fn hull_of_tetrahedron() {
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.5, 1.0, 0.0),
            Point3::new(0.5, 0.5, 1.0),
        ];
        let hull = convex_hull_3d(&points).expect("hull should succeed");
        assert_eq!(hull.vertices.len(), 4);
        assert_eq!(hull.faces.len(), 4);
    }

    #[test]
    fn hull_with_interior_points() {
        // 8 cube corners + 1 interior point
        let mut points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 0.0),
            Point3::new(0.0, 0.0, 1.0),
            Point3::new(1.0, 0.0, 1.0),
            Point3::new(0.0, 1.0, 1.0),
            Point3::new(1.0, 1.0, 1.0),
        ];
        points.push(Point3::new(0.5, 0.5, 0.5)); // interior
        let hull = convex_hull_3d(&points).expect("hull should succeed");
        // Interior point should be ignored — still a cube.
        assert_eq!(hull.faces.len(), 12);
    }

    #[test]
    fn hull_rejects_coplanar_points() {
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 0.0),
        ];
        assert!(convex_hull_3d(&points).is_none());
    }

    #[test]
    fn hull_rejects_too_few_points() {
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
        ];
        assert!(convex_hull_3d(&points).is_none());
    }

    /// Compute volume of a triangle mesh via the signed tetrahedron method
    /// (divergence theorem: V = sum of signed tets formed with the origin).
    fn mesh_volume(hull: &ConvexHull) -> f64 {
        let mut vol = 0.0;
        for &[a, b, c] in &hull.faces {
            let pa = hull.vertices[a];
            let pb = hull.vertices[b];
            let pc = hull.vertices[c];
            // Signed volume of tetrahedron (origin, pa, pb, pc).
            vol += pa.x() * (pb.y() * pc.z() - pb.z() * pc.y())
                + pa.y() * (pb.z() * pc.x() - pb.x() * pc.z())
                + pa.z() * (pb.x() * pc.y() - pb.y() * pc.x());
        }
        vol / 6.0
    }

    #[test]
    fn hull_cube_volume() {
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 0.0),
            Point3::new(0.0, 0.0, 1.0),
            Point3::new(1.0, 0.0, 1.0),
            Point3::new(0.0, 1.0, 1.0),
            Point3::new(1.0, 1.0, 1.0),
        ];
        let hull = convex_hull_3d(&points).expect("hull should succeed");
        let vol = mesh_volume(&hull);
        assert!(
            (vol - 1.0).abs() < 1e-10,
            "unit cube volume should be 1.0, got {vol}"
        );
    }

    #[test]
    fn hull_displaced_cube_volume() {
        // Cube at (5, 5, 5) to (6, 6, 6) — volume should still be 1.0.
        let points = vec![
            Point3::new(5.0, 5.0, 5.0),
            Point3::new(6.0, 5.0, 5.0),
            Point3::new(5.0, 6.0, 5.0),
            Point3::new(6.0, 6.0, 5.0),
            Point3::new(5.0, 5.0, 6.0),
            Point3::new(6.0, 5.0, 6.0),
            Point3::new(5.0, 6.0, 6.0),
            Point3::new(6.0, 6.0, 6.0),
        ];
        let hull = convex_hull_3d(&points).expect("hull should succeed");
        let vol = mesh_volume(&hull);
        assert!(
            (vol - 1.0).abs() < 1e-10,
            "displaced unit cube volume should be 1.0, got {vol}"
        );
    }

    #[test]
    fn hull_minkowski_sum_two_unit_cubes() {
        // Minkowski sum of [0,1]^3 with [0,1]^3 = [0,2]^3, volume = 8.
        // Generate all 64 pairwise vertex sums.
        let cube_a: Vec<Point3> = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 0.0),
            Point3::new(0.0, 0.0, 1.0),
            Point3::new(1.0, 0.0, 1.0),
            Point3::new(0.0, 1.0, 1.0),
            Point3::new(1.0, 1.0, 1.0),
        ];
        let cube_b = cube_a.clone();

        let mut sum_points = Vec::with_capacity(64);
        for &a in &cube_a {
            for &b in &cube_b {
                sum_points.push(Point3::new(a.x() + b.x(), a.y() + b.y(), a.z() + b.z()));
            }
        }
        assert_eq!(sum_points.len(), 64);

        let hull = convex_hull_3d(&sum_points).expect("hull should succeed");
        let vol = mesh_volume(&hull);
        assert!(
            (vol - 8.0).abs() < 1e-8,
            "Minkowski sum of two unit cubes should have volume 8.0, got {vol}"
        );
    }

    #[test]
    fn hull_minkowski_sum_displaced_cubes() {
        // Cube A at origin [0,1]^3, Cube B at (5,5,5) to (6,6,6).
        // Minkowski sum vertices span [0+5, 1+6] = [5,7] in each axis.
        // So the hull is a 2x2x2 cube, volume = 8.
        let cube_a = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 0.0),
            Point3::new(0.0, 0.0, 1.0),
            Point3::new(1.0, 0.0, 1.0),
            Point3::new(0.0, 1.0, 1.0),
            Point3::new(1.0, 1.0, 1.0),
        ];
        let cube_b = vec![
            Point3::new(5.0, 5.0, 5.0),
            Point3::new(6.0, 5.0, 5.0),
            Point3::new(5.0, 6.0, 5.0),
            Point3::new(6.0, 6.0, 5.0),
            Point3::new(5.0, 5.0, 6.0),
            Point3::new(6.0, 5.0, 6.0),
            Point3::new(5.0, 6.0, 6.0),
            Point3::new(6.0, 6.0, 6.0),
        ];

        let mut sum_points = Vec::with_capacity(64);
        for &a in &cube_a {
            for &b in &cube_b {
                sum_points.push(Point3::new(a.x() + b.x(), a.y() + b.y(), a.z() + b.z()));
            }
        }

        let hull = convex_hull_3d(&sum_points).expect("hull should succeed");
        let vol = mesh_volume(&hull);
        assert!(
            (vol - 8.0).abs() < 1e-8,
            "Minkowski sum of two displaced unit cubes should have volume 8.0, got {vol}"
        );
    }

    #[test]
    fn hull_large_point_cloud_sphere() {
        // Generate points on a unit sphere — hull volume should approach 4*pi/3.
        use std::f64::consts::PI;
        let n_phi = 20;
        let n_theta = 40;
        let mut points = Vec::new();
        for i in 0..=n_phi {
            #[allow(clippy::cast_precision_loss)]
            let phi = PI * (i as f64) / (n_phi as f64);
            for j in 0..n_theta {
                #[allow(clippy::cast_precision_loss)]
                let theta = 2.0 * PI * (j as f64) / (n_theta as f64);
                points.push(Point3::new(
                    phi.sin() * theta.cos(),
                    phi.sin() * theta.sin(),
                    phi.cos(),
                ));
            }
        }

        let hull = convex_hull_3d(&points).expect("hull should succeed");
        let vol = mesh_volume(&hull);
        let expected = 4.0 * PI / 3.0;
        // With 20x40 = 800 points, the inscribed polyhedron volume should be
        // close but slightly less than the true sphere volume.
        assert!(
            vol > 0.95 * expected,
            "sphere hull volume {vol} should be close to {expected}"
        );
        assert!(
            vol <= expected + 1e-6,
            "sphere hull volume {vol} should not exceed true sphere volume {expected}"
        );
    }

    #[test]
    fn hull_faces_outward_winding() {
        // All face normals should point outward (positive signed distance
        // from centroid to each face plane should be negative).
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 2.0, 0.0),
            Point3::new(0.0, 0.0, 2.0),
            Point3::new(2.0, 2.0, 0.0),
            Point3::new(2.0, 0.0, 2.0),
            Point3::new(0.0, 2.0, 2.0),
            Point3::new(2.0, 2.0, 2.0),
        ];
        let hull = convex_hull_3d(&points).expect("hull should succeed");

        // Compute centroid of all hull vertices.
        let n = hull.vertices.len() as f64;
        let cx: f64 = hull.vertices.iter().map(|p| p.x()).sum::<f64>() / n;
        let cy: f64 = hull.vertices.iter().map(|p| p.y()).sum::<f64>() / n;
        let cz: f64 = hull.vertices.iter().map(|p| p.z()).sum::<f64>() / n;
        let centroid = Point3::new(cx, cy, cz);

        for &[a, b, c] in &hull.faces {
            let pa = hull.vertices[a];
            let pb = hull.vertices[b];
            let pc = hull.vertices[c];
            let ab = pb - pa;
            let ac = pc - pa;
            let normal = ab.cross(ac);
            // Dot with vector from face vertex to centroid should be negative
            // (centroid is inside, normal points outward).
            let to_centroid = Vec3::new(
                centroid.x() - pa.x(),
                centroid.y() - pa.y(),
                centroid.z() - pa.z(),
            );
            let dot = normal.dot(to_centroid);
            assert!(
                dot <= 0.0,
                "face [{a},{b},{c}] normal should point away from centroid, dot = {dot}"
            );
        }
    }
}