Skip to main content

brepkit_math/
ray_triangle.rs

1//! Watertight ray-triangle intersection (Woop, Benthin, Wald 2013).
2//!
3//! This module implements the watertight ray-triangle intersection algorithm
4//! that guarantees no cracks or double-hits on shared edges between adjacent
5//! triangles. The key idea is to transform coordinates so the ray is
6//! axis-aligned along +Z, then evaluate edge functions using identical
7//! floating-point operations on shared vertices.
8
9use crate::madd::Madd;
10use crate::vec::{Point3, Vec3};
11
12/// Result of a watertight ray-triangle intersection test.
13#[derive(Debug, Clone, Copy)]
14pub struct RayTriangleHit {
15    /// Distance along the ray to the hit point (t parameter).
16    pub t: f64,
17    /// Barycentric coordinate u.
18    pub u: f64,
19    /// Barycentric coordinate v.
20    pub v: f64,
21}
22
23/// Deterministic tie-breaking for zero-valued edge functions.
24///
25/// When a 2D edge function `p x q` evaluates to exactly zero, this function
26/// returns a small positive or negative value based on the edge direction.
27/// The sign is chosen deterministically so that for the complementary edge
28/// (`q x p`), the opposite sign is returned. This ensures shared edges are
29/// assigned to exactly one triangle.
30fn edge_tiebreak(px: f64, py: f64, qx: f64, qy: f64) -> f64 {
31    // Use the signs of the constituent products as a tiebreaker.
32    // For edge function `px*qy - py*qx`, when result is zero, look at
33    // the individual terms to pick a deterministic sign.
34    let a = px * qy;
35    let b = py * qx;
36    if a > b {
37        f64::MIN_POSITIVE
38    } else if a < b {
39        -f64::MIN_POSITIVE
40    } else {
41        // Both products are equal (and possibly zero). Use coordinate signs.
42        // This order is deterministic: we break ties by comparing coordinates.
43        if px > qx {
44            f64::MIN_POSITIVE
45        } else if px < qx {
46            -f64::MIN_POSITIVE
47        } else if py > qy {
48            f64::MIN_POSITIVE
49        } else {
50            -f64::MIN_POSITIVE
51        }
52    }
53}
54
55/// Watertight ray-triangle intersection (Woop, Benthin, Wald 2013).
56///
57/// Tests whether a ray from `origin` in direction `dir` hits the triangle
58/// `(v0, v1, v2)`. Returns `Some(hit)` with the parametric distance and
59/// barycentric coordinates, or `None` if no intersection.
60///
61/// This algorithm guarantees watertight results on shared edges: a ray
62/// hitting a shared edge between two triangles will report exactly one
63/// intersection, with no cracks or double-hits. This is achieved by using
64/// identical floating-point operations on shared vertices.
65///
66/// The barycentric coordinates satisfy `hit_point = (1-u-v)*v0 + u*v1 + v*v2`.
67#[must_use]
68#[allow(clippy::many_single_char_names)]
69pub fn watertight_ray_triangle_intersect(
70    origin: Point3,
71    dir: Vec3,
72    v0: Point3,
73    v1: Point3,
74    v2: Point3,
75) -> Option<RayTriangleHit> {
76    let d = dir.0;
77
78    // Step 1: Find the largest absolute component of dir (kz), then set kx, ky.
79    let abs_x = d[0].abs();
80    let abs_y = d[1].abs();
81    let abs_z = d[2].abs();
82
83    let kz = if abs_x > abs_y && abs_x > abs_z {
84        0
85    } else if abs_y > abs_z {
86        1
87    } else {
88        2
89    };
90    let mut kx = (kz + 1) % 3;
91    let mut ky = (kx + 1) % 3;
92
93    // Swap kx and ky if dir[kz] is negative to preserve winding order.
94    if d[kz] < 0.0 {
95        std::mem::swap(&mut kx, &mut ky);
96    }
97
98    // Step 2: Shear constants.
99    let sz = 1.0 / d[kz];
100    let sx = d[kx] * sz;
101    let sy = d[ky] * sz;
102
103    // Step 3: Translate vertices relative to ray origin.
104    let a = (v0 - origin).0;
105    let b = (v1 - origin).0;
106    let c = (v2 - origin).0;
107
108    // Step 4: Shear and permute.
109    let ax = a[kx] - sx * a[kz];
110    let ay = a[ky] - sy * a[kz];
111    let bx = b[kx] - sx * b[kz];
112    let by = b[ky] - sy * b[kz];
113    let cx = c[kx] - sx * c[kz];
114    let cy = c[ky] - sy * c[kz];
115
116    // Step 5: Edge function values (2D cross products).
117    let mut u = cx.madd(by, -(cy * bx));
118    let mut v = ax.madd(cy, -(ay * cx));
119    let mut w = bx.madd(ay, -(by * ax));
120
121    // Step 6: Deterministic tie-breaking for zero edge functions.
122    // When an edge function is exactly zero, assign a deterministic sign
123    // based on the edge direction to guarantee that shared edges/vertices
124    // are claimed by exactly one triangle.
125    if u == 0.0 {
126        u = edge_tiebreak(cx, cy, bx, by);
127    }
128    if v == 0.0 {
129        v = edge_tiebreak(ax, ay, cx, cy);
130    }
131    if w == 0.0 {
132        w = edge_tiebreak(bx, by, ax, ay);
133    }
134
135    // Step 7: Sign check — U, V, W must all share the same sign.
136    if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
137        return None;
138    }
139
140    // Step 8: Determinant.
141    let det = u + v + w;
142    if det == 0.0 {
143        return None;
144    }
145
146    // Step 9: Compute scaled t.
147    let az = sz * a[kz];
148    let bz = sz * b[kz];
149    let cz = sz * c[kz];
150    let t_scaled = u.madd(az, v.madd(bz, w * cz));
151
152    // Step 10: Check that t is positive (ray goes forward).
153    // If det > 0, t_scaled must be > 0; if det < 0, t_scaled must be < 0.
154    if (det > 0.0 && t_scaled <= 0.0) || (det < 0.0 && t_scaled >= 0.0) {
155        return None;
156    }
157
158    // Step 11: Final values.
159    let inv_det = 1.0 / det;
160    Some(RayTriangleHit {
161        t: t_scaled * inv_det,
162        u: v * inv_det,
163        v: w * inv_det,
164    })
165}
166
167#[cfg(test)]
168#[allow(
169    clippy::unwrap_used,
170    clippy::expect_used,
171    clippy::cast_lossless,
172    clippy::suboptimal_flops
173)]
174mod tests {
175    use super::*;
176
177    const EPS: f64 = 1e-12;
178
179    fn tri() -> (Point3, Point3, Point3) {
180        (
181            Point3::new(-1.0, -1.0, 0.0),
182            Point3::new(1.0, -1.0, 0.0),
183            Point3::new(0.0, 1.0, 0.0),
184        )
185    }
186
187    #[test]
188    fn ray_hits_triangle() {
189        let (v0, v1, v2) = tri();
190        let origin = Point3::new(0.0, 0.0, -1.0);
191        let dir = Vec3::new(0.0, 0.0, 1.0);
192
193        let hit = watertight_ray_triangle_intersect(origin, dir, v0, v1, v2).expect("should hit");
194        assert!((hit.t - 1.0).abs() < EPS);
195    }
196
197    #[test]
198    fn ray_misses_triangle() {
199        let (v0, v1, v2) = tri();
200        let origin = Point3::new(10.0, 10.0, -1.0);
201        let dir = Vec3::new(0.0, 0.0, 1.0);
202
203        assert!(watertight_ray_triangle_intersect(origin, dir, v0, v1, v2).is_none());
204    }
205
206    #[test]
207    fn ray_parallel_to_triangle() {
208        let (v0, v1, v2) = tri();
209        let origin = Point3::new(0.0, 0.0, 0.0);
210        let dir = Vec3::new(1.0, 0.0, 0.0);
211
212        assert!(watertight_ray_triangle_intersect(origin, dir, v0, v1, v2).is_none());
213    }
214
215    #[test]
216    fn shared_edge_exactly_one_hit() {
217        // Two triangles sharing edge from (0,0,0) to (1,0,0).
218        let shared_a = Point3::new(0.0, 0.0, 0.0);
219        let shared_b = Point3::new(1.0, 0.0, 0.0);
220        let tri1_c = Point3::new(0.5, 1.0, 0.0);
221        let tri2_c = Point3::new(0.5, -1.0, 0.0);
222
223        // Ray aimed at the midpoint of the shared edge.
224        let origin = Point3::new(0.5, 0.0, -1.0);
225        let dir = Vec3::new(0.0, 0.0, 1.0);
226
227        let hit1 = watertight_ray_triangle_intersect(origin, dir, shared_a, shared_b, tri1_c);
228        let hit2 = watertight_ray_triangle_intersect(origin, dir, shared_a, shared_b, tri2_c);
229
230        let count = hit1.is_some() as u32 + hit2.is_some() as u32;
231        assert_eq!(count, 1, "shared edge must report exactly one hit");
232    }
233
234    #[test]
235    fn ray_hits_vertex() {
236        // Four triangles forming a complete fan around the origin vertex,
237        // covering all quadrants so the fan is closed.
238        let shared = Point3::new(0.0, 0.0, 0.0);
239        let tris = [
240            (
241                shared,
242                Point3::new(1.0, 0.0, 0.0),
243                Point3::new(0.0, 1.0, 0.0),
244            ),
245            (
246                shared,
247                Point3::new(0.0, 1.0, 0.0),
248                Point3::new(-1.0, 0.0, 0.0),
249            ),
250            (
251                shared,
252                Point3::new(-1.0, 0.0, 0.0),
253                Point3::new(0.0, -1.0, 0.0),
254            ),
255            (
256                shared,
257                Point3::new(0.0, -1.0, 0.0),
258                Point3::new(1.0, 0.0, 0.0),
259            ),
260        ];
261
262        let origin = Point3::new(0.0, 0.0, -1.0);
263        let dir = Vec3::new(0.0, 0.0, 1.0);
264
265        let count: u32 = tris
266            .iter()
267            .map(|&(a, b, c)| {
268                watertight_ray_triangle_intersect(origin, dir, a, b, c).is_some() as u32
269            })
270            .sum();
271
272        assert_eq!(
273            count, 1,
274            "vertex shared by 4 triangles must report exactly one hit"
275        );
276    }
277
278    #[test]
279    fn backface_not_hit() {
280        let (v0, v1, v2) = tri();
281        // Ray going away from the triangle.
282        let origin = Point3::new(0.0, 0.0, -1.0);
283        let dir = Vec3::new(0.0, 0.0, -1.0);
284
285        assert!(watertight_ray_triangle_intersect(origin, dir, v0, v1, v2).is_none());
286    }
287
288    #[test]
289    fn barycentric_coordinates_valid() {
290        let (v0, v1, v2) = tri();
291        let origin = Point3::new(0.0, 0.0, -1.0);
292        let dir = Vec3::new(0.0, 0.0, 1.0);
293
294        let hit = watertight_ray_triangle_intersect(origin, dir, v0, v1, v2).expect("should hit");
295
296        assert!(hit.u >= -EPS, "u = {} should be >= 0", hit.u);
297        assert!(hit.v >= -EPS, "v = {} should be >= 0", hit.v);
298        assert!(
299            hit.u + hit.v <= 1.0 + EPS,
300            "u + v = {} should be <= 1",
301            hit.u + hit.v,
302        );
303
304        // Verify that barycentric coords reconstruct the hit point.
305        let w = 1.0 - hit.u - hit.v;
306        let px = w * v0.x() + hit.u * v1.x() + hit.v * v2.x();
307        let py = w * v0.y() + hit.u * v1.y() + hit.v * v2.y();
308        let pz = w * v0.z() + hit.u * v1.z() + hit.v * v2.z();
309
310        let expected = origin.0[2] + hit.t * dir.0[2];
311        assert!(
312            (pz - expected).abs() < EPS,
313            "pz = {pz}, expected = {expected}"
314        );
315        // The hit point should be at origin + t*dir.
316        assert!((px - origin.x()).abs() < EPS);
317        assert!((py - origin.y()).abs() < EPS);
318    }
319}