Skip to main content

crcbl_phys/
query.rs

1//! Shape-level intersection queries: ray-vs-shape and swept-sphere TOI.
2//!
3//! These operate on the collider shapes directly (sphere, box, capsule) rather
4//! than on the BVH. They compute exact hit points, normals, and times of impact.
5//!
6//! The functions named for an AABB take a box whose axes are the world's; the
7//! ones named for a box ([`ray_vs_box`] and its siblings) take a
8//! [`BoxCollider`](crate::BoxCollider), which may be turned, and are what the
9//! query world answers its boxes with.
10
11mod arc;
12mod arc_selection;
13mod boxes;
14mod capsules;
15mod sphere_overlap;
16
17use crate::broadphase::Ray;
18use crate::collider::{Aabb, Capsule, Sphere};
19use glam::DVec3;
20
21pub use self::arc::{ARC_MAX_ITERATIONS, ARC_TIME_TOLERANCE, AcceleratedPath, ArcHit};
22pub(crate) use self::arc::{
23    arc_capsule_vs_box, arc_capsule_vs_sphere, arc_capsule_vs_turned_capsule, support,
24};
25pub(crate) use self::arc_selection::contact_where;
26pub use self::boxes::{
27    aabb_overlaps_box, capsule_penetration_vs_box, ray_vs_box, sphere_overlap_vs_box,
28    sphere_overlaps_box, swept_capsule_vs_box, swept_sphere_vs_box,
29};
30pub(crate) use self::boxes::{contact_box, nearest_on_box};
31pub(crate) use self::capsules::{
32    TurnedCapsule, capsule_penetration_vs_turned_capsule, ray_vs_turned_capsule,
33    sphere_overlap_vs_turned_capsule, swept_capsule_vs_turned_capsule,
34    swept_sphere_vs_turned_capsule,
35};
36pub use self::sphere_overlap::{
37    OverlapHit, sphere_overlap_vs_aabb, sphere_overlap_vs_capsule, sphere_overlap_vs_sphere,
38};
39
40// ---------------------------------------------------------------------------
41// Overlap queries
42// ---------------------------------------------------------------------------
43
44/// Test whether two spheres overlap — the sphere is inside the other by more
45/// than nothing, so touching does not count.
46///
47/// The yes-or-no form of [`sphere_overlap_vs_sphere`], and answered by it, so
48/// the two can never disagree at the boundary.
49#[must_use]
50pub fn sphere_overlaps_sphere(a: &Sphere, b: &Sphere) -> bool {
51    sphere_overlap_vs_sphere(a, b).is_some()
52}
53
54/// Test whether a sphere overlaps an AABB; touching does not count. The
55/// yes-or-no form of [`sphere_overlap_vs_aabb`], and answered by it.
56#[must_use]
57pub fn sphere_overlaps_aabb(sphere: &Sphere, aabb: &Aabb) -> bool {
58    sphere_overlap_vs_aabb(sphere, aabb).is_some()
59}
60
61/// Test whether a sphere overlaps a Y-aligned capsule; touching does not
62/// count. The yes-or-no form of [`sphere_overlap_vs_capsule`], and answered by
63/// it.
64#[must_use]
65pub fn sphere_overlaps_capsule(sphere: &Sphere, capsule: &Capsule) -> bool {
66    sphere_overlap_vs_capsule(sphere, capsule).is_some()
67}
68
69/// The point on a capsule's axis segment (bottom cap centre → top cap centre)
70/// closest to `point`.
71///
72/// The capsule surface is exactly the set of points at distance `radius` from
73/// this segment, so this is the anchor for every capsule normal and distance
74/// in this module. A degenerate (zero-height) capsule returns its centre.
75#[inline]
76#[must_use]
77fn closest_point_on_capsule_axis(capsule: &Capsule, point: DVec3) -> DVec3 {
78    let bot = capsule.bottom();
79    let seg = capsule.top() - bot;
80    let len_sq = seg.length_squared();
81    if len_sq <= 0.0 {
82        return capsule.centre;
83    }
84    bot + seg * ((point - bot).dot(seg) / len_sq).clamp(0.0, 1.0)
85}
86
87// ---------------------------------------------------------------------------
88// Hit result
89// ---------------------------------------------------------------------------
90
91/// The result of a ray or sweep query against a single shape.
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub struct ShapeHit {
94    /// Parametric distance along the ray at the hit point.
95    pub t: f64,
96    /// World-space position of the hit.
97    pub point: DVec3,
98    /// Unit normal at the hit point, pointing **away** from the surface the ray
99    /// struck.  For swept-sphere queries this is the contact normal.
100    pub normal: DVec3,
101    /// Whether the query's accepted interval *begins* inside the shape — for
102    /// a ray that is `origin + dir * t_min`, for a sweep the sweep's start
103    /// position. A hit with this set is a resolution case (push out), not an
104    /// approach.
105    pub started_inside: bool,
106    /// Which part of the collider was struck: for a compound
107    /// ([`crate::PhysicsWorld::add_compound`]) the index of the part in its
108    /// [`CompoundShape::parts`](crate::CompoundShape::parts), and `0` for
109    /// every other collider and from every shape-level function here.
110    pub part: usize,
111}
112
113// ---------------------------------------------------------------------------
114// Shared root selection
115// ---------------------------------------------------------------------------
116
117/// What a query reports when its accepted interval starts inside the shape.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119enum InsideRule {
120    /// Report the far root: the surface the ray leaves through. Ray casts use
121    /// this — a ray fired from inside a volume strikes its far wall.
122    Exit,
123    /// Report the start of the interval: the shapes are already touching, so
124    /// the time of impact is now. Sweeps use this.
125    Contact,
126}
127
128/// Solve `a·t² + b·t + c = 0`, returning the roots in ascending order.
129///
130/// `None` means no real intersection: either the quadratic is degenerate
131/// (`a` at or below the noise floor — a ray with no length along the axis
132/// being solved) or the discriminant is negative (a miss).
133#[inline]
134fn solve_quadratic(a: f64, b: f64, c: f64) -> Option<(f64, f64)> {
135    if a <= f64::EPSILON {
136        return None;
137    }
138    let disc = b * b - 4.0 * a * c;
139    if disc < 0.0 {
140        return None;
141    }
142    let sqrt_disc = disc.sqrt();
143    let inv_2a = 0.5 / a;
144    Some(((-b - sqrt_disc) * inv_2a, (-b + sqrt_disc) * inv_2a))
145}
146
147/// The one root-selection rule in this module: every quadratic and every AABB
148/// slab test resolves its `(near, far)` interval through here.
149///
150/// `near..=far` is the interval over which the ray is inside the shape and
151/// `lo..=hi` the interval the caller accepts. The result is the reported `t`
152/// and whether the accepted interval began inside the shape.
153///
154/// * Disjoint intervals are a miss.
155/// * A `near` inside `lo..=hi` is the hit, from outside the shape.
156/// * Otherwise `lo` is already inside the shape and `rule` decides what to
157///   report. Note this covers a caller that merely *advanced* `lo` past the
158///   entry point (`Ray::with_bounds`) as well as one that genuinely starts
159///   within the shape — both must still produce a hit.
160#[inline]
161fn select_hit(near: f64, far: f64, lo: f64, hi: f64, rule: InsideRule) -> Option<(f64, bool)> {
162    if near > far || far < lo || near > hi {
163        return None;
164    }
165    if near >= lo {
166        return Some((near, false));
167    }
168    match rule {
169        InsideRule::Exit if far <= hi => Some((far, true)),
170        InsideRule::Exit => None,
171        InsideRule::Contact => Some((lo, true)),
172    }
173}
174
175/// The outward unit normal of the box face nearest to `point`, and how far
176/// `point` is from that face.
177///
178/// Doubles as the surface normal for a hit lying on a face (distance zero) and
179/// as the minimum-penetration escape axis for a point inside the box, so
180/// callers never have to fabricate a normal when a query starts overlapping.
181/// The distance is what a caller pushing that point back out has to travel.
182#[must_use]
183fn aabb_escape(aabb: &Aabb, point: DVec3) -> (DVec3, f64) {
184    let faces = [
185        ((point.x - aabb.min.x).abs(), DVec3::NEG_X),
186        ((aabb.max.x - point.x).abs(), DVec3::X),
187        ((point.y - aabb.min.y).abs(), DVec3::NEG_Y),
188        ((aabb.max.y - point.y).abs(), DVec3::Y),
189        ((point.z - aabb.min.z).abs(), DVec3::NEG_Z),
190        ((aabb.max.z - point.z).abs(), DVec3::Z),
191    ];
192    let mut best = faces[0];
193    for &face in &faces[1..] {
194        if face.0 < best.0 {
195            best = face;
196        }
197    }
198    (best.1, best.0)
199}
200
201// ---------------------------------------------------------------------------
202// Ray vs sphere
203// ---------------------------------------------------------------------------
204
205/// Intersect a ray with a sphere. Returns the nearest hit within the ray's
206/// bounds, or `None` if the ray misses entirely (including if the sphere is
207/// behind the ray origin).
208///
209/// A ray whose accepted interval starts inside the sphere hits the far surface
210/// and reports [`ShapeHit::started_inside`].
211#[must_use]
212pub fn ray_vs_sphere(ray: &Ray, sphere: &Sphere) -> Option<ShapeHit> {
213    let oc = ray.origin - sphere.centre;
214    let a = ray.dir.dot(ray.dir);
215    let b = 2.0 * oc.dot(ray.dir);
216    let c = oc.dot(oc) - sphere.radius * sphere.radius;
217    let (near, far) = solve_quadratic(a, b, c)?;
218    let (t, started_inside) = select_hit(near, far, ray.t_min, ray.t_max, InsideRule::Exit)?;
219    let point = ray.origin + ray.dir * t;
220    let to_centre = point - sphere.centre;
221    let normal = if to_centre.length_squared() > 0.0 {
222        to_centre.normalize()
223    } else {
224        DVec3::Y
225    };
226    Some(ShapeHit {
227        t,
228        point,
229        normal,
230        started_inside,
231        part: 0,
232    })
233}
234
235// ---------------------------------------------------------------------------
236// Ray vs AABB (axis-aligned box)
237// ---------------------------------------------------------------------------
238
239/// Intersect a ray with an axis-aligned bounding box (treated as a solid box).
240/// Returns the nearest hit within the ray's bounds, or `None` if the ray
241/// misses entirely.
242///
243/// A ray whose accepted interval starts inside the box hits the far face and
244/// reports [`ShapeHit::started_inside`].
245#[must_use]
246pub fn ray_vs_aabb(ray: &Ray, aabb: &Aabb) -> Option<ShapeHit> {
247    let inv_dir = ray.dir.recip();
248    let dir_is_neg = [ray.dir.x < 0.0, ray.dir.y < 0.0, ray.dir.z < 0.0];
249
250    let (near, far) = aabb.ray_slab(ray.origin, inv_dir, dir_is_neg)?;
251    let (t, started_inside) = select_hit(near, far, ray.t_min, ray.t_max, InsideRule::Exit)?;
252
253    let point = ray.origin + ray.dir * t;
254    let normal = aabb_escape(aabb, point).0;
255
256    Some(ShapeHit {
257        t,
258        point,
259        normal,
260        started_inside,
261        part: 0,
262    })
263}
264
265// ---------------------------------------------------------------------------
266// Ray vs capsule
267// ---------------------------------------------------------------------------
268
269/// Intersect a ray with a Y-aligned capsule. Returns the nearest hit within
270/// the ray's bounds, or `None`.
271///
272/// The capsule surface is the union of three pieces — the cylindrical band
273/// between the cap centres, the top hemisphere above the top cap centre, and
274/// the bottom hemisphere below the bottom one. Every root of all three is
275/// tested, each is kept only if it lands on the piece that owns it (the rest
276/// of each cap sphere lies *inside* the capsule), and the nearest survivor
277/// wins. Testing the pieces in sequence instead would return a far-side
278/// cylinder exit in preference to a nearer cap hit.
279#[must_use]
280pub fn ray_vs_capsule(ray: &Ray, capsule: &Capsule) -> Option<ShapeHit> {
281    let bot = capsule.bottom();
282    let top = capsule.top();
283    let radius_sq = capsule.radius * capsule.radius;
284
285    let mut best = f64::INFINITY;
286    let mut consider = |t: f64| {
287        if t >= ray.t_min && t <= ray.t_max && t < best {
288            best = t;
289        }
290    };
291
292    // Cylindrical band: solve in the XZ plane, keep roots between the caps.
293    let oc_xz = DVec3::new(
294        ray.origin.x - capsule.centre.x,
295        0.0,
296        ray.origin.z - capsule.centre.z,
297    );
298    let dir_xz = DVec3::new(ray.dir.x, 0.0, ray.dir.z);
299    if let Some(roots) = solve_quadratic(
300        dir_xz.dot(dir_xz),
301        2.0 * oc_xz.dot(dir_xz),
302        oc_xz.dot(oc_xz) - radius_sq,
303    ) {
304        for t in [roots.0, roots.1] {
305            let y = ray.origin.y + ray.dir.y * t;
306            if y >= bot.y && y <= top.y {
307                consider(t);
308            }
309        }
310    }
311
312    // Hemispherical caps: keep only the roots beyond the cap centre's plane.
313    let a = ray.dir.dot(ray.dir);
314    for (cap, is_top) in [(top, true), (bot, false)] {
315        let oc = ray.origin - cap;
316        if let Some(roots) = solve_quadratic(a, 2.0 * oc.dot(ray.dir), oc.dot(oc) - radius_sq) {
317            for t in [roots.0, roots.1] {
318                let y = ray.origin.y + ray.dir.y * t;
319                if (is_top && y >= top.y) || (!is_top && y <= bot.y) {
320                    consider(t);
321                }
322            }
323        }
324    }
325
326    if !best.is_finite() {
327        return None;
328    }
329
330    let point = ray.origin + ray.dir * best;
331    let axis_point = closest_point_on_capsule_axis(capsule, point);
332    let radial = point - axis_point;
333    let normal = if radial.length_squared() > 0.0 {
334        radial.normalize()
335    } else {
336        DVec3::Y
337    };
338
339    // The interval starts inside the capsule when the point at `t_min` is
340    // within `radius` of the axis segment.
341    let entry = ray.origin + ray.dir * ray.t_min;
342    let started_inside =
343        (entry - closest_point_on_capsule_axis(capsule, entry)).length_squared() <= radius_sq;
344
345    Some(ShapeHit {
346        t: best,
347        point,
348        normal,
349        started_inside,
350        part: 0,
351    })
352}
353
354// ---------------------------------------------------------------------------
355// Swept sphere vs sphere
356// ---------------------------------------------------------------------------
357
358/// Compute the time of impact (TOI) for a sphere moving along a segment against
359/// a static target sphere. Returns the earliest time in `[0, 1]` and contact
360/// details, or `None` if no collision occurs.
361///
362/// The `swept` sphere moves from `segment.start` to `segment.end`; the `target`
363/// sphere is static at its position.
364///
365/// A sweep that is already overlapping at `segment.start` reports `t = 0` and
366/// [`ShapeHit::started_inside`] — including when it is overlapping for the
367/// whole sweep — so a body resting inside another still produces a contact.
368#[must_use]
369pub fn swept_sphere_vs_sphere(
370    segment: &crate::broadphase::Segment,
371    swept_radius: f64,
372    target: &Sphere,
373) -> Option<ShapeHit> {
374    let dir = segment.end - segment.start;
375    let combined_r = swept_radius + target.radius;
376    let oc = segment.start - target.centre;
377
378    // A zero or near-stationary sweep (dir·dir at or below the quadratic
379    // floor) takes the overlap branch: `solve_quadratic` rejects `a <= EPSILON`
380    // outright, so anything shorter would be reported as a miss instead of the
381    // documented resting contact.
382    if dir.length_squared() <= f64::EPSILON {
383        // Stationary sweep: just test sphere-sphere overlap.
384        let dist = oc.length();
385        if dist <= combined_r {
386            let overlap = combined_r - dist;
387            let normal = if dist > 0.0 { oc / dist } else { DVec3::Y };
388            return Some(ShapeHit {
389                t: 0.0,
390                point: segment.start - normal * (swept_radius - overlap * 0.5),
391                normal,
392                started_inside: true,
393                part: 0,
394            });
395        }
396        return None;
397    }
398
399    // Solve: |oc + t * dir| = combined_r
400    // a = dir·dir, b = 2 * oc·dir, c = oc·oc - combined_r²
401    let (near, far) = solve_quadratic(
402        dir.dot(dir),
403        2.0 * oc.dot(dir),
404        oc.dot(oc) - combined_r * combined_r,
405    )?;
406    let (t, started_inside) = select_hit(near, far, 0.0, 1.0, InsideRule::Contact)?;
407
408    let point_on_swept = segment.start + dir * t;
409    let to_target = point_on_swept - target.centre;
410    let normal = if to_target.length_squared() > 0.0 {
411        to_target.normalize()
412    } else {
413        DVec3::Y
414    };
415    let contact_point = target.centre + normal * target.radius;
416
417    Some(ShapeHit {
418        t,
419        point: contact_point,
420        normal,
421        started_inside,
422        part: 0,
423    })
424}
425
426// ---------------------------------------------------------------------------
427// Swept sphere vs AABB
428// ---------------------------------------------------------------------------
429
430pub use aabb_sweep::swept_sphere_vs_aabb;
431
432#[path = "query/aabb_sweep.rs"]
433mod aabb_sweep;
434
435// ---------------------------------------------------------------------------
436// Swept sphere vs capsule
437// ---------------------------------------------------------------------------
438
439/// Compute the TOI for a sphere moving along a segment against a static
440/// Y-aligned capsule.
441///
442/// The capsule is inflated by `swept_radius` and the segment (sphere centre
443/// path) is tested against the inflated shape via ray-vs-capsule.
444///
445/// As with the sphere and AABB sweeps, a sweep that starts already overlapping
446/// reports `t = 0`, [`ShapeHit::started_inside`], and the normal pointing out
447/// of the capsule along its nearest axis point — not out of its centre, which
448/// would push a character along a tall capsule instead of away from it.
449#[must_use]
450pub fn swept_sphere_vs_capsule(
451    segment: &crate::broadphase::Segment,
452    swept_radius: f64,
453    capsule: &Capsule,
454) -> Option<ShapeHit> {
455    let combined = swept_radius + capsule.radius;
456
457    // Already overlapping at the start of the sweep: contact is now.
458    let axis_point = closest_point_on_capsule_axis(capsule, segment.start);
459    let radial = segment.start - axis_point;
460    let dist_sq = radial.length_squared();
461    if dist_sq <= combined * combined {
462        let dist = dist_sq.sqrt();
463        let normal = if dist > 0.0 { radial / dist } else { DVec3::Y };
464        return Some(ShapeHit {
465            t: 0.0,
466            point: axis_point + normal * capsule.radius,
467            normal,
468            started_inside: true,
469            part: 0,
470        });
471    }
472
473    let dir = segment.end - segment.start;
474    if dir.length_squared() <= 0.0 {
475        return None; // Stationary and not overlapping.
476    }
477
478    // Inflate the capsule by the swept sphere radius.  The segment (sphere
479    // centre path) vs the inflated capsule is a ray-vs-capsule test.
480    let inflated = Capsule::new(capsule.centre, combined, capsule.half_height);
481    let ray = Ray::new(segment.start, dir).with_bounds(0.0, 1.0);
482
483    ray_vs_capsule(&ray, &inflated).map(|hit| {
484        // Back out the contact point on the original capsule surface.
485        let contact_point = hit.point - hit.normal * swept_radius;
486        ShapeHit {
487            t: hit.t, // already in [0, 1] because t_max = 1.0
488            point: contact_point,
489            normal: hit.normal,
490            started_inside: hit.started_inside,
491            part: 0,
492        }
493    })
494}
495
496// ---------------------------------------------------------------------------
497// Swept capsule
498// ---------------------------------------------------------------------------
499
500// The swept-capsule tests below are the swept-*sphere* tests against a target
501// that has already absorbed the capsule's axis.
502//
503// Sweeping shape `A` against a static `B` asks whether `A`'s origin path enters
504// the Minkowski sum `B ⊕ (−A)`. A capsule is `axis ⊕ ball(r)` with the axis
505// symmetric about the capsule centre, so `−A = A` and the sum is
506// `(B ⊕ axis) ⊕ ball(r)`: a *ball* of the capsule's radius following the capsule
507// centre, against a target grown along Y by the capsule's half-height. Growing
508// along Y is closed over the shapes this crate has — a sphere becomes a capsule,
509// a capsule a taller capsule, an AABB a taller AABB — which is what makes the
510// reduction exact rather than an approximation, and it is exact only because
511// every capsule here is Y-aligned.
512//
513// The time of impact, the contact normal and `started_inside` therefore come
514// straight back from the swept-sphere call. Only [`ShapeHit::point`] has to be
515// undone: the sphere test reports a point on the *grown* target, and each
516// function below maps it back onto the real one.
517
518/// Compute the TOI for a Y-aligned capsule moving along a segment against a
519/// static sphere. `segment` is the path of the capsule's **centre**.
520///
521/// A sphere grown along Y is a capsule, so this is [`swept_sphere_vs_capsule`]
522/// against that proxy — see the note above.
523///
524/// As with the sphere sweeps, a sweep that starts already overlapping reports
525/// `t = 0` and [`ShapeHit::started_inside`].
526#[must_use]
527pub fn swept_capsule_vs_sphere(
528    segment: &crate::broadphase::Segment,
529    swept_radius: f64,
530    swept_half_height: f64,
531    target: &Sphere,
532) -> Option<ShapeHit> {
533    let proxy = Capsule::new(target.centre, target.radius, swept_half_height);
534    let hit = swept_sphere_vs_capsule(segment, swept_radius, &proxy)?;
535    // The proxy's surface is a capsule's and the contact is on the real sphere,
536    // which the normal already points out of.
537    Some(ShapeHit {
538        point: target.centre + hit.normal * target.radius,
539        ..hit
540    })
541}
542
543/// Compute the TOI for a Y-aligned capsule moving along a segment against a
544/// static AABB. `segment` is the path of the capsule's **centre**.
545///
546/// An AABB grown along Y is an AABB, so this is a sphere swept against that
547/// proxy — see the note above — and **against the proxy rounded by the
548/// radius**, not inflated: a capsule passing within its radius of a top edge
549/// meets the edge's curve, with the normal from the edge towards its axis,
550/// where an inflated box would hand it the top face and a flat normal, and a
551/// character standing a radius past the edge would stand on air.
552///
553/// As with the sphere sweeps, a sweep that starts already overlapping reports
554/// `t = 0`, [`ShapeHit::started_inside`] and the minimum-penetration face
555/// normal.
556#[must_use]
557pub fn swept_capsule_vs_aabb(
558    segment: &crate::broadphase::Segment,
559    swept_radius: f64,
560    swept_half_height: f64,
561    target: &Aabb,
562) -> Option<ShapeHit> {
563    // Checked before the growth and not after: a box inverted only on Y reads
564    // as non-empty once Y has been grown, and would then be swept against as
565    // though it were a real box.
566    if target.is_empty() {
567        return None;
568    }
569    let grown = Aabb::new(
570        target.min - DVec3::Y * swept_half_height,
571        target.max + DVec3::Y * swept_half_height,
572    );
573    let hit = aabb_sweep::swept_sphere_vs_rounded_aabb(segment, swept_radius, &grown)?;
574    // The contact is on `grown`, so only Y can be off the real box; clamping
575    // again puts it back on the face or edge that was grown.
576    Some(ShapeHit {
577        point: hit.point.clamp(target.min, target.max),
578        ..hit
579    })
580}
581
582/// Compute the TOI for a Y-aligned capsule moving along a segment against a
583/// static Y-aligned capsule. `segment` is the path of the moving capsule's
584/// **centre**.
585///
586/// A capsule grown along Y is a capsule with the half-heights summed, so this
587/// is [`swept_sphere_vs_capsule`] against that proxy — see the note above.
588///
589/// As with the sphere sweeps, a sweep that starts already overlapping reports
590/// `t = 0` and [`ShapeHit::started_inside`].
591#[must_use]
592pub fn swept_capsule_vs_capsule(
593    segment: &crate::broadphase::Segment,
594    swept_radius: f64,
595    swept_half_height: f64,
596    target: &Capsule,
597) -> Option<ShapeHit> {
598    let proxy = Capsule::new(
599        target.centre,
600        target.radius,
601        target.half_height + swept_half_height,
602    );
603    let hit = swept_sphere_vs_capsule(segment, swept_radius, &proxy)?;
604    // The proxy is taller than the target, so the axis point the sphere test
605    // anchored on is not one of the target's. Re-anchor on the real axis, which
606    // the normal points out of.
607    let centre_at_hit = segment.start + (segment.end - segment.start) * hit.t;
608    let axis_point = closest_point_on_capsule_axis(target, centre_at_hit);
609    Some(ShapeHit {
610        point: axis_point + hit.normal * target.radius,
611        ..hit
612    })
613}
614
615// ---------------------------------------------------------------------------
616// Capsule penetration
617// ---------------------------------------------------------------------------
618
619/// How far an overlapping shape has to move, and which way, to stop
620/// overlapping.
621///
622/// This is what a sweep cannot answer. A sweep that starts already overlapping
623/// reports the contact at `t = 0` and stops there, because there is no
624/// *earlier* time to report; the depth is a different measurement, and a
625/// character that woke up inside the world needs it to get out. PhysX exposes
626/// the same pair separately (`PxSweep*` against `PxComputePenetration`), and so
627/// does Unity (`CapsuleCast` against `Physics.ComputePenetration`).
628#[derive(Debug, Clone, Copy, PartialEq)]
629pub struct Penetration {
630    /// Unit direction to translate the overlapping shape along, pointing out of
631    /// the shape it is inside.
632    pub normal: DVec3,
633    /// How far along `normal` the translation has to go. Always positive — a
634    /// pair that merely touches is not a penetration and is reported as `None`.
635    pub depth: f64,
636}
637
638/// The push-out for a Y-aligned capsule overlapping a sphere, or `None` if they
639/// are clear of each other.
640///
641/// The same Y-growth reduction the swept-capsule tests use: a sphere grown
642/// along Y by the capsule's half-height is a capsule, and the capsule's centre
643/// is inside it exactly when the two shapes overlap.
644#[must_use]
645pub fn capsule_penetration_vs_sphere(capsule: &Capsule, target: &Sphere) -> Option<Penetration> {
646    let grown = Capsule::new(target.centre, target.radius, capsule.half_height);
647    penetration_in_capsule(capsule.centre, capsule.radius, &grown)
648}
649
650/// The push-out for a Y-aligned capsule overlapping a Y-aligned capsule, or
651/// `None` if they are clear of each other.
652#[must_use]
653pub fn capsule_penetration_vs_capsule(capsule: &Capsule, target: &Capsule) -> Option<Penetration> {
654    let grown = Capsule::new(
655        target.centre,
656        target.radius,
657        target.half_height + capsule.half_height,
658    );
659    penetration_in_capsule(capsule.centre, capsule.radius, &grown)
660}
661
662/// The push-out for a Y-aligned capsule overlapping an AABB, or `None` if they
663/// are clear of each other.
664///
665/// A centre *inside* the grown box has no direction to escape along, so the
666/// answer there is the minimum-penetration face — the same choice the swept
667/// forms make, and the reason a character that spawned inside a wall leaves
668/// through the nearest one rather than travelling the length of the room.
669#[must_use]
670pub fn capsule_penetration_vs_aabb(capsule: &Capsule, target: &Aabb) -> Option<Penetration> {
671    // Checked before the growth, for the reason `swept_capsule_vs_aabb` gives.
672    if target.is_empty() {
673        return None;
674    }
675    let grown = Aabb::new(
676        target.min - DVec3::Y * capsule.half_height,
677        target.max + DVec3::Y * capsule.half_height,
678    );
679    let closest = capsule.centre.clamp(grown.min, grown.max);
680    let out = capsule.centre - closest;
681    let dist_sq = out.length_squared();
682    if dist_sq > capsule.radius * capsule.radius {
683        return None;
684    }
685    let (normal, depth) = if dist_sq > 0.0 {
686        let dist = dist_sq.sqrt();
687        (out / dist, capsule.radius - dist)
688    } else {
689        let (normal, to_face) = aabb_escape(&grown, capsule.centre);
690        (normal, capsule.radius + to_face)
691    };
692    (depth > 0.0).then_some(Penetration { normal, depth })
693}
694
695/// The push-out for a point of the given radius sitting inside `grown`, which
696/// is whichever capsule the caller's Y-growth produced.
697///
698/// A point exactly on the axis has no direction to escape along and takes the
699/// same `+Y` fallback the swept forms use for the same degenerate case.
700fn penetration_in_capsule(point: DVec3, radius: f64, grown: &Capsule) -> Option<Penetration> {
701    let combined = radius + grown.radius;
702    let out = point - closest_point_on_capsule_axis(grown, point);
703    let dist_sq = out.length_squared();
704    if dist_sq > combined * combined {
705        return None;
706    }
707    let dist = dist_sq.sqrt();
708    let depth = combined - dist;
709    if depth <= 0.0 {
710        return None;
711    }
712    Some(Penetration {
713        normal: if dist > 0.0 { out / dist } else { DVec3::Y },
714        depth,
715    })
716}
717
718// ---------------------------------------------------------------------------
719// Tests
720// ---------------------------------------------------------------------------
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725    use crate::broadphase::Ray;
726
727    // ── Ray vs sphere ─────────────────────────────────────────────────
728
729    #[test]
730    fn ray_hits_sphere_dead_centre() {
731        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X);
732        let sphere = Sphere::new(DVec3::ZERO, 1.0);
733        let hit = ray_vs_sphere(&ray, &sphere).unwrap();
734        assert!((hit.t - 4.0).abs() < 0.001);
735        assert_eq!(hit.normal, DVec3::NEG_X);
736    }
737
738    #[test]
739    fn a_ray_passing_beside_a_sphere_reports_no_hit() {
740        let ray = Ray::new(DVec3::new(-5.0, 3.0, 0.0), DVec3::X);
741        let sphere = Sphere::new(DVec3::ZERO, 1.0);
742        assert!(ray_vs_sphere(&ray, &sphere).is_none());
743    }
744
745    #[test]
746    fn ray_starts_inside_sphere() {
747        let ray = Ray::new(DVec3::ZERO, DVec3::X);
748        let sphere = Sphere::new(DVec3::ZERO, 2.0);
749        let hit = ray_vs_sphere(&ray, &sphere).unwrap();
750        assert!(hit.started_inside);
751        assert!((hit.t - 2.0).abs() < 0.001);
752    }
753
754    #[test]
755    fn ray_sphere_behind_origin() {
756        let ray = Ray::new(DVec3::new(5.0, 0.0, 0.0), DVec3::NEG_X);
757        let sphere = Sphere::new(DVec3::ZERO, 1.0);
758        let hit = ray_vs_sphere(&ray, &sphere).unwrap();
759        assert!((hit.t - 4.0).abs() < 0.001);
760    }
761
762    #[test]
763    fn zero_radius_sphere_normal_is_finite_when_hit_at_centre() {
764        // Bypass Sphere::new's debug_assert to test the query directly
765        // with a degenerate radius=0 sphere.  Before the guard,
766        // `.normalize()` on the zero-length centre-to-point vector
767        // produced NaN.
768        let sphere = Sphere {
769            centre: DVec3::ZERO,
770            radius: 0.0,
771        };
772        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X);
773        let hit =
774            ray_vs_sphere(&ray, &sphere).expect("ray through centre must hit zero-radius sphere");
775        assert!(
776            !hit.normal.x.is_nan() && !hit.normal.y.is_nan() && !hit.normal.z.is_nan(),
777            "normal must be finite for zero-radius sphere hit at centre; got {:?}",
778            hit.normal
779        );
780    }
781
782    #[test]
783    fn ray_hits_sphere_it_already_entered_before_t_min() {
784        // Near root at t=4, far at t=6, but the caller advanced t_min past the
785        // near root.  The far root is still in bounds, so this is a hit.
786        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X).with_bounds(4.5, 100.0);
787        let sphere = Sphere::new(DVec3::ZERO, 1.0);
788        let hit = ray_vs_sphere(&ray, &sphere).expect("far root is within bounds");
789        assert!((hit.t - 6.0).abs() < 1e-9, "t = {}", hit.t);
790        assert!(hit.started_inside);
791    }
792
793    #[test]
794    fn ray_misses_sphere_when_both_roots_are_out_of_bounds() {
795        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X).with_bounds(6.5, 100.0);
796        let sphere = Sphere::new(DVec3::ZERO, 1.0);
797        assert!(ray_vs_sphere(&ray, &sphere).is_none());
798    }
799
800    // ── Ray vs AABB ───────────────────────────────────────────────────
801
802    #[test]
803    fn ray_hits_aabb_centre() {
804        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X);
805        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
806        let hit = ray_vs_aabb(&ray, &aabb).unwrap();
807        assert!((hit.t - 4.0).abs() < 0.001);
808        assert_eq!(hit.normal, DVec3::NEG_X);
809    }
810
811    #[test]
812    fn a_ray_passing_above_a_box_reports_no_hit() {
813        let ray = Ray::new(DVec3::new(-5.0, 5.0, 0.0), DVec3::X);
814        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
815        assert!(ray_vs_aabb(&ray, &aabb).is_none());
816    }
817
818    #[test]
819    fn ray_hits_aabb_from_inside() {
820        let ray = Ray::new(DVec3::ZERO, DVec3::X);
821        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
822        let hit = ray_vs_aabb(&ray, &aabb).unwrap();
823        assert!(hit.started_inside);
824        assert!((hit.t - 1.0).abs() < 0.001);
825    }
826
827    #[test]
828    fn ray_hits_aabb_y_face() {
829        let ray = Ray::new(DVec3::new(0.0, -5.0, 0.0), DVec3::Y);
830        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
831        let hit = ray_vs_aabb(&ray, &aabb).unwrap();
832        assert_eq!(hit.normal, DVec3::NEG_Y);
833        assert!((hit.t - 4.0).abs() < 0.001);
834    }
835
836    #[test]
837    fn ray_hits_aabb_z_face() {
838        let ray = Ray::new(DVec3::new(0.0, 0.0, -5.0), DVec3::Z);
839        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
840        let hit = ray_vs_aabb(&ray, &aabb).unwrap();
841        assert_eq!(hit.normal, DVec3::NEG_Z);
842    }
843
844    #[test]
845    fn ray_on_aabb_face_zero_dir_component_hits() {
846        // Ray starts on +Y face with zero Y direction — would NaN before fix.
847        let ray = Ray::new(DVec3::new(0.0, 1.0, 0.0), DVec3::new(1.0, 0.0, 0.0));
848        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
849        let hit = ray_vs_aabb(&ray, &aabb).unwrap();
850        assert!(hit.started_inside);
851        assert!((hit.t - 1.0).abs() < 0.001);
852        assert_eq!(hit.normal, DVec3::X);
853    }
854
855    #[test]
856    fn ray_parallel_to_axis_outside_misses() {
857        // Ray outside AABB on Y, zero Y direction — should miss.
858        let ray = Ray::new(DVec3::new(0.0, 5.0, 0.0), DVec3::new(1.0, 0.0, 0.0));
859        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
860        assert!(ray_vs_aabb(&ray, &aabb).is_none());
861    }
862
863    #[test]
864    fn ray_hits_aabb_it_already_entered_before_t_min() {
865        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X).with_bounds(4.5, 100.0);
866        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
867        let hit = ray_vs_aabb(&ray, &aabb).expect("far face is within bounds");
868        assert!((hit.t - 6.0).abs() < 1e-9, "t = {}", hit.t);
869        assert!(hit.started_inside);
870        assert_eq!(hit.normal, DVec3::X);
871    }
872
873    // ── Ray vs capsule ────────────────────────────────────────────────
874
875    #[test]
876    fn ray_hits_capsule_cylinder() {
877        let capsule = Capsule::new(DVec3::ZERO, 0.5, 1.0);
878        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X);
879        let hit = ray_vs_capsule(&ray, &capsule).unwrap();
880        assert!((hit.t - 4.5).abs() < 0.001);
881    }
882
883    #[test]
884    fn ray_hits_capsule_top_cap() {
885        let capsule = Capsule::new(DVec3::ZERO, 0.5, 1.0);
886        // Aim at the top hemisphere centre.
887        let ray = Ray::new(DVec3::new(0.0, 5.0, 0.0), DVec3::NEG_Y);
888        let hit = ray_vs_capsule(&ray, &capsule).unwrap();
889        assert!((hit.t - 3.5).abs() < 0.001);
890    }
891
892    #[test]
893    fn a_ray_passing_beside_a_capsule_reports_no_hit() {
894        let capsule = Capsule::new(DVec3::ZERO, 0.5, 1.0);
895        let ray = Ray::new(DVec3::new(-5.0, 3.0, 0.0), DVec3::X);
896        assert!(ray_vs_capsule(&ray, &capsule).is_none());
897    }
898
899    #[test]
900    fn ray_inside_capsule_cylinder_radius_hits_the_cap_not_the_far_side() {
901        // Origin is radially inside the infinite cylinder (|x| = 0.9 < r = 1)
902        // but far above the capsule, aimed almost straight down.  The first
903        // real surface is the top hemisphere at t ≈ 4; the cylinder's exit at
904        // t ≈ 5 is a backface and must not win.
905        let capsule = Capsule::new(DVec3::ZERO, 1.0, 1.0);
906        let ray = Ray::new(DVec3::new(0.9, 5.0, 0.0), DVec3::new(0.0001, -1.0, 0.0));
907        let hit = ray_vs_capsule(&ray, &capsule).expect("ray must hit the capsule");
908        assert!(
909            hit.t < 4.5,
910            "expected the top cap at t ≈ 4, got t = {} at {:?}",
911            hit.t,
912            hit.point
913        );
914        assert!(
915            hit.point.y > 1.0,
916            "hit must be on the top cap: {:?}",
917            hit.point
918        );
919        assert!(
920            hit.normal.y > 0.0,
921            "top-cap normal must point up: {:?}",
922            hit.normal
923        );
924        assert!(!hit.started_inside);
925    }
926
927    #[test]
928    fn ray_started_inside_capsule_is_reported() {
929        let capsule = Capsule::new(DVec3::ZERO, 1.0, 2.0);
930        let ray = Ray::new(DVec3::ZERO, DVec3::X);
931        let hit = ray_vs_capsule(&ray, &capsule).expect("ray from the axis must exit the capsule");
932        assert!(hit.started_inside);
933        assert!((hit.t - 1.0).abs() < 1e-9, "t = {}", hit.t);
934    }
935
936    // ── Swept sphere vs sphere ────────────────────────────────────────
937
938    #[test]
939    fn swept_sphere_hits_static_sphere() {
940        let seg =
941            crate::broadphase::Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
942        let target = Sphere::new(DVec3::ZERO, 1.0);
943        let hit = swept_sphere_vs_sphere(&seg, 0.5, &target).unwrap();
944        // Combined radius = 1.5, start at x=-5, hit at x=-1.5
945        // t = (5 - 1.5) / 10 = 0.35
946        // Actually: distance to travel = 10, distance before contact = 5 - 1.5 = 3.5
947        // t = 3.5 / 10 = 0.35
948        assert!((hit.t - 0.35).abs() < 0.001, "expected 0.35, got {}", hit.t);
949    }
950
951    #[test]
952    fn swept_sphere_misses_static_sphere() {
953        let seg =
954            crate::broadphase::Segment::new(DVec3::new(-5.0, 5.0, 0.0), DVec3::new(5.0, 5.0, 0.0));
955        let target = Sphere::new(DVec3::ZERO, 1.0);
956        assert!(swept_sphere_vs_sphere(&seg, 0.5, &target).is_none());
957    }
958
959    #[test]
960    fn swept_sphere_starts_overlapping() {
961        let seg =
962            crate::broadphase::Segment::new(DVec3::new(0.5, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
963        let target = Sphere::new(DVec3::ZERO, 1.0);
964        let hit = swept_sphere_vs_sphere(&seg, 0.5, &target).expect("overlap at t=0 is a contact");
965        // Contact is now, not when the sphere would leave the target.
966        assert_eq!(hit.t, 0.0);
967        assert!(hit.started_inside);
968        assert!((hit.normal - DVec3::X).length() < 1e-9, "{:?}", hit.normal);
969    }
970
971    #[test]
972    fn swept_sphere_overlapping_for_the_whole_sweep_still_contacts() {
973        // Deep overlap: both roots lie outside [0, 1] (t1 < 0 < 1 < t2), which
974        // is a resting contact, not a miss.
975        let seg = crate::broadphase::Segment::new(DVec3::ZERO, DVec3::new(0.1, 0.0, 0.0));
976        let target = Sphere::new(DVec3::ZERO, 5.0);
977        let hit = swept_sphere_vs_sphere(&seg, 0.5, &target).expect("resting contact");
978        assert_eq!(hit.t, 0.0);
979        assert!(hit.started_inside);
980    }
981
982    // ── Swept sphere vs AABB ──────────────────────────────────────────
983
984    #[test]
985    fn swept_sphere_hits_aabb() {
986        let seg =
987            crate::broadphase::Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
988        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
989        let hit = swept_sphere_vs_aabb(&seg, 0.5, &aabb).unwrap();
990        // Sphere radius 0.5, AABB half-extent 1.0. Inflated AABB spans [-1.5, 1.5].
991        // Distance from start (-5) to inflated near plane (-1.5) = 3.5.
992        // Segment length = 10. t = 3.5 / 10 = 0.35
993        assert!((hit.t - 0.35).abs() < 0.001, "expected 0.35, got {}", hit.t);
994        assert_eq!(hit.normal, DVec3::NEG_X);
995    }
996
997    #[test]
998    fn swept_sphere_misses_aabb() {
999        let seg =
1000            crate::broadphase::Segment::new(DVec3::new(-5.0, 5.0, 0.0), DVec3::new(5.0, 5.0, 0.0));
1001        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1002        assert!(swept_sphere_vs_aabb(&seg, 0.5, &aabb).is_none());
1003    }
1004
1005    #[test]
1006    fn swept_sphere_vs_aabb_starts_overlapping() {
1007        let seg =
1008            crate::broadphase::Segment::new(DVec3::new(0.5, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
1009        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1010        let hit = swept_sphere_vs_aabb(&seg, 0.5, &aabb).expect("overlap at t=0 is a contact");
1011        assert_eq!(hit.t, 0.0);
1012        assert!(hit.started_inside);
1013        // Nearest inflated face from (0.5, 0, 0) is +X (0.5 vs 1.5 elsewhere),
1014        // not the fabricated +Z the eps-chain used to fall through to.
1015        assert_eq!(hit.normal, DVec3::X);
1016    }
1017
1018    #[test]
1019    fn tiny_sweep_starting_inside_sphere_is_a_contact() {
1020        // A sweep of length ~1e-10 m (dir·dir = 1e-20) is a real, non-stationary
1021        // sweep but sits below `solve_quadratic`'s EPSILON floor. It must take
1022        // the stationary branch and report a contact, not be rejected as a miss.
1023        let seg = crate::broadphase::Segment::new(DVec3::ZERO, DVec3::new(1e-10, 0.0, 0.0));
1024        let target = Sphere::new(DVec3::ZERO, 1.0);
1025        let hit = swept_sphere_vs_sphere(&seg, 0.5, &target)
1026            .expect("a sweep inside the target is a contact, not a miss");
1027        assert_eq!(hit.t, 0.0);
1028        assert!(hit.started_inside);
1029    }
1030
1031    #[test]
1032    fn tiny_sweep_starting_inside_aabb_is_a_contact() {
1033        let seg = crate::broadphase::Segment::new(DVec3::ZERO, DVec3::new(1e-10, 0.0, 0.0));
1034        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1035        let hit = swept_sphere_vs_aabb(&seg, 0.5, &aabb)
1036            .expect("a sweep inside the box is a contact, not a miss");
1037        assert_eq!(hit.t, 0.0);
1038        assert!(hit.started_inside);
1039    }
1040
1041    #[test]
1042    fn empty_aabb_overlaps_nothing() {
1043        let sphere = Sphere::new(DVec3::ZERO, 1.0);
1044        assert!(!sphere_overlaps_aabb(&sphere, &Aabb::EMPTY));
1045    }
1046
1047    #[test]
1048    fn swept_sphere_vs_empty_aabb_is_a_miss() {
1049        let seg = crate::broadphase::Segment::new(DVec3::ZERO, DVec3::ZERO);
1050        assert!(swept_sphere_vs_aabb(&seg, 1.0, &Aabb::EMPTY).is_none());
1051    }
1052
1053    #[test]
1054    fn swept_sphere_vs_aabb_touches_y_face() {
1055        let seg =
1056            crate::broadphase::Segment::new(DVec3::new(0.0, -5.0, 0.0), DVec3::new(0.0, 5.0, 0.0));
1057        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1058        let hit = swept_sphere_vs_aabb(&seg, 0.5, &aabb).unwrap();
1059        assert_eq!(hit.normal, DVec3::NEG_Y);
1060    }
1061
1062    #[test]
1063    fn swept_sphere_zero_dir_on_face_hits() {
1064        // Sphere starts on inflated Y face with zero Y direction.
1065        // AABB half-extent 1.0, radius 0.5 → inflated spans [-1.5, 1.5].
1066        // Origin at y=1.5 (on inflated +Y face), dir = (1,0,0) (zero Y).
1067        let seg =
1068            crate::broadphase::Segment::new(DVec3::new(-2.0, 1.5, 0.0), DVec3::new(2.0, 1.5, 0.0));
1069        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1070        let hit = swept_sphere_vs_aabb(&seg, 0.5, &aabb).unwrap();
1071        assert!(hit.t >= 0.0 && hit.t <= 1.0);
1072    }
1073
1074    // ── Overlap queries ────────────────────────────────────────────────
1075
1076    #[test]
1077    fn spheres_overlap_when_close() {
1078        let a = Sphere::new(DVec3::ZERO, 1.0);
1079        let b = Sphere::new(DVec3::new(1.5, 0.0, 0.0), 1.0);
1080        assert!(sphere_overlaps_sphere(&a, &b));
1081    }
1082
1083    /// **Touching is not overlapping, for every yes-or-no check** — the rule
1084    /// the hit-answering queries keep, so the two forms agree at the boundary.
1085    #[test]
1086    fn the_yes_or_no_checks_do_not_count_a_touch() {
1087        let unit = Sphere::new(DVec3::ZERO, 1.0);
1088        assert!(!sphere_overlaps_sphere(
1089            &unit,
1090            &Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0)
1091        ));
1092        let cube = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1093        assert!(!sphere_overlaps_aabb(
1094            &Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0),
1095            &cube
1096        ));
1097        let capsule = Capsule::new(DVec3::ZERO, 0.5, 2.0);
1098        assert!(!sphere_overlaps_capsule(
1099            &Sphere::new(DVec3::new(1.5, 1.0, 0.0), 1.0),
1100            &capsule
1101        ));
1102    }
1103
1104    #[test]
1105    fn spheres_do_not_overlap_when_far() {
1106        let a = Sphere::new(DVec3::ZERO, 1.0);
1107        let b = Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0);
1108        assert!(!sphere_overlaps_sphere(&a, &b));
1109    }
1110
1111    #[test]
1112    fn sphere_overlaps_aabb_when_intersecting() {
1113        let sphere = Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.5);
1114        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1115        assert!(sphere_overlaps_aabb(&sphere, &aabb));
1116    }
1117
1118    #[test]
1119    fn sphere_does_not_overlap_distant_aabb() {
1120        let sphere = Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0);
1121        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
1122        assert!(!sphere_overlaps_aabb(&sphere, &aabb));
1123    }
1124
1125    #[test]
1126    fn sphere_overlaps_capsule_body() {
1127        let sphere = Sphere::new(DVec3::new(1.0, 0.0, 0.0), 0.6);
1128        let capsule = Capsule::new(DVec3::ZERO, 0.5, 2.0);
1129        assert!(sphere_overlaps_capsule(&sphere, &capsule));
1130    }
1131
1132    #[test]
1133    fn sphere_overlaps_capsule_cap() {
1134        let sphere = Sphere::new(DVec3::new(0.0, 3.0, 0.0), 0.6);
1135        let capsule = Capsule::new(DVec3::ZERO, 0.5, 2.0);
1136        // capsule top is at y=2.0, radius 0.5 → top cap spans y ∈ [1.5, 2.5]
1137        // sphere at y=3.0, radius 0.6, combined radius 1.1 → distance 1.0 < 1.1
1138        assert!(sphere_overlaps_capsule(&sphere, &capsule));
1139    }
1140
1141    #[test]
1142    fn sphere_does_not_overlap_distant_capsule() {
1143        let sphere = Sphere::new(DVec3::new(10.0, 0.0, 0.0), 1.0);
1144        let capsule = Capsule::new(DVec3::ZERO, 0.5, 2.0);
1145        assert!(!sphere_overlaps_capsule(&sphere, &capsule));
1146    }
1147
1148    // ── Swept sphere vs capsule ────────────────────────────────────────
1149
1150    #[test]
1151    fn swept_sphere_hits_capsule_cylinder() {
1152        let seg =
1153            crate::broadphase::Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
1154        let capsule = Capsule::new(DVec3::ZERO, 0.5, 2.0);
1155        let hit = swept_sphere_vs_capsule(&seg, 0.5, &capsule).unwrap();
1156        // Combined radius = 1.0, capsule at origin, swept sphere starts at -5.
1157        // Should hit the cylinder at approximately t = (5 - 1) / 10 = 0.4.
1158        assert!(hit.t > 0.0 && hit.t < 1.0);
1159        assert!((hit.normal.x + 1.0).abs() < 0.1); // normal is roughly -X
1160    }
1161
1162    #[test]
1163    fn swept_sphere_misses_capsule() {
1164        let seg =
1165            crate::broadphase::Segment::new(DVec3::new(-5.0, 5.0, 0.0), DVec3::new(5.0, 5.0, 0.0));
1166        let capsule = Capsule::new(DVec3::ZERO, 0.5, 2.0);
1167        assert!(swept_sphere_vs_capsule(&seg, 0.5, &capsule).is_none());
1168    }
1169
1170    #[test]
1171    fn swept_sphere_overlapping_tall_capsule_pushes_out_sideways() {
1172        // A sphere overlapping the side of a tall capsule must be pushed along
1173        // the shortest way out — laterally — not away from the capsule centre.
1174        let capsule = Capsule::new(DVec3::ZERO, 1.0, 5.0);
1175        let seg =
1176            crate::broadphase::Segment::new(DVec3::new(1.2, 5.0, 0.0), DVec3::new(1.2, 5.0, 0.0));
1177        let hit = swept_sphere_vs_capsule(&seg, 0.5, &capsule).expect("resting contact");
1178        assert_eq!(hit.t, 0.0);
1179        assert!(hit.started_inside);
1180        assert!(
1181            (hit.normal - DVec3::X).length() < 1e-9,
1182            "expected a lateral normal, got {:?}",
1183            hit.normal
1184        );
1185    }
1186
1187    #[test]
1188    fn swept_sphere_vs_capsule_touches_top_cap() {
1189        // Swept sphere moving downward toward the top cap.
1190        let seg =
1191            crate::broadphase::Segment::new(DVec3::new(0.0, 5.0, 0.0), DVec3::new(0.0, 0.0, 0.0));
1192        let capsule = Capsule::new(DVec3::ZERO, 0.5, 2.0);
1193        // Capsule top at y=2.0, radius 0.5. Swept sphere radius 0.5.
1194        // Combined radius = 1.0. Hit at t = (5 - 2 - 1) / 5 = 2/5 = 0.4.
1195        let hit = swept_sphere_vs_capsule(&seg, 0.5, &capsule).unwrap();
1196        assert!((hit.t - 0.4).abs() < 0.01); // near t=0.4
1197        assert!(hit.normal.y > 0.5); // pointing away from capsule (upward)
1198    }
1199
1200    // ── Swept capsule ──────────────────────────────────────────────────
1201
1202    /// A capsule sweep is the query a character needs and a sphere sweep is
1203    /// not: the curb is below the sphere and inside the capsule.
1204    #[test]
1205    fn a_capsule_sweep_strikes_a_curb_the_sphere_at_its_waist_rides_over() {
1206        // Feet on y = 0, so the capsule spans y ∈ [0, 1.8] and the sphere of
1207        // the same radius, at the same centre, spans y ∈ [0.5, 1.3].
1208        let (radius, half_height) = (0.4, 0.5);
1209        let centre_y = radius + half_height;
1210        let seg = crate::broadphase::Segment::new(
1211            DVec3::new(-3.0, centre_y, 0.0),
1212            DVec3::new(3.0, centre_y, 0.0),
1213        );
1214        let curb = Aabb::new(DVec3::new(1.0, 0.0, -2.0), DVec3::new(3.0, 0.3, 2.0));
1215
1216        assert!(
1217            swept_sphere_vs_aabb(&seg, radius, &curb).is_none(),
1218            "the sphere must miss the curb, or the capsule hitting it proves nothing",
1219        );
1220        let hit = swept_capsule_vs_aabb(&seg, radius, half_height, &curb)
1221            .expect("the capsule reaches down to the curb");
1222        // The lower cap's centre is 0.1 above the curb's top, so the round
1223        // capsule meets the curb's rounded top edge, not its -X face.
1224        let rise = 0.1_f64;
1225        let expected = DVec3::new(-(radius * radius - rise * rise).sqrt(), rise, 0.0) / radius;
1226        assert!(
1227            (hit.normal - expected).length() < 1e-12,
1228            "struck the curb's top edge: {:?}",
1229            hit.normal
1230        );
1231    }
1232
1233    /// The contact is reported on the real box, not on the Y-grown proxy the
1234    /// reduction sweeps against — a controller placing a foot from this point
1235    /// would otherwise stand `half_height` above the floor.
1236    #[test]
1237    fn a_capsule_landing_reports_the_contact_on_the_floor_not_the_grown_box() {
1238        let (radius, half_height) = (0.4, 0.5);
1239        let floor = Aabb::new(DVec3::new(-5.0, -1.0, -5.0), DVec3::new(5.0, 0.0, 5.0));
1240        let seg =
1241            crate::broadphase::Segment::new(DVec3::new(0.0, 3.0, 0.0), DVec3::new(0.0, 0.5, 0.0));
1242        let hit = swept_capsule_vs_aabb(&seg, radius, half_height, &floor).expect("lands");
1243        assert_eq!(hit.normal, DVec3::Y);
1244        // Bottom cap touches y = 0 when the centre is at radius + half_height.
1245        let touch_y = radius + half_height;
1246        assert!(
1247            (hit.t - (3.0 - touch_y) / 2.5).abs() < 1e-12,
1248            "expected the TOI where the bottom cap meets the floor, got t = {}",
1249            hit.t,
1250        );
1251        assert!(
1252            (hit.point.y - floor.max.y).abs() < 1e-12,
1253            "contact reported at y = {}, and the floor's top is y = {}",
1254            hit.point.y,
1255            floor.max.y,
1256        );
1257    }
1258
1259    /// A box inverted only on Y reads as non-empty once Y has been grown, so
1260    /// the emptiness check has to happen before the growth.
1261    #[test]
1262    fn a_capsule_sweep_misses_a_box_that_is_empty_only_on_y() {
1263        let inverted = Aabb::new(DVec3::new(-1.0, 1.0, -1.0), DVec3::new(1.0, -1.0, 1.0));
1264        assert!(inverted.is_empty());
1265        let seg =
1266            crate::broadphase::Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
1267        assert!(swept_capsule_vs_aabb(&seg, 0.5, 2.0, &inverted).is_none());
1268    }
1269
1270    /// The capsule's flank reaches a sphere its centre line passes well below,
1271    /// and the contact comes back on the sphere's own surface.
1272    #[test]
1273    fn a_capsule_flank_hits_a_sphere_above_its_centre_line() {
1274        let (radius, half_height) = (0.5, 2.0);
1275        let target = Sphere::new(DVec3::ZERO, 1.0);
1276        // The path is 1.6 above the target's centre: further than the 1.5 the
1277        // two radii cover, so the sphere sweep misses, and well inside the
1278        // capsule's 2.0 half-height, so the flank does not.
1279        let seg =
1280            crate::broadphase::Segment::new(DVec3::new(-5.0, 1.6, 0.0), DVec3::new(5.0, 1.6, 0.0));
1281        assert!(
1282            swept_sphere_vs_sphere(&seg, radius, &target).is_none(),
1283            "the sphere must miss, or the capsule hitting it proves nothing",
1284        );
1285
1286        let hit = swept_capsule_vs_sphere(&seg, radius, half_height, &target).expect("flank hit");
1287        // Contact at |x| = radius + target.radius along a 10 m path from -5.
1288        assert!(
1289            (hit.t - (5.0 - 1.5) / 10.0).abs() < 1e-12,
1290            "expected the TOI where the flank meets the sphere, got t = {}",
1291            hit.t,
1292        );
1293        assert!(
1294            (hit.normal - DVec3::NEG_X).length() < 1e-12,
1295            "got {:?}",
1296            hit.normal
1297        );
1298        assert!(
1299            (hit.point - DVec3::new(-1.0, 0.0, 0.0)).length() < 1e-12,
1300            "the contact belongs on the target sphere's surface, and came back at {:?}",
1301            hit.point,
1302        );
1303    }
1304
1305    /// Two Y-aligned capsules meet when the horizontal gap closes to the sum of
1306    /// their radii, and the contact lands on the static one's surface rather
1307    /// than on the taller proxy the reduction sweeps against.
1308    #[test]
1309    fn a_capsule_sweep_re_anchors_its_contact_on_the_static_capsules_axis() {
1310        let (radius, half_height) = (0.5, 3.0);
1311        let target = Capsule::new(DVec3::ZERO, 0.5, 1.0);
1312        // The mover's centre rides above the target's top cap; only the flanks
1313        // can meet, and the overlap of the two axes tops out at y = 1.0.
1314        let seg =
1315            crate::broadphase::Segment::new(DVec3::new(-5.0, 2.0, 0.0), DVec3::new(5.0, 2.0, 0.0));
1316        let hit =
1317            swept_capsule_vs_capsule(&seg, radius, half_height, &target).expect("flanks meet");
1318        assert!(
1319            (hit.t - (5.0 - 1.0) / 10.0).abs() < 1e-12,
1320            "expected the TOI where the two flanks touch, got t = {}",
1321            hit.t,
1322        );
1323        assert!(
1324            (hit.normal - DVec3::NEG_X).length() < 1e-12,
1325            "got {:?}",
1326            hit.normal
1327        );
1328        let off_axis = hit.point - closest_point_on_capsule_axis(&target, hit.point);
1329        assert!(
1330            (off_axis.length() - target.radius).abs() < 1e-12,
1331            "the contact is {} from the target's axis and its surface is {} out — \
1332             the proxy's axis is taller than the target's, so this is what an \
1333             un-re-anchored point fails",
1334            off_axis.length(),
1335            target.radius,
1336        );
1337    }
1338
1339    /// A capsule that starts overlapping is a resting contact at `t = 0`, the
1340    /// same answer the sphere sweeps give and the one depenetration reads.
1341    #[test]
1342    fn a_capsule_sweep_that_starts_overlapping_is_a_contact_at_zero() {
1343        let (radius, half_height) = (0.4, 0.9);
1344        let wall = Aabb::new(DVec3::new(0.0, -5.0, -5.0), DVec3::new(5.0, 5.0, 5.0));
1345        // Centre 0.2 inside the wall's -X face, so the whole flank overlaps.
1346        let seg =
1347            crate::broadphase::Segment::new(DVec3::new(0.2, 0.0, 0.0), DVec3::new(0.2, 0.0, 1.0));
1348        let hit = swept_capsule_vs_aabb(&seg, radius, half_height, &wall).expect("resting contact");
1349        assert_eq!(hit.t, 0.0);
1350        assert!(hit.started_inside);
1351        assert_eq!(
1352            hit.normal,
1353            DVec3::NEG_X,
1354            "the shortest way out is back through the face it entered",
1355        );
1356    }
1357}