Skip to main content

crcbl_phys/query/
arc.rs

1//! Where a capsule moving under constant acceleration first touches a shape,
2//! as a time: the shape-level half of
3//! [`PhysicsWorld::sweep_capsule_arc`](crate::PhysicsWorld::sweep_capsule_arc).
4//!
5//! The straight sweeps answer a share of one segment. A body falling, or
6//! braking in the air, does not move along a segment: its path bows away from
7//! the chord between its ends by `|a| T² / 8` at the middle, so a chord can
8//! miss a wall the path reaches and leaves, and a share of the chord is not a
9//! time on the path. These answer the time itself, on the path itself.
10//!
11//! # Conservative advancement against a supporting plane
12//!
13//! Each shape is advanced on alone, by conservative advancement — Mirtich,
14//! _Impulse-based Dynamic Simulation of Rigid Body Systems_, PhD thesis, UC
15//! Berkeley, 1996 — with the step bounded by a plane rather than by a speed:
16//!
17//! - measure the gap and its normal `n` with the narrow phase the straight
18//!   sweeps use (the contact pipeline's `gap`, or a mesh's own triangle
19//!   distance);
20//! - take the plane across `n` through the shape's furthest point along it,
21//!   its support: the whole shape lies behind that plane, so how far the
22//!   capsule is in front of it is a lower bound on the gap, now and at every
23//!   later time;
24//! - along a constant-acceleration path that height changes by exactly
25//!   `n · (v s + ½ a s²)` over the next `s`, a quadratic, so its first root
26//!   is a time before which the capsule cannot touch the shape; step there.
27//!
28//! No contact is stepped over, a touch-and-leave included: the bound holds at
29//! every time in the step, not only at its end, because it is the whole path
30//! against the plane. Its rate of change, `n · (v + a s)`, is never faster
31//! than `|v| + |a| s`, so the step is never shorter than a bound on the
32//! distance's rate of change would allow, and for a flat face it lands on
33//! the contact in one step. A path that never reaches the plane never
34//! reaches the shape, which is what ends the search for a body sliding along
35//! a wall rather than into it.
36//!
37//! The search reports a contact once the next safe step is no longer than
38//! [`ARC_TIME_TOLERANCE`], or the gap is gone; and gives up, reporting where
39//! it got to, after [`ARC_MAX_ITERATIONS`] steps. Either way the time
40//! reported is never later than the first touch.
41
42use glam::{DQuat, DVec3};
43
44use super::{TurnedCapsule, contact_box, nearest_on_box};
45use crate::collider::{Aabb, BoxCollider, Sphere};
46use crate::contact::manifold::{closest_between_segments, gap};
47use crate::contact::shape::ContactShape;
48
49/// How short the next safe step of
50/// [`PhysicsWorld::sweep_capsule_arc`](crate::PhysicsWorld::sweep_capsule_arc)
51/// must become for the capsule to count as touching, in the path's own units
52/// of time — seconds for a velocity in metres per second.
53///
54/// A contact is reported at most this long before the capsule could next
55/// reach the plane bounding the shape; a pass that comes within the distance
56/// the capsule closes in this time may be reported as a touch. EW's local
57/// contact bisection stops at the same interval.
58pub const ARC_TIME_TOLERANCE: f64 = 1e-9;
59
60/// The most steps
61/// [`PhysicsWorld::sweep_capsule_arc`](crate::PhysicsWorld::sweep_capsule_arc)
62/// takes against one shape. A search still short of [`ARC_TIME_TOLERANCE`]
63/// after this many reports a contact where its last step left it, which is
64/// never past the first touch: the answer Box2D's `b2TimeOfImpact` gives when
65/// it runs out of iterations. A flat face is met in one step, and an edge or
66/// a round surface approached head on in a handful.
67pub const ARC_MAX_ITERATIONS: usize = 64;
68
69/// A point moving under constant acceleration for a while: the path of a
70/// capsule's centre that
71/// [`PhysicsWorld::sweep_capsule_arc`](crate::PhysicsWorld::sweep_capsule_arc)
72/// sweeps.
73///
74/// At time `t` in `[0, duration]` the point is at
75/// `start + velocity t + ½ acceleration t²`. Gravity and a steering
76/// acceleration together are one constant acceleration; anything that
77/// changes over the interval — a correction that ends, a drag — is the
78/// caller's to split the interval at.
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct AcceleratedPath {
81    /// Where the point is at time zero.
82    pub start: DVec3,
83    /// Its velocity at time zero.
84    pub velocity: DVec3,
85    /// Its constant acceleration.
86    pub acceleration: DVec3,
87    /// How long it moves for: the end of the interval `[0, duration]`.
88    pub duration: f64,
89}
90
91impl AcceleratedPath {
92    /// A path from `start` at `velocity`, accelerating at `acceleration`, for
93    /// `duration`.
94    ///
95    /// # Panics
96    ///
97    /// Panics in debug builds if `duration` is negative or not finite.
98    #[must_use]
99    pub fn new(start: DVec3, velocity: DVec3, acceleration: DVec3, duration: f64) -> Self {
100        debug_assert!(
101            duration >= 0.0 && duration.is_finite(),
102            "a path's duration must be finite and non-negative"
103        );
104        Self {
105            start,
106            velocity,
107            acceleration,
108            duration,
109        }
110    }
111
112    /// Where the point is at `time`.
113    #[must_use]
114    pub fn position_at(&self, time: f64) -> DVec3 {
115        self.start + self.velocity * time + self.acceleration * (0.5 * time * time)
116    }
117
118    /// The point's velocity at `time`.
119    #[must_use]
120    pub fn velocity_at(&self, time: f64) -> DVec3 {
121        self.velocity + self.acceleration * time
122    }
123
124    /// The smallest world-axis box holding the whole path: its two ends, and
125    /// on each axis whose motion turns back within the interval the turning
126    /// point — a jump's apex lies above both its ends.
127    pub(crate) fn bounds(&self) -> Aabb {
128        let end = self.position_at(self.duration);
129        let (mut min, mut max) = (self.start.min(end), self.start.max(end));
130        for axis in 0..3 {
131            let acceleration = self.acceleration[axis];
132            if acceleration == 0.0 {
133                continue;
134            }
135            let turn = -self.velocity[axis] / acceleration;
136            if turn > 0.0 && turn < self.duration {
137                let at = self.position_at(turn)[axis];
138                min[axis] = min[axis].min(at);
139                max[axis] = max[axis].max(at);
140            }
141        }
142        Aabb::new(min, max)
143    }
144
145    /// This path as seen from a frame at `origin` turned by `turn`'s inverse:
146    /// `turn` takes a world vector into that frame.
147    pub(crate) fn in_frame(&self, origin: DVec3, turn: DQuat) -> Self {
148        Self {
149            start: turn * (self.start - origin),
150            velocity: turn * self.velocity,
151            acceleration: turn * self.acceleration,
152            duration: self.duration,
153        }
154    }
155}
156
157/// Where
158/// [`PhysicsWorld::sweep_capsule_arc`](crate::PhysicsWorld::sweep_capsule_arc)
159/// found a capsule first touching a collider.
160#[derive(Debug, Clone, Copy, PartialEq)]
161pub struct ArcHit {
162    /// When the capsule touches, in `[0, duration]` of the path, and never
163    /// later than the first touch. The search stops once its next safe step
164    /// is no longer than [`ARC_TIME_TOLERANCE`]: a flat face is met to
165    /// rounding, and an edge or a round surface to within the distance the
166    /// capsule closes in that time. Zero when it started touching.
167    pub time: f64,
168    /// The point of the collider nearest the capsule at [`time`](Self::time).
169    pub point: DVec3,
170    /// Unit normal pointing away from the surface met, toward the capsule.
171    pub normal: DVec3,
172    /// Whether this is the contact at the original path's starting overlap.
173    /// Its [`time`](Self::time) is zero whichever way the capsule moves, as a
174    /// straight sweep's [`ShapeHit::started_inside`](crate::ShapeHit) is. A
175    /// later re-entry selected after rejecting that overlap is not flagged.
176    pub started_inside: bool,
177    /// The part of the collider met, as
178    /// [`ShapeHit::part`](crate::ShapeHit::part) means it.
179    pub part: usize,
180}
181
182/// A Y-aligned capsule of `radius` and `half_height` whose centre follows
183/// `path` against a sphere.
184pub(crate) fn arc_capsule_vs_sphere(
185    path: &AcceleratedPath,
186    radius: f64,
187    half_height: f64,
188    target: &Sphere,
189    accept: impl Fn(&ArcHit) -> bool,
190) -> Option<ArcHit> {
191    let shape = ContactShape::Sphere {
192        centre: target.centre,
193        radius: target.radius,
194    };
195    arc_capsule_vs_shape(
196        path,
197        radius,
198        half_height,
199        &shape,
200        |_, _, normal| target.centre + normal * target.radius,
201        accept,
202    )
203}
204
205/// [`arc_capsule_vs_sphere`] against a box collider, turned or not.
206pub(crate) fn arc_capsule_vs_box(
207    path: &AcceleratedPath,
208    radius: f64,
209    half_height: f64,
210    target: &BoxCollider,
211    accept: impl Fn(&ArcHit) -> bool,
212) -> Option<ArcHit> {
213    arc_capsule_vs_shape(
214        path,
215        radius,
216        half_height,
217        &contact_box(target),
218        |bottom, top, _| nearest_on_box(target, bottom, top),
219        accept,
220    )
221}
222
223/// [`arc_capsule_vs_sphere`] against a capsule, standing or turned.
224pub(crate) fn arc_capsule_vs_turned_capsule(
225    path: &AcceleratedPath,
226    radius: f64,
227    half_height: f64,
228    target: &TurnedCapsule,
229    accept: impl Fn(&ArcHit) -> bool,
230) -> Option<ArcHit> {
231    let (a, b) = target.core();
232    arc_capsule_vs_shape(
233        path,
234        radius,
235        half_height,
236        &target.contact_shape(),
237        |bottom, top, normal| {
238            closest_between_segments(a, b, bottom, top).0 + normal * target.capsule.radius
239        },
240        accept,
241    )
242}
243
244/// A Y-aligned capsule following `path` against a convex `target`, measured
245/// by the contact pipeline's [`gap`]; `nearest` finds the target's point
246/// nearest the capsule's core, given the core's ends and the normal there.
247fn arc_capsule_vs_shape(
248    path: &AcceleratedPath,
249    radius: f64,
250    half_height: f64,
251    target: &ContactShape,
252    nearest: impl Fn(DVec3, DVec3, DVec3) -> DVec3,
253    accept: impl Fn(&ArcHit) -> bool,
254) -> Option<ArcHit> {
255    let half = DVec3::Y * half_height;
256    super::arc_selection::contact_where(
257        path,
258        half,
259        radius,
260        |direction| support(target, direction),
261        |a, b| gap(target, &ContactShape::Capsule { a, b, radius }),
262        |time, normal| {
263            let centre = path.position_at(time);
264            nearest(centre - half, centre + half, normal)
265        },
266        accept,
267    )
268}
269
270/// The time a capsule of `radius` about the segment from `-half` to `+half`
271/// round its centre, the centre following `path`, first touches a convex
272/// shape; the normal out of the shape there; and whether it started touching.
273/// `None` if it does not touch within the path's duration. See the module
274/// docs for the method.
275///
276/// `separation` measures the shape against the capsule whose core runs
277/// between two points: the signed gap, and the unit normal from the shape
278/// toward the capsule. `support` is the shape's support function: the
279/// furthest it reaches along a unit direction, `max n · x` over its points.
280pub(crate) fn earliest_contact(
281    path: &AcceleratedPath,
282    half: DVec3,
283    radius: f64,
284    support: impl Fn(DVec3) -> f64,
285    separation: impl Fn(DVec3, DVec3) -> (f64, DVec3),
286) -> Option<(f64, DVec3, bool)> {
287    let core = |time: f64| {
288        let centre = path.position_at(time);
289        (centre - half, centre + half)
290    };
291    let (a, b) = core(0.0);
292    let (distance, mut normal) = separation(a, b);
293    if distance <= 0.0 {
294        return Some((0.0, normal, true));
295    }
296    let mut time = 0.0;
297    for _ in 0..ARC_MAX_ITERATIONS {
298        let (a, b) = core(time);
299        // The capsule's height in front of the plane that holds the shape
300        // behind it. A narrow phase whose normal is not the exact closest
301        // direction can leave this at or below zero while the gap is not;
302        // the capsule is then as near as the bound can tell, and is touching.
303        let ahead = normal.dot(a).min(normal.dot(b)) - radius - support(normal);
304        let step = if ahead > 0.0 {
305            first_root(
306                ahead,
307                normal.dot(path.velocity_at(time)),
308                normal.dot(path.acceleration),
309            )?
310        } else {
311            0.0
312        };
313        time += step;
314        if time > path.duration {
315            return None;
316        }
317        let (a, b) = core(time);
318        let (distance, next) = separation(a, b);
319        normal = next;
320        if distance <= 0.0 || step <= ARC_TIME_TOLERANCE {
321            return Some((time, normal, false));
322        }
323    }
324    Some((time, normal, false))
325}
326
327/// The least `s > 0` at which `ahead + rate s + ½ curve s²` reaches zero,
328/// for an `ahead` above zero, or `None` if it never does.
329///
330/// Each branch is the root the quadratic formula loses no digits to: the
331/// one whose numerator adds two terms of the same sign.
332fn first_root(ahead: f64, rate: f64, curve: f64) -> Option<f64> {
333    let discriminant = rate * rate - 2.0 * curve * ahead;
334    if discriminant < 0.0 {
335        return None;
336    }
337    let root = discriminant.sqrt();
338    if rate < 0.0 {
339        Some(2.0 * ahead / (root - rate))
340    } else if curve < 0.0 {
341        Some((rate + root) / -curve)
342    } else {
343        None
344    }
345}
346
347/// How far `shape` reaches along the unit `direction`: the most
348/// `direction · x` over its points, its support function.
349///
350/// A half-space reaches a finite distance only along its own outward normal,
351/// and infinitely far along every other direction.
352pub(crate) fn support(shape: &ContactShape, direction: DVec3) -> f64 {
353    match *shape {
354        ContactShape::Sphere { centre, radius } => direction.dot(centre) + radius,
355        ContactShape::Capsule { a, b, radius } => direction.dot(a).max(direction.dot(b)) + radius,
356        ContactShape::Box {
357            centre,
358            rotation,
359            half,
360        } => direction.dot(centre) + (rotation.inverse() * direction).abs().dot(half),
361        ContactShape::Triangle { corners, .. } => {
362            corners.iter().fold(f64::NEG_INFINITY, |far, &corner| {
363                far.max(direction.dot(corner))
364            })
365        }
366        ContactShape::Plane { normal, offset } => {
367            if direction == normal {
368                offset
369            } else {
370                f64::INFINITY
371            }
372        }
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    /// How closely a value worked out by hand has to agree with the code's:
381    /// only rounding separates them.
382    const EXACT: f64 = 1e-12;
383
384    /// **A jump's apex is inside its bounds**, though both its ends are
385    /// below it; an axis that does not turn within the interval is bounded
386    /// by its ends alone.
387    #[test]
388    fn the_bounds_hold_the_turning_point_as_well_as_the_ends() {
389        let gravity = -9.81;
390        let rise = 3.5;
391        let path = AcceleratedPath::new(
392            DVec3::new(1.0, 2.0, 3.0),
393            DVec3::new(0.5, rise, 0.0),
394            DVec3::new(0.0, gravity, 0.0),
395            // The return to the starting height, a little past it.
396            2.2 * rise / -gravity,
397        );
398        let bounds = path.bounds();
399        let apex = 2.0 + rise * rise / (2.0 * -gravity);
400        let end = path.position_at(path.duration);
401        assert!(end.y < path.start.y, "the ends are below the apex");
402        assert!(
403            (bounds.max.y - apex).abs() < EXACT,
404            "the bounds reach the apex at {apex}: {bounds:?}"
405        );
406        assert_eq!(bounds.min.y, end.y);
407        assert_eq!((bounds.min.x, bounds.max.x), (path.start.x, end.x));
408        assert_eq!((bounds.min.z, bounds.max.z), (3.0, 3.0));
409
410        // Stopped before the apex, the path's top is its end.
411        let rising = AcceleratedPath {
412            duration: 0.5 * rise / -gravity,
413            ..path
414        };
415        assert_eq!(rising.bounds().max.y, rising.position_at(rising.duration).y);
416    }
417
418    /// The root is where the quadratic is zero, the first of two, and none
419    /// is found for a quadratic that turns back before reaching zero or
420    /// never heads there.
421    #[test]
422    fn the_first_root_is_the_earlier_zero_or_none() {
423        let value =
424            |ahead: f64, rate: f64, curve: f64, s: f64| ahead + rate * s + 0.5 * curve * s * s;
425        for (ahead, rate, curve) in [
426            (1.0, -2.0, 0.0),
427            (1.0, -2.0, 1.0),
428            (1.0, -2.0, -3.0),
429            (1.0, 0.0, -2.0),
430            (1.0, 3.0, -2.0),
431            (1e-12, -5.0, 9.81),
432        ] {
433            let s = first_root(ahead, rate, curve).expect("it reaches zero");
434            assert!(s > 0.0);
435            assert!(
436                value(ahead, rate, curve, s).abs() < EXACT,
437                "({ahead}, {rate}, {curve}) at {s}"
438            );
439            // Nothing earlier reaches zero.
440            let earlier = s * 0.999;
441            assert!(value(ahead, rate, curve, earlier) > 0.0);
442        }
443        assert_eq!(first_root(1.0, -1.0, 1.0), None, "it turns back first");
444        assert_eq!(first_root(1.0, 0.0, 0.0), None, "it never moves");
445        assert_eq!(first_root(1.0, 2.0, 1.0), None, "it heads away");
446    }
447}