Skip to main content

crcbl_phys/mesh/
query.rs

1//! Rays, sweeps and overlaps against a [`TriangleMesh`], exact to the
2//! triangle: its own tree finds the triangles a query's bounds reach, and each
3//! is tested exactly.
4//!
5//! A mesh answers in its own frame, and names the triangle and where on it;
6//! [`PlacedMesh`] is a mesh at a [`Transform`], answering in the world as the
7//! other shapes of [`crate::PhysicsWorld`] do. To a query a triangle is a
8//! surface with two sides: a hit's normal faces the side the query came from.
9
10use glam::{DMat3, DQuat, DVec3};
11
12use super::TriangleMesh;
13use super::geometry::{
14    Cuboid, box_triangle_axes, closest_on_triangle, ray_triangle, segment_triangle,
15    sweep_into_triangle,
16};
17use crate::broadphase::{BvhHit, Ray, Segment};
18use crate::collider::{Aabb, Capsule, Sphere};
19use crate::components::Transform;
20use crate::contact::shape::ContactShape;
21use crate::query::{
22    AcceleratedPath, ArcHit, OverlapHit, Penetration, ShapeHit, contact_where, support,
23};
24
25/// A query's nearest hit on a [`TriangleMesh`].
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct MeshHit {
28    /// The triangle struck: an index into [`TriangleMesh::triangles`].
29    pub triangle: u32,
30    /// The weights of the triangle's three corners that make the point struck
31    /// on it — [`hit`](Self::hit)'s `point` in the mesh's frame.
32    pub barycentric: DVec3,
33    /// The hit, as the query's shape-level form reports one: for a sweep,
34    /// `point` is on the triangle and `normal` points from it to the swept
35    /// shape; for a ray, `normal` faces the ray.
36    pub hit: ShapeHit,
37}
38
39/// The buffers a mesh query descends its tree in, kept by whoever runs the
40/// query.
41#[derive(Debug, Default)]
42pub(crate) struct MeshScratch {
43    stack: Vec<u32>,
44    found: Vec<u32>,
45    hits: Vec<BvhHit>,
46}
47
48impl TriangleMesh {
49    /// The nearest triangle a ray in the mesh's frame crosses within its
50    /// bounds, from either side: [`ShapeHit::started_inside`] is never set,
51    /// since a surface has no inside. A ray running along a triangle's plane
52    /// does not strike it.
53    #[must_use]
54    pub fn cast_ray(&self, ray: &Ray) -> Option<MeshHit> {
55        self.cast_ray_with(ray, &mut MeshScratch::default())
56    }
57
58    pub(crate) fn cast_ray_with(&self, ray: &Ray, scratch: &mut MeshScratch) -> Option<MeshHit> {
59        self.bvh()
60            .traverse_ray_into(ray, &mut scratch.stack, &mut scratch.hits);
61        let mut best: Option<(f64, u32, DVec3)> = None;
62        for leaf in &scratch.hits {
63            if best.is_some_and(|(t, _, _)| leaf.t > t) {
64                continue;
65            }
66            let index = leaf.element_id;
67            let Some((t, weights)) =
68                ray_triangle(ray.origin, ray.dir, &self.corners(index as usize))
69            else {
70                continue;
71            };
72            if t < ray.t_min || t > ray.t_max {
73                continue;
74            }
75            if best.is_none_or(|(bt, bi, _)| t < bt || (t == bt && index < bi)) {
76                best = Some((t, index, weights));
77            }
78        }
79        let (t, triangle, barycentric) = best?;
80        let n = self.normal(triangle as usize);
81        Some(MeshHit {
82            triangle,
83            barycentric,
84            hit: ShapeHit {
85                t,
86                point: ray.origin + ray.dir * t,
87                normal: if ray.dir.dot(n) <= 0.0 { n } else { -n },
88                started_inside: false,
89                part: 0,
90            },
91        })
92    }
93
94    /// The first triangle a sphere of `radius` meets moving along `segment`,
95    /// in the mesh's frame, as [`crate::swept_sphere_vs_sphere`] reports one:
96    /// `t` in `[0, 1]`, a sweep that starts touching a triangle is a contact at
97    /// `t = 0` with [`ShapeHit::started_inside`].
98    #[must_use]
99    pub fn sweep_sphere(&self, segment: &Segment, radius: f64) -> Option<MeshHit> {
100        self.sweep_with(segment, radius, DVec3::ZERO, &mut MeshScratch::default())
101    }
102
103    /// [`sweep_sphere`](Self::sweep_sphere) for a capsule standing up the
104    /// mesh frame's `y` axis, `segment` the path of its centre, as
105    /// [`crate::swept_capsule_vs_aabb`] takes one.
106    #[must_use]
107    pub fn sweep_capsule(
108        &self,
109        segment: &Segment,
110        radius: f64,
111        half_height: f64,
112    ) -> Option<MeshHit> {
113        self.sweep_with(
114            segment,
115            radius,
116            DVec3::Y * half_height,
117            &mut MeshScratch::default(),
118        )
119    }
120
121    /// The first triangle a capsule of `radius` about the segment from
122    /// `-half` to `+half` meets moving along `segment` — a sphere when `half`
123    /// is zero.
124    pub(crate) fn sweep_with(
125        &self,
126        segment: &Segment,
127        radius: f64,
128        half: DVec3,
129        scratch: &mut MeshScratch,
130    ) -> Option<MeshHit> {
131        self.sweep_where_with(segment, radius, half, scratch, |_| true)
132    }
133
134    fn sweep_where_with(
135        &self,
136        segment: &Segment,
137        radius: f64,
138        half: DVec3,
139        scratch: &mut MeshScratch,
140        accept: impl Fn(&ShapeHit) -> bool,
141    ) -> Option<MeshHit> {
142        let (start, dir) = (segment.start, segment.end - segment.start);
143        let reach = DVec3::splat(radius) + half.abs();
144        let bounds = Aabb::new(
145            start.min(segment.end) - reach,
146            start.max(segment.end) + reach,
147        );
148        self.bvh()
149            .traverse_aabb_into(&bounds, &mut scratch.stack, &mut scratch.found);
150        let mut best: Option<MeshHit> = None;
151        for &index in &scratch.found {
152            let corners = self.corners(index as usize);
153            let normal = self.normal(index as usize);
154            let inside =
155                segment_triangle(start - half, start + half, &corners, normal).distance() <= radius;
156            let t = if inside {
157                Some(0.0)
158            } else {
159                sweep_into_triangle(start, dir, &corners, half, radius)
160            };
161            let Some(t) = t else { continue };
162            if !best.is_none_or(|hit| t < hit.hit.t || (t == hit.hit.t && index < hit.triangle)) {
163                continue;
164            }
165            let centre = start + dir * t;
166            let closest = segment_triangle(centre - half, centre + half, &corners, normal);
167            let away = closest.on_segment - closest.on_triangle.point;
168            let hit = ShapeHit {
169                t,
170                point: closest.on_triangle.point,
171                normal: facing(away, away.length(), normal, centre - corners[0]),
172                started_inside: inside,
173                part: 0,
174            };
175            if accept(&hit) {
176                best = Some(MeshHit {
177                    triangle: index,
178                    barycentric: closest.on_triangle.barycentric,
179                    hit,
180                });
181            }
182        }
183        best
184    }
185
186    /// Whether a sphere in the mesh's frame touches any triangle.
187    #[must_use]
188    pub fn overlaps_sphere(&self, sphere: &Sphere) -> bool {
189        self.overlaps_sphere_with(sphere, &mut MeshScratch::default())
190    }
191
192    pub(crate) fn overlaps_sphere_with(&self, sphere: &Sphere, scratch: &mut MeshScratch) -> bool {
193        self.bvh()
194            .traverse_aabb_into(&sphere.aabb(), &mut scratch.stack, &mut scratch.found);
195        scratch.found.iter().any(|&index| {
196            let corners = self.corners(index as usize);
197            (closest_on_triangle(sphere.centre, &corners).point - sphere.centre).length_squared()
198                <= sphere.radius * sphere.radius
199        })
200    }
201
202    /// Whether a box in the mesh's frame touches any triangle, exactly: by
203    /// the separating axis test of
204    /// Akenine-Möller's triangle–box overlap, not by bounds.
205    #[must_use]
206    pub fn overlaps_aabb(&self, aabb: &Aabb) -> bool {
207        self.overlaps_box_with(
208            aabb.centre(),
209            DQuat::IDENTITY,
210            aabb.extents() * 0.5,
211            &mut MeshScratch::default(),
212        )
213    }
214
215    pub(crate) fn overlaps_box_with(
216        &self,
217        centre: DVec3,
218        rotation: DQuat,
219        half: DVec3,
220        scratch: &mut MeshScratch,
221    ) -> bool {
222        let m = DMat3::from_quat(rotation);
223        let cuboid = Cuboid {
224            centre,
225            axes: [m.x_axis, m.y_axis, m.z_axis],
226            half,
227        };
228        let reach = DVec3::new(
229            cuboid.radius(DVec3::X),
230            cuboid.radius(DVec3::Y),
231            cuboid.radius(DVec3::Z),
232        );
233        self.bvh().traverse_aabb_into(
234            &Aabb::from_centre_half(centre, reach),
235            &mut scratch.stack,
236            &mut scratch.found,
237        );
238        scratch.found.iter().any(|&index| {
239            box_triangle_axes(
240                &cuboid,
241                &self.corners(index as usize),
242                self.normal(index as usize),
243            )
244            .into_iter()
245            .flatten()
246            .all(|axis| axis.separation <= 0.0)
247        })
248    }
249
250    /// How far a capsule standing up the mesh frame's `y` axis must move, and
251    /// which way, to leave the triangle it is deepest in — the push-out
252    /// [`crate::capsule_penetration_vs_aabb`] gives for a box — or `None` if it
253    /// is inside none.
254    ///
255    /// A capsule whose core crosses a triangle is pushed out along the
256    /// triangle's normal on the side its centre is, far enough for the end
257    /// behind it to clear the plane.
258    #[must_use]
259    pub fn capsule_penetration(&self, capsule: &Capsule) -> Option<Penetration> {
260        self.capsule_penetration_with(
261            capsule.centre,
262            DVec3::Y * capsule.half_height,
263            capsule.radius,
264            &mut MeshScratch::default(),
265        )
266    }
267
268    pub(crate) fn capsule_penetration_with(
269        &self,
270        centre: DVec3,
271        half: DVec3,
272        radius: f64,
273        scratch: &mut MeshScratch,
274    ) -> Option<Penetration> {
275        let mut deepest: Option<(f64, u32, DVec3)> = None;
276        self.for_each_capsule_contact(centre, half, radius, scratch, |index, depth, out| {
277            if deepest.is_none_or(|(d, i, _)| depth > d || (depth == d && index < i)) {
278                deepest = Some((depth, index, out));
279            }
280        });
281        deepest.map(|(depth, _, normal)| Penetration { normal, depth })
282    }
283
284    /// The push-out normal of every triangle a capsule of `radius` about
285    /// `centre - half ..= centre + half` is inside, in triangle order: what
286    /// [`capsule_penetration_with`](Self::capsule_penetration_with) chooses the
287    /// deepest of. A capsule wedged between two faces is inside both.
288    pub(crate) fn capsule_contact_normals_with(
289        &self,
290        centre: DVec3,
291        half: DVec3,
292        radius: f64,
293        scratch: &mut MeshScratch,
294        out: &mut Vec<DVec3>,
295    ) {
296        self.for_each_capsule_contact(centre, half, radius, scratch, |_, _, normal| {
297            out.push(normal);
298        });
299    }
300
301    /// Calls `visit(index, depth, normal)` for every triangle a capsule of
302    /// `radius` about `centre - half ..= centre + half` is inside: its depth,
303    /// and the unit push-out on the side the capsule's centre is, far enough
304    /// for the end behind the plane to clear it.
305    fn for_each_capsule_contact(
306        &self,
307        centre: DVec3,
308        half: DVec3,
309        radius: f64,
310        scratch: &mut MeshScratch,
311        mut visit: impl FnMut(u32, f64, DVec3),
312    ) {
313        let reach = DVec3::splat(radius) + half.abs();
314        self.bvh().traverse_aabb_into(
315            &Aabb::new(centre - reach, centre + reach),
316            &mut scratch.stack,
317            &mut scratch.found,
318        );
319        let (p0, p1) = (centre - half, centre + half);
320        for &index in &scratch.found {
321            let corners = self.corners(index as usize);
322            let normal = self.normal(index as usize);
323            let closest = segment_triangle(p0, p1, &corners, normal);
324            let away = closest.on_segment - closest.on_triangle.point;
325            let distance = away.length();
326            if distance >= radius {
327                continue;
328            }
329            let out = facing(away, distance, normal, centre - corners[0]);
330            let depth = if distance > 0.0 {
331                radius - distance
332            } else {
333                let behind = (-out.dot(p0 - corners[0]))
334                    .max(-out.dot(p1 - corners[0]))
335                    .max(0.0);
336                radius + behind
337            };
338            visit(index, depth, out);
339        }
340    }
341}
342
343/// The unit direction from a triangle to a shape `distance` away along
344/// `away`, or, where they touch, its normal on the side `offset` — the shape's
345/// centre less a corner — lies.
346fn facing(away: DVec3, distance: f64, normal: DVec3, offset: DVec3) -> DVec3 {
347    if distance > 0.0 {
348        away / distance
349    } else if normal.dot(offset) >= 0.0 {
350        normal
351    } else {
352        -normal
353    }
354}
355
356/// A mesh at a transform: what [`crate::PhysicsWorld`] keeps for one, and
357/// answers world queries through.
358#[derive(Debug, Clone)]
359pub(crate) struct PlacedMesh {
360    pub(crate) mesh: TriangleMesh,
361    pub(crate) transform: Transform,
362    /// Every triangle's world bounds, together.
363    pub(crate) bounds: Aabb,
364}
365
366impl PlacedMesh {
367    pub(crate) fn new(mesh: TriangleMesh, transform: Transform) -> Self {
368        let local = mesh.bounds();
369        let m = DMat3::from_quat(transform.rotation);
370        let half = local.extents() * 0.5;
371        let reach = DVec3::new(
372            m.x_axis.x.abs() * half.x + m.y_axis.x.abs() * half.y + m.z_axis.x.abs() * half.z,
373            m.x_axis.y.abs() * half.x + m.y_axis.y.abs() * half.y + m.z_axis.y.abs() * half.z,
374            m.x_axis.z.abs() * half.x + m.y_axis.z.abs() * half.y + m.z_axis.z.abs() * half.z,
375        );
376        let bounds = Aabb::from_centre_half(to_world(&transform, local.centre()), reach);
377        Self {
378            mesh,
379            transform,
380            bounds,
381        }
382    }
383
384    fn to_local(&self, point: DVec3) -> DVec3 {
385        self.transform.rotation.inverse() * (point - self.transform.position)
386    }
387
388    fn hit_to_world(&self, hit: ShapeHit) -> ShapeHit {
389        ShapeHit {
390            point: to_world(&self.transform, hit.point),
391            normal: self.transform.rotation * hit.normal,
392            ..hit
393        }
394    }
395
396    pub(crate) fn cast_ray(&self, ray: &Ray, scratch: &mut MeshScratch) -> Option<ShapeHit> {
397        let local = Ray {
398            origin: self.to_local(ray.origin),
399            dir: self.transform.rotation.inverse() * ray.dir,
400            ..*ray
401        };
402        let hit = self.mesh.cast_ray_with(&local, scratch)?.hit;
403        // The world point from the world ray, so it lies on it to the bit.
404        Some(ShapeHit {
405            point: ray.origin + ray.dir * hit.t,
406            normal: self.transform.rotation * hit.normal,
407            ..hit
408        })
409    }
410
411    /// A capsule of `radius` about `-half ..= +half`, turned with the world,
412    /// swept along `segment`: a sphere when `half` is zero.
413    pub(crate) fn sweep(
414        &self,
415        segment: &Segment,
416        radius: f64,
417        half: DVec3,
418        scratch: &mut MeshScratch,
419    ) -> Option<ShapeHit> {
420        self.sweep_where(segment, radius, half, scratch, |_| true)
421    }
422
423    /// The first accepted triangle contact, with world-space geometry.
424    pub(crate) fn sweep_where(
425        &self,
426        segment: &Segment,
427        radius: f64,
428        half: DVec3,
429        scratch: &mut MeshScratch,
430        accept: impl Fn(&ShapeHit) -> bool,
431    ) -> Option<ShapeHit> {
432        let local = Segment::new(self.to_local(segment.start), self.to_local(segment.end));
433        let half = self.transform.rotation.inverse() * half;
434        let hit = self
435            .mesh
436            .sweep_where_with(&local, radius, half, scratch, |hit| {
437                accept(&self.hit_to_world(*hit))
438            })?;
439        Some(self.hit_to_world(hit.hit))
440    }
441
442    /// A capsule of `radius` about `-half ..= +half`, turned with the world,
443    /// its centre following `path`: the first accepted triangle contact,
444    /// from either side. The predicate receives world-space geometry.
445    ///
446    /// Each triangle the path's bounds reach is advanced on alone, by the
447    /// segment-to-triangle distance the straight sweep's starting test uses;
448    /// of two met at the same time the lower-numbered triangle is kept, as
449    /// the straight sweep keeps it.
450    pub(crate) fn sweep_arc_where(
451        &self,
452        path: &AcceleratedPath,
453        radius: f64,
454        half: DVec3,
455        scratch: &mut MeshScratch,
456        accept: impl Fn(&ArcHit) -> bool,
457    ) -> Option<ArcHit> {
458        let turn = self.transform.rotation.inverse();
459        let local = path.in_frame(self.transform.position, turn);
460        let half = turn * half;
461        let reach = DVec3::splat(radius) + half.abs();
462        let bounds = local.bounds();
463        self.mesh.bvh().traverse_aabb_into(
464            &Aabb::new(bounds.min - reach, bounds.max + reach),
465            &mut scratch.stack,
466            &mut scratch.found,
467        );
468        let separation = |index: u32, p0: DVec3, p1: DVec3| {
469            let corners = self.mesh.corners(index as usize);
470            let normal = self.mesh.normal(index as usize);
471            let closest = segment_triangle(p0, p1, &corners, normal);
472            let away = closest.on_segment - closest.on_triangle.point;
473            let distance = away.length();
474            let centre = (p0 + p1) * 0.5;
475            (
476                distance - radius,
477                facing(away, distance, normal, centre - corners[0]),
478                closest.on_triangle.point,
479            )
480        };
481        let world_hit = |hit: ArcHit| ArcHit {
482            point: to_world(&self.transform, hit.point),
483            normal: self.transform.rotation * hit.normal,
484            ..hit
485        };
486        let mut best: Option<(u32, ArcHit)> = None;
487        for &index in &scratch.found {
488            let triangle = ContactShape::Triangle {
489                corners: self.mesh.corners(index as usize),
490                normal: self.mesh.normal(index as usize),
491                active_edges: self.mesh.active_edges(index as usize),
492            };
493            let Some(hit) = contact_where(
494                &local,
495                half,
496                radius,
497                |direction| support(&triangle, direction),
498                |p0, p1| {
499                    let (distance, normal, _) = separation(index, p0, p1);
500                    (distance, normal)
501                },
502                |time, _| {
503                    let centre = local.position_at(time);
504                    separation(index, centre - half, centre + half).2
505                },
506                |hit| accept(&world_hit(*hit)),
507            ) else {
508                continue;
509            };
510            let hit = world_hit(hit);
511            let time = hit.time;
512            if best.is_none_or(|(bi, bh)| time < bh.time || (time == bh.time && index < bi)) {
513                best = Some((index, hit));
514            }
515        }
516        best.map(|(_, hit)| hit)
517    }
518
519    /// How `sphere` overlaps the mesh — the capsule push-out for a capsule of
520    /// no height, against the triangle it is deepest in — or `None` if it is
521    /// inside none.
522    pub(crate) fn sphere_overlap(
523        &self,
524        sphere: &Sphere,
525        scratch: &mut MeshScratch,
526    ) -> Option<OverlapHit> {
527        let penetration =
528            self.turned_capsule_penetration(sphere.centre, DVec3::ZERO, sphere.radius, scratch)?;
529        Some(OverlapHit::from_penetration(sphere, penetration))
530    }
531
532    pub(crate) fn overlaps_aabb(&self, aabb: &Aabb, scratch: &mut MeshScratch) -> bool {
533        self.mesh.overlaps_box_with(
534            self.to_local(aabb.centre()),
535            self.transform.rotation.inverse(),
536            aabb.extents() * 0.5,
537            scratch,
538        )
539    }
540
541    pub(crate) fn capsule_penetration(
542        &self,
543        capsule: &Capsule,
544        scratch: &mut MeshScratch,
545    ) -> Option<Penetration> {
546        self.turned_capsule_penetration(
547            capsule.centre,
548            DVec3::Y * capsule.half_height,
549            capsule.radius,
550            scratch,
551        )
552    }
553
554    /// [`capsule_penetration`](Self::capsule_penetration) for a capsule of
555    /// `radius` about `centre - half ..= centre + half`, at any angle.
556    pub(crate) fn turned_capsule_penetration(
557        &self,
558        centre: DVec3,
559        half: DVec3,
560        radius: f64,
561        scratch: &mut MeshScratch,
562    ) -> Option<Penetration> {
563        let penetration = self.mesh.capsule_penetration_with(
564            self.to_local(centre),
565            self.transform.rotation.inverse() * half,
566            radius,
567            scratch,
568        )?;
569        Some(Penetration {
570            normal: self.transform.rotation * penetration.normal,
571            ..penetration
572        })
573    }
574
575    /// [`TriangleMesh::capsule_contact_normals_with`] for an upright capsule,
576    /// the normals in world space, appended to `out`.
577    pub(crate) fn capsule_contact_normals(
578        &self,
579        capsule: &Capsule,
580        scratch: &mut MeshScratch,
581        out: &mut Vec<DVec3>,
582    ) {
583        let first = out.len();
584        self.mesh.capsule_contact_normals_with(
585            self.to_local(capsule.centre),
586            self.transform.rotation.inverse() * (DVec3::Y * capsule.half_height),
587            capsule.radius,
588            scratch,
589            out,
590        );
591        for normal in &mut out[first..] {
592            *normal = self.transform.rotation * *normal;
593        }
594    }
595}
596
597fn to_world(transform: &Transform, local: DVec3) -> DVec3 {
598    transform.position + transform.rotation * local
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604
605    /// Two triangles side by side in the floor, each a unit right triangle:
606    /// triangle 0 over `x ∈ [0, 1]` and triangle 1 over `x ∈ [2, 3]`.
607    fn two() -> TriangleMesh {
608        TriangleMesh::new(
609            &[
610                DVec3::new(0.0, 0.0, 0.0),
611                DVec3::new(0.0, 0.0, 1.0),
612                DVec3::new(1.0, 0.0, 0.0),
613                DVec3::new(2.0, 0.0, 0.0),
614                DVec3::new(2.0, 0.0, 1.0),
615                DVec3::new(3.0, 0.0, 0.0),
616            ],
617            &[[0, 1, 2], [3, 4, 5]],
618        )
619        .unwrap()
620    }
621
622    fn close(a: DVec3, b: DVec3) -> bool {
623        (a - b).length() < 1e-12
624    }
625
626    /// **A ray names the triangle it struck and where**: straight down at
627    /// `(2.25, ·, 0.25)` it crosses triangle 1 at weights `(½, ¼, ¼)` of its
628    /// corners `(2,0,0)`, `(2,0,1)`, `(3,0,0)`; from below the normal faces
629    /// down.
630    #[test]
631    fn a_ray_names_the_triangle_and_the_point() {
632        let mesh = two();
633        let hit = mesh
634            .cast_ray(&Ray::new(DVec3::new(2.25, 3.0, 0.25), -DVec3::Y))
635            .unwrap();
636        assert_eq!(hit.triangle, 1);
637        assert!(
638            close(hit.barycentric, DVec3::new(0.5, 0.25, 0.25)),
639            "{hit:?}"
640        );
641        assert!((hit.hit.t - 3.0).abs() < 1e-15);
642        assert_eq!(hit.hit.normal, DVec3::Y);
643        let below = mesh
644            .cast_ray(&Ray::new(DVec3::new(0.25, -1.0, 0.25), DVec3::Y))
645            .unwrap();
646        assert_eq!(below.triangle, 0);
647        assert_eq!(below.hit.normal, -DVec3::Y);
648        assert!(
649            mesh.cast_ray(&Ray::new(DVec3::new(1.5, 3.0, 0.25), -DVec3::Y))
650                .is_none(),
651            "between the two"
652        );
653    }
654
655    /// **A sphere dropped on a triangle's face lands a radius above it**, and
656    /// the contact is under its centre; one dropped past the hypotenuse of
657    /// triangle 0 lands on that edge.
658    #[test]
659    fn a_swept_sphere_lands_on_the_face_or_the_edge() {
660        let mesh = two();
661        let hit = mesh
662            .sweep_sphere(
663                &Segment::new(DVec3::new(2.25, 2.0, 0.25), DVec3::new(2.25, 0.0, 0.25)),
664                0.5,
665            )
666            .unwrap();
667        assert_eq!(hit.triangle, 1);
668        assert!((hit.hit.t - 0.75).abs() < 1e-12, "{hit:?}");
669        assert!(close(hit.hit.point, DVec3::new(2.25, 0.0, 0.25)), "{hit:?}");
670        assert!(close(hit.barycentric, DVec3::new(0.5, 0.25, 0.25)));
671        assert!(close(hit.hit.normal, DVec3::Y));
672        assert!(!hit.hit.started_inside);
673
674        // Over (0.75, ·, 0.75), 0.25√2 past the hypotenuse x + z = 1, whose
675        // nearest point is (0.5, 0, 0.5): radius 0.5 touches it at height
676        // √(0.25 − 0.125).
677        let hit = mesh
678            .sweep_sphere(
679                &Segment::new(DVec3::new(0.75, 2.0, 0.75), DVec3::new(0.75, 0.0, 0.75)),
680                0.5,
681            )
682            .unwrap();
683        assert_eq!(hit.triangle, 0);
684        let height = 0.125f64.sqrt();
685        assert!((hit.hit.t - (2.0 - height) / 2.0).abs() < 1e-12, "{hit:?}");
686        assert!(close(hit.hit.point, DVec3::new(0.5, 0.0, 0.5)), "{hit:?}");
687        assert!(close(hit.barycentric, DVec3::new(0.0, 0.5, 0.5)), "{hit:?}");
688    }
689
690    /// **A capsule swept sideways into a wall of triangles** meets it with
691    /// its flank, and one that starts touching is a contact at zero.
692    #[test]
693    fn a_swept_capsule_meets_with_its_flank_or_starts_touching() {
694        // A wall in x = 0, facing -x: y, z ∈ [0, 2].
695        let wall = TriangleMesh::new(
696            &[
697                DVec3::new(0.0, 0.0, 0.0),
698                DVec3::new(0.0, 2.0, 0.0),
699                DVec3::new(0.0, 2.0, 2.0),
700                DVec3::new(0.0, 0.0, 2.0),
701            ],
702            &[[0, 2, 1], [0, 3, 2]],
703        )
704        .unwrap();
705        assert_eq!(wall.normal(0), -DVec3::X);
706        let hit = wall
707            .sweep_capsule(
708                &Segment::new(DVec3::new(-3.0, 1.0, 1.0), DVec3::new(1.0, 1.0, 1.0)),
709                0.5,
710                0.5,
711            )
712            .unwrap();
713        // The flank, 0.5 out, touches with the centre at x = -0.5.
714        assert!((hit.hit.t - 0.625).abs() < 1e-12, "{hit:?}");
715        assert!(close(hit.hit.normal, -DVec3::X), "{hit:?}");
716        let touching = wall
717            .sweep_capsule(
718                &Segment::new(DVec3::new(-0.4, 1.0, 1.0), DVec3::new(-1.0, 1.0, 1.0)),
719                0.5,
720                0.5,
721            )
722            .unwrap();
723        assert_eq!(touching.hit.t, 0.0);
724        assert!(touching.hit.started_inside);
725    }
726
727    /// Overlaps are exact: a box under a triangle's hypotenuse overlaps its
728    /// bounds and not the triangle, and a sphere overlaps by distance.
729    #[test]
730    fn overlaps_are_decided_by_the_triangles_not_their_bounds() {
731        let mesh = two();
732        let past_hypotenuse = Aabb::from_centre_half(DVec3::new(0.9, 0.0, 0.9), DVec3::splat(0.1));
733        assert!(!mesh.overlaps_aabb(&past_hypotenuse));
734        assert!(mesh.overlaps_aabb(&Aabb::from_centre_half(
735            DVec3::new(0.3, 0.05, 0.3),
736            DVec3::splat(0.1)
737        )));
738        assert!(!mesh.overlaps_sphere(&Sphere::new(DVec3::new(0.9, 0.0, 0.9), 0.1)));
739        assert!(mesh.overlaps_sphere(&Sphere::new(DVec3::new(0.3, 0.1, 0.3), 0.1)));
740    }
741
742    /// A capsule sunk into the floor is pushed up by its depth; a placed mesh
743    /// answers in the world.
744    #[test]
745    fn a_sunk_capsule_is_pushed_out_along_the_normal() {
746        let mesh = two();
747        let capsule = Capsule::new(DVec3::new(0.3, 0.9, 0.3), 0.25, 0.75);
748        let penetration = mesh.capsule_penetration(&capsule).unwrap();
749        assert!(close(penetration.normal, DVec3::Y));
750        assert!((penetration.depth - 0.1).abs() < 1e-12, "{penetration:?}");
751
752        // Turned a quarter about x, the floor is the wall z = 0 facing +z, and
753        // moved 5 along x.
754        let turn = crate::rotation_from_scaled_axis(DVec3::X * core::f64::consts::FRAC_PI_2);
755        let placed = PlacedMesh::new(mesh, Transform::new(DVec3::new(5.0, 0.0, 0.0), turn));
756        let mut scratch = MeshScratch::default();
757        let hit = placed
758            .cast_ray(
759                &Ray::new(DVec3::new(5.25, -0.25, -3.0), DVec3::Z),
760                &mut scratch,
761            )
762            .unwrap();
763        assert!((hit.t - 3.0).abs() < 1e-12, "{hit:?}");
764        assert!(close(hit.normal, -DVec3::Z), "{hit:?}");
765        // The turned floor is flat to within the rotation's rounding.
766        assert!(
767            placed
768                .bounds
769                .inflated(1e-12)
770                .contains(&Aabb::new(hit.point, hit.point))
771        );
772    }
773}