Skip to main content

crcbl_phys/
mesh.rs

1//! Static triangle meshes: level geometry — floors, ramps, stairs — that the
2//! contact solver and the query world both collide triangle by triangle.
3//!
4//! A [`TriangleMesh`] is vertices and triangles in its own frame, validated
5//! once, with a bounding volume hierarchy over its triangles and a record of
6//! which of each triangle's edges are **active**. It goes on a static or
7//! kinematic body as [`crate::ColliderComponent::Mesh`], or straight into a
8//! [`crate::PhysicsWorld`] with [`crate::PhysicsWorld::add_mesh`].
9//!
10//! # Validation: refused, not skipped
11//!
12//! [`TriangleMesh::new`] refuses a mesh with no triangles, a vertex holding a
13//! `NaN` or an infinity, an index past the vertices, and a **degenerate
14//! triangle** — one whose height across its longest edge is under
15//! [`TriangleMesh::MIN_ASPECT`] of that edge, zero-area and repeated-index
16//! triangles included. A degenerate triangle has no normal to push along, and
17//! skipping it silently would renumber every triangle after it, so the
18//! triangle indices a [`ContactReport`](crate::ContactReport) or a
19//! [`MeshHit`] names would no longer be the indices the game gave. Refusing
20//! names the first offender instead, and the game cleans its data once.
21//!
22//! # Active edges: no catching on seams
23//!
24//! A box sliding across a floor made of two triangles meets the seam between
25//! them: to the second triangle alone, the box's leading edge is sinking into
26//! _its_ edge, and the separating axis says so with a normal pointing back
27//! against the slide — a ghost collision that jolts or stops the box. The fix
28//! transcribed here is Jolt Physics' (`Jolt/Geometry/ActiveEdges.h`, Jorrit
29//! Rouwé), the precomputed form of Bullet's `btAdjustInternalEdgeContacts`:
30//!
31//! - **At build**, each edge two triangles share is marked active only if it
32//!   is **convex** and bends more than [`TriangleMesh::ACTIVE_EDGE_COSINE`]'s
33//!   angle (`IsEdgeActive`); a coplanar seam or a concave crease is inactive.
34//!   An edge of one triangle, or of three or more, is active.
35//! - **At contact**, a contact on an inactive edge, or on a vertex whose two
36//!   edges are both inactive, pushes along the **triangle's normal** instead
37//!   of the direction it found (`FixNormal`). A stair's nose is active, so a
38//!   ball rolls off it round; a seam in a floor is not.
39//!
40//! Jolt's `FixNormal` also takes the pair's relative velocity as a hint for a
41//! body grazing a triangle's inactive edge side-on; that part is not
42//! transcribed — see `docs/notes/simulation.md` and `docs/backlog.md`.
43//!
44//! Edges are shared by vertex **position**, not by index: vertices at the
45//! same point are welded first, so a mesh an exporter wrote with each face's
46//! corners repeated still finds its seams. Only exactly equal positions weld.
47//!
48//! # One-sided to contacts, two-sided to queries
49//!
50//! To the contact solver a triangle is **one-sided**: a shape whose centre is
51//! behind its plane — against its normal, by the right-hand winding
52//! `(v1 − v0) × (v2 − v0)` — is not collided with it, as Box2D v3's chain
53//! segments are (`b2CollideChainSegmentAndPolygon`, "polygon is behind
54//! segment"). So a body pushed a little through a floor is pushed back up, not
55//! down and out of the level. To rays, sweeps and overlaps a triangle is a
56//! surface with two sides, and a hit's normal faces the side it came from.
57//!
58//! # Cost
59//!
60//! In a system with contacts **each triangle is a broadphase proxy of its
61//! own**, as each part of a compound is (see [`crate::contact`]), so a contact
62//! is one body against one triangle, with the triangle's own manifold, feature
63//! ids and warm start. The query world keeps one entry per mesh and descends
64//! the mesh's own tree.
65
66pub(crate) mod geometry;
67mod query;
68
69use std::fmt;
70use std::sync::Arc;
71
72use glam::DVec3;
73
74pub use self::query::MeshHit;
75pub(crate) use self::query::{MeshScratch, PlacedMesh};
76use crate::broadphase::Bvh;
77use crate::collider::Aabb;
78
79/// A static triangle mesh, validated, with active edges and a tree over its
80/// triangles: see the [module docs](self).
81///
82/// Cloning copies a pointer: the data is shared behind an [`Arc`].
83#[derive(Clone)]
84pub struct TriangleMesh {
85    data: Arc<MeshData>,
86}
87
88/// The shared half of a [`TriangleMesh`].
89#[derive(Clone)]
90struct MeshData {
91    vertices: Vec<DVec3>,
92    triangles: Vec<[u32; 3]>,
93    /// Each triangle's unit normal.
94    normals: Vec<DVec3>,
95    /// Each triangle's active edges: bit `i` for edge `i`, from vertex `i` to
96    /// vertex `i + 1`.
97    active: Vec<u8>,
98    /// Over the triangles, each named by its index.
99    bvh: Bvh,
100    bounds: Aabb,
101}
102
103/// Why [`TriangleMesh::new`] refused a mesh.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum MeshError {
106    /// No triangles: nothing to collide with.
107    NoTriangles,
108    /// More triangles than a `u32` can name.
109    TooManyTriangles {
110        /// How many it was given.
111        count: usize,
112    },
113    /// The vertex at `index` holds a `NaN` or an infinity.
114    NonFiniteVertex {
115        /// Its index.
116        index: usize,
117    },
118    /// Triangle `triangle` names a vertex that does not exist.
119    IndexOutOfRange {
120        /// The triangle.
121        triangle: usize,
122        /// The index it named.
123        index: u32,
124    },
125    /// Triangle `triangle` is degenerate: see [`TriangleMesh::MIN_ASPECT`].
126    DegenerateTriangle {
127        /// The triangle.
128        triangle: usize,
129    },
130}
131
132impl fmt::Display for MeshError {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        match self {
135            Self::NoTriangles => write!(f, "a triangle mesh needs at least one triangle"),
136            Self::TooManyTriangles { count } => {
137                write!(
138                    f,
139                    "a triangle mesh has at most 2^32 - 1 triangles, not {count}"
140                )
141            }
142            Self::NonFiniteVertex { index } => {
143                write!(f, "mesh vertex {index} is not finite")
144            }
145            Self::IndexOutOfRange { triangle, index } => {
146                write!(
147                    f,
148                    "mesh triangle {triangle} names vertex {index}, which does not exist"
149                )
150            }
151            Self::DegenerateTriangle { triangle } => {
152                write!(f, "mesh triangle {triangle} is degenerate")
153            }
154        }
155    }
156}
157
158impl std::error::Error for MeshError {}
159
160impl TriangleMesh {
161    /// The least a triangle's height across its longest edge may be, as a
162    /// share of that edge, before it is refused as degenerate: a micrometre
163    /// across a metre. Below it the normal is rounding.
164    pub const MIN_ASPECT: f64 = 1.0e-6;
165
166    /// The cosine of the angle a convex edge between two triangles must bend
167    /// by to be active: five degrees, Jolt's default
168    /// `mActiveEdgeCosThresholdAngle`. A seam flatter than that is treated as
169    /// flat.
170    pub const ACTIVE_EDGE_COSINE: f64 = 0.996_194_698_091_745_5;
171
172    /// The cosine past which two triangles' normals are opposite, back to
173    /// back: one degree, Jolt's.
174    const BACK_TO_BACK_COSINE: f64 = 0.999_847_695_156_391_2;
175
176    /// A mesh of `triangles`, each three indices into `vertices` wound so
177    /// `(v1 − v0) × (v2 − v0)` is its outward normal.
178    ///
179    /// # Errors
180    ///
181    /// See the [module docs](self): [`MeshError::NoTriangles`] and
182    /// [`MeshError::TooManyTriangles`] first, then the first non-finite vertex
183    /// in vertex order, then the first bad triangle in triangle order — an
184    /// index out of range before degeneracy.
185    pub fn new(vertices: &[DVec3], triangles: &[[u32; 3]]) -> Result<Self, MeshError> {
186        if triangles.is_empty() {
187            return Err(MeshError::NoTriangles);
188        }
189        if u32::try_from(triangles.len()).is_err() {
190            return Err(MeshError::TooManyTriangles {
191                count: triangles.len(),
192            });
193        }
194        if let Some(index) = vertices.iter().position(|v| !v.is_finite()) {
195            return Err(MeshError::NonFiniteVertex { index });
196        }
197        let mut normals = Vec::with_capacity(triangles.len());
198        for (triangle, indices) in triangles.iter().enumerate() {
199            if let Some(&index) = indices.iter().find(|&&i| i as usize >= vertices.len()) {
200                return Err(MeshError::IndexOutOfRange { triangle, index });
201            }
202            let [a, b, c] = indices.map(|i| vertices[i as usize]);
203            let cross = (b - a).cross(c - a);
204            let longest = (b - a)
205                .length_squared()
206                .max((c - b).length_squared())
207                .max((a - c).length_squared());
208            // |cross| is the longest edge times the height across it. One so
209            // large its products overflow has no normal to take either.
210            let twice_area = cross.length();
211            if !twice_area.is_finite() || twice_area <= Self::MIN_ASPECT * longest {
212                return Err(MeshError::DegenerateTriangle { triangle });
213            }
214            normals.push(cross.normalize());
215        }
216
217        let active = active_edges(vertices, triangles, &normals);
218        let boxes: Vec<(Aabb, u32)> = triangles
219            .iter()
220            .enumerate()
221            .map(|(index, t)| {
222                (
223                    triangle_bounds(&t.map(|i| vertices[i as usize])),
224                    index as u32,
225                )
226            })
227            .collect();
228        let bounds = boxes
229            .iter()
230            .fold(Aabb::EMPTY, |bounds, (aabb, _)| bounds.union(*aabb));
231        Ok(Self {
232            data: Arc::new(MeshData {
233                vertices: vertices.to_vec(),
234                triangles: triangles.to_vec(),
235                normals,
236                active,
237                bvh: Bvh::build(boxes),
238                bounds,
239            }),
240        })
241    }
242
243    /// This mesh with **every edge active**, seams included: Jolt's
244    /// `EActiveEdgeMode::CollideWithAll`. A body sliding across a seam then
245    /// catches on it, which is what the active edges are there to stop; this
246    /// is for comparing against that, not for a level.
247    #[must_use]
248    pub fn collide_with_all_edges(mut self) -> Self {
249        Arc::make_mut(&mut self.data).active.fill(0b111);
250        self
251    }
252
253    /// The vertices, as given.
254    #[must_use]
255    pub fn vertices(&self) -> &[DVec3] {
256        &self.data.vertices
257    }
258
259    /// The triangles, as given: three indices into [`vertices`](Self::vertices)
260    /// each.
261    #[must_use]
262    pub fn triangles(&self) -> &[[u32; 3]] {
263        &self.data.triangles
264    }
265
266    /// How many triangles there are.
267    #[must_use]
268    pub fn triangle_count(&self) -> usize {
269        self.data.triangles.len()
270    }
271
272    /// Triangle `index`'s three corners.
273    ///
274    /// # Panics
275    ///
276    /// Panics if there is no triangle `index`.
277    #[must_use]
278    pub fn corners(&self, index: usize) -> [DVec3; 3] {
279        self.data.triangles[index].map(|i| self.data.vertices[i as usize])
280    }
281
282    /// Triangle `index`'s unit normal.
283    ///
284    /// # Panics
285    ///
286    /// Panics if there is no triangle `index`.
287    #[must_use]
288    pub fn normal(&self, index: usize) -> DVec3 {
289        self.data.normals[index]
290    }
291
292    /// Triangle `index`'s active edges: bit `i` set when edge `i`, from its
293    /// vertex `i` to vertex `i + 1`, is active. See the [module docs](self).
294    ///
295    /// # Panics
296    ///
297    /// Panics if there is no triangle `index`.
298    #[must_use]
299    pub fn active_edges(&self, index: usize) -> u8 {
300        self.data.active[index]
301    }
302
303    /// The bounds of every triangle, in the mesh's frame.
304    #[must_use]
305    pub fn bounds(&self) -> Aabb {
306        self.data.bounds
307    }
308
309    /// The tree over the triangles, each leaf named by its triangle's index.
310    pub(crate) fn bvh(&self) -> &Bvh {
311        &self.data.bvh
312    }
313}
314
315impl PartialEq for TriangleMesh {
316    /// Equal when the vertices, the triangles and the active edges are: the
317    /// normals and the tree follow from those.
318    fn eq(&self, other: &Self) -> bool {
319        Arc::ptr_eq(&self.data, &other.data)
320            || (self.data.vertices == other.data.vertices
321                && self.data.triangles == other.data.triangles
322                && self.data.active == other.data.active)
323    }
324}
325
326impl fmt::Debug for TriangleMesh {
327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328        f.debug_struct("TriangleMesh")
329            .field("vertices", &self.data.vertices.len())
330            .field("triangles", &self.data.triangles.len())
331            .field("bounds", &self.data.bounds)
332            .finish()
333    }
334}
335
336/// The bounds of a triangle's three corners.
337pub(crate) fn triangle_bounds(corners: &[DVec3; 3]) -> Aabb {
338    Aabb::new(
339        corners[0].min(corners[1]).min(corners[2]),
340        corners[0].max(corners[1]).max(corners[2]),
341    )
342}
343
344/// Each triangle's active-edge bits: see the module docs.
345///
346/// Vertices are welded by exact position first, then every edge is keyed by
347/// its two welded ends and the keys sorted, so the triangles sharing an edge
348/// come out next to each other in an order that depends only on the input.
349fn active_edges(vertices: &[DVec3], triangles: &[[u32; 3]], normals: &[DVec3]) -> Vec<u8> {
350    // Weld: each vertex's id is the lowest index at its exact position, `-0.0`
351    // and `+0.0` alike.
352    let bits = |v: DVec3| v.to_array().map(|x| if x == 0.0 { 0 } else { x.to_bits() });
353    let mut order: Vec<u32> = (0..vertices.len() as u32).collect();
354    order.sort_unstable_by_key(|&i| (bits(vertices[i as usize]), i));
355    let mut welded = vec![0u32; vertices.len()];
356    let mut run = 0usize;
357    for k in 0..order.len() {
358        if bits(vertices[order[k] as usize]) != bits(vertices[order[run] as usize]) {
359            run = k;
360        }
361        welded[order[k] as usize] = order[run];
362    }
363
364    // (lower end, upper end, triangle, edge) for every edge.
365    let mut edges: Vec<(u32, u32, u32, u8)> = Vec::with_capacity(triangles.len() * 3);
366    for (t, indices) in triangles.iter().enumerate() {
367        for e in 0..3u8 {
368            let p = welded[indices[e as usize] as usize];
369            let q = welded[indices[(e as usize + 1) % 3] as usize];
370            edges.push((p.min(q), p.max(q), t as u32, e));
371        }
372    }
373    edges.sort_unstable();
374
375    let mut active = vec![0u8; triangles.len()];
376    let mut start = 0;
377    while start < edges.len() {
378        let key = (edges[start].0, edges[start].1);
379        let mut end = start + 1;
380        while end < edges.len() && (edges[end].0, edges[end].1) == key {
381            end += 1;
382        }
383        let shared = &edges[start..end];
384        if let [(_, _, t1, e1), (_, _, t2, e2)] = *shared {
385            let direction = |t: u32, e: u8| {
386                let indices = triangles[t as usize];
387                vertices[indices[(e as usize + 1) % 3] as usize]
388                    - vertices[indices[e as usize] as usize]
389            };
390            let (n1, n2) = (normals[t1 as usize], normals[t2 as usize]);
391            if is_edge_active(n1, n2, direction(t1, e1)) {
392                active[t1 as usize] |= 1 << e1;
393            }
394            if is_edge_active(n2, n1, direction(t2, e2)) {
395                active[t2 as usize] |= 1 << e2;
396            }
397        } else {
398            // One triangle's edge is the mesh's boundary, and three or more
399            // triangles on one edge have no single neighbour to be flat with.
400            for &(_, _, t, e) in shared {
401                active[t as usize] |= 1 << e;
402            }
403        }
404        start = end;
405    }
406    active
407}
408
409/// Whether the edge running along `direction` in the triangle of normal `n1`,
410/// shared with the triangle of normal `n2`, is active — Jolt's
411/// `ActiveEdges::IsEdgeActive`: back to back is active, concave is not, and
412/// convex is when it bends past [`TriangleMesh::ACTIVE_EDGE_COSINE`].
413fn is_edge_active(n1: DVec3, n2: DVec3, direction: DVec3) -> bool {
414    let cosine = n1.dot(n2);
415    if cosine < -TriangleMesh::BACK_TO_BACK_COSINE {
416        return true;
417    }
418    if n1.cross(n2).dot(direction) < 0.0 {
419        return false;
420    }
421    cosine < TriangleMesh::ACTIVE_EDGE_COSINE
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427
428    /// A square floor of side 2 at `y = 0`, split along its diagonal from
429    /// `(-1, 0, -1)` to `(1, 0, 1)`, both triangles facing up.
430    fn quad() -> (Vec<DVec3>, Vec<[u32; 3]>) {
431        (
432            vec![
433                DVec3::new(-1.0, 0.0, -1.0),
434                DVec3::new(1.0, 0.0, -1.0),
435                DVec3::new(1.0, 0.0, 1.0),
436                DVec3::new(-1.0, 0.0, 1.0),
437            ],
438            vec![[0, 3, 2], [0, 2, 1]],
439        )
440    }
441
442    /// **What is refused, and which offender is named.**
443    #[test]
444    fn a_mesh_refuses_what_cannot_be_collided_with() {
445        let (vertices, triangles) = quad();
446        assert!(TriangleMesh::new(&vertices, &triangles).is_ok());
447        assert_eq!(
448            TriangleMesh::new(&vertices, &[]),
449            Err(MeshError::NoTriangles)
450        );
451        let mut poisoned = vertices.clone();
452        poisoned[2].y = f64::NAN;
453        assert_eq!(
454            TriangleMesh::new(&poisoned, &triangles),
455            Err(MeshError::NonFiniteVertex { index: 2 })
456        );
457        poisoned[2].y = f64::INFINITY;
458        assert_eq!(
459            TriangleMesh::new(&poisoned, &triangles),
460            Err(MeshError::NonFiniteVertex { index: 2 })
461        );
462        assert_eq!(
463            TriangleMesh::new(&vertices, &[[0, 3, 2], [0, 2, 4]]),
464            Err(MeshError::IndexOutOfRange {
465                triangle: 1,
466                index: 4
467            })
468        );
469        // A repeated index, three points in a line, and a sliver a tenth of
470        // a micrometre high across a metre.
471        for bad in [[0, 0, 2], [0, 1, 1]] {
472            assert_eq!(
473                TriangleMesh::new(&vertices, &[[0, 3, 2], bad]),
474                Err(MeshError::DegenerateTriangle { triangle: 1 })
475            );
476        }
477        let line = [DVec3::ZERO, DVec3::X, DVec3::X * 2.0];
478        assert_eq!(
479            TriangleMesh::new(&line, &[[0, 1, 2]]),
480            Err(MeshError::DegenerateTriangle { triangle: 0 })
481        );
482        let sliver = [DVec3::ZERO, DVec3::X, DVec3::new(0.5, 1.0e-7, 0.0)];
483        assert_eq!(
484            TriangleMesh::new(&sliver, &[[0, 1, 2]]),
485            Err(MeshError::DegenerateTriangle { triangle: 0 })
486        );
487        let thin = [DVec3::ZERO, DVec3::X, DVec3::new(0.5, 1.0e-5, 0.0)];
488        assert!(TriangleMesh::new(&thin, &[[0, 1, 2]]).is_ok());
489    }
490
491    /// **A flat seam is inactive and the outline is active**: the diagonal
492    /// of the quad is edge 2 of its first triangle (`2 → 0`) and edge 0 of its
493    /// second (`0 → 2`), and every other edge is the boundary.
494    #[test]
495    fn a_flat_seam_is_inactive_and_the_outline_active() {
496        let (vertices, triangles) = quad();
497        let mesh = TriangleMesh::new(&vertices, &triangles).unwrap();
498        assert_eq!(mesh.active_edges(0), 0b011);
499        assert_eq!(mesh.active_edges(1), 0b110);
500        assert_eq!(mesh.normal(0), DVec3::Y);
501        let all = mesh.collide_with_all_edges();
502        assert_eq!((all.active_edges(0), all.active_edges(1)), (0b111, 0b111));
503    }
504
505    /// **Welded by position**: the same quad written with each triangle's
506    /// corners as vertices of its own still finds its seam.
507    #[test]
508    fn repeated_corners_weld_into_one_seam() {
509        let (vertices, triangles) = quad();
510        let unshared: Vec<DVec3> = triangles
511            .iter()
512            .flat_map(|t| t.map(|i| vertices[i as usize]))
513            .collect();
514        let mesh = TriangleMesh::new(&unshared, &[[0, 1, 2], [3, 4, 5]]).unwrap();
515        assert_eq!(mesh.active_edges(0), 0b011);
516        assert_eq!(mesh.active_edges(1), 0b110);
517    }
518
519    /// **A step's nose is active and its crease is not.** The nose, where
520    /// the tread turns down into the riser below it, is convex; the riser's
521    /// foot, where it meets the floor in front, is concave.
522    #[test]
523    fn a_stairs_nose_is_active_and_its_crease_is_not() {
524        // Floor x ∈ [-1, 0] at y = 0; riser x = 0, y ∈ [0, 1], facing -x;
525        // tread y = 1 over x ∈ [0, 1]; all across z ∈ [0, 1].
526        let vertices = [
527            DVec3::new(-1.0, 0.0, 0.0),
528            DVec3::new(-1.0, 0.0, 1.0),
529            DVec3::new(0.0, 0.0, 0.0),
530            DVec3::new(0.0, 0.0, 1.0),
531            DVec3::new(0.0, 1.0, 0.0),
532            DVec3::new(0.0, 1.0, 1.0),
533            DVec3::new(1.0, 1.0, 0.0),
534            DVec3::new(1.0, 1.0, 1.0),
535        ];
536        let triangles = [
537            [0, 1, 3],
538            [0, 3, 2], // floor
539            [2, 3, 5],
540            [2, 5, 4], // riser
541            [4, 5, 7],
542            [4, 7, 6], // tread
543        ];
544        let mesh = TriangleMesh::new(&vertices, &triangles).unwrap();
545        assert_eq!(mesh.normal(0), DVec3::Y);
546        assert_eq!(mesh.normal(2), -DVec3::X);
547        assert_eq!(mesh.normal(4), DVec3::Y);
548        // Floor triangle 1's edge 1 (3 → 2) is the crease: concave.
549        assert_eq!(mesh.active_edges(1) & 0b010, 0, "the crease");
550        // Riser triangle 3's edge 1 (5 → 4) is the nose: convex, a right angle.
551        assert_ne!(mesh.active_edges(3) & 0b010, 0, "the nose");
552        // The tread's own seam, 7 → 4 in triangle 4 and 4 → 7 in 5, is flat.
553        assert_eq!(mesh.active_edges(4) & 0b100, 0, "the tread's seam");
554        assert_eq!(mesh.active_edges(5) & 0b001, 0, "the tread's seam");
555    }
556}