use glam::{DQuat, DVec3};
use super::{TurnedCapsule, contact_box, nearest_on_box};
use crate::collider::{Aabb, BoxCollider, Sphere};
use crate::contact::manifold::{closest_between_segments, gap};
use crate::contact::shape::ContactShape;
pub const ARC_TIME_TOLERANCE: f64 = 1e-9;
pub const ARC_MAX_ITERATIONS: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AcceleratedPath {
pub start: DVec3,
pub velocity: DVec3,
pub acceleration: DVec3,
pub duration: f64,
}
impl AcceleratedPath {
#[must_use]
pub fn new(start: DVec3, velocity: DVec3, acceleration: DVec3, duration: f64) -> Self {
debug_assert!(
duration >= 0.0 && duration.is_finite(),
"a path's duration must be finite and non-negative"
);
Self {
start,
velocity,
acceleration,
duration,
}
}
#[must_use]
pub fn position_at(&self, time: f64) -> DVec3 {
self.start + self.velocity * time + self.acceleration * (0.5 * time * time)
}
#[must_use]
pub fn velocity_at(&self, time: f64) -> DVec3 {
self.velocity + self.acceleration * time
}
pub(crate) fn bounds(&self) -> Aabb {
let end = self.position_at(self.duration);
let (mut min, mut max) = (self.start.min(end), self.start.max(end));
for axis in 0..3 {
let acceleration = self.acceleration[axis];
if acceleration == 0.0 {
continue;
}
let turn = -self.velocity[axis] / acceleration;
if turn > 0.0 && turn < self.duration {
let at = self.position_at(turn)[axis];
min[axis] = min[axis].min(at);
max[axis] = max[axis].max(at);
}
}
Aabb::new(min, max)
}
pub(crate) fn in_frame(&self, origin: DVec3, turn: DQuat) -> Self {
Self {
start: turn * (self.start - origin),
velocity: turn * self.velocity,
acceleration: turn * self.acceleration,
duration: self.duration,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ArcHit {
pub time: f64,
pub point: DVec3,
pub normal: DVec3,
pub started_inside: bool,
pub part: usize,
}
pub(crate) fn arc_capsule_vs_sphere(
path: &AcceleratedPath,
radius: f64,
half_height: f64,
target: &Sphere,
accept: impl Fn(&ArcHit) -> bool,
) -> Option<ArcHit> {
let shape = ContactShape::Sphere {
centre: target.centre,
radius: target.radius,
};
arc_capsule_vs_shape(
path,
radius,
half_height,
&shape,
|_, _, normal| target.centre + normal * target.radius,
accept,
)
}
pub(crate) fn arc_capsule_vs_box(
path: &AcceleratedPath,
radius: f64,
half_height: f64,
target: &BoxCollider,
accept: impl Fn(&ArcHit) -> bool,
) -> Option<ArcHit> {
arc_capsule_vs_shape(
path,
radius,
half_height,
&contact_box(target),
|bottom, top, _| nearest_on_box(target, bottom, top),
accept,
)
}
pub(crate) fn arc_capsule_vs_turned_capsule(
path: &AcceleratedPath,
radius: f64,
half_height: f64,
target: &TurnedCapsule,
accept: impl Fn(&ArcHit) -> bool,
) -> Option<ArcHit> {
let (a, b) = target.core();
arc_capsule_vs_shape(
path,
radius,
half_height,
&target.contact_shape(),
|bottom, top, normal| {
closest_between_segments(a, b, bottom, top).0 + normal * target.capsule.radius
},
accept,
)
}
fn arc_capsule_vs_shape(
path: &AcceleratedPath,
radius: f64,
half_height: f64,
target: &ContactShape,
nearest: impl Fn(DVec3, DVec3, DVec3) -> DVec3,
accept: impl Fn(&ArcHit) -> bool,
) -> Option<ArcHit> {
let half = DVec3::Y * half_height;
super::arc_selection::contact_where(
path,
half,
radius,
|direction| support(target, direction),
|a, b| gap(target, &ContactShape::Capsule { a, b, radius }),
|time, normal| {
let centre = path.position_at(time);
nearest(centre - half, centre + half, normal)
},
accept,
)
}
pub(crate) fn earliest_contact(
path: &AcceleratedPath,
half: DVec3,
radius: f64,
support: impl Fn(DVec3) -> f64,
separation: impl Fn(DVec3, DVec3) -> (f64, DVec3),
) -> Option<(f64, DVec3, bool)> {
let core = |time: f64| {
let centre = path.position_at(time);
(centre - half, centre + half)
};
let (a, b) = core(0.0);
let (distance, mut normal) = separation(a, b);
if distance <= 0.0 {
return Some((0.0, normal, true));
}
let mut time = 0.0;
for _ in 0..ARC_MAX_ITERATIONS {
let (a, b) = core(time);
let ahead = normal.dot(a).min(normal.dot(b)) - radius - support(normal);
let step = if ahead > 0.0 {
first_root(
ahead,
normal.dot(path.velocity_at(time)),
normal.dot(path.acceleration),
)?
} else {
0.0
};
time += step;
if time > path.duration {
return None;
}
let (a, b) = core(time);
let (distance, next) = separation(a, b);
normal = next;
if distance <= 0.0 || step <= ARC_TIME_TOLERANCE {
return Some((time, normal, false));
}
}
Some((time, normal, false))
}
fn first_root(ahead: f64, rate: f64, curve: f64) -> Option<f64> {
let discriminant = rate * rate - 2.0 * curve * ahead;
if discriminant < 0.0 {
return None;
}
let root = discriminant.sqrt();
if rate < 0.0 {
Some(2.0 * ahead / (root - rate))
} else if curve < 0.0 {
Some((rate + root) / -curve)
} else {
None
}
}
pub(crate) fn support(shape: &ContactShape, direction: DVec3) -> f64 {
match *shape {
ContactShape::Sphere { centre, radius } => direction.dot(centre) + radius,
ContactShape::Capsule { a, b, radius } => direction.dot(a).max(direction.dot(b)) + radius,
ContactShape::Box {
centre,
rotation,
half,
} => direction.dot(centre) + (rotation.inverse() * direction).abs().dot(half),
ContactShape::Triangle { corners, .. } => {
corners.iter().fold(f64::NEG_INFINITY, |far, &corner| {
far.max(direction.dot(corner))
})
}
ContactShape::Plane { normal, offset } => {
if direction == normal {
offset
} else {
f64::INFINITY
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const EXACT: f64 = 1e-12;
#[test]
fn the_bounds_hold_the_turning_point_as_well_as_the_ends() {
let gravity = -9.81;
let rise = 3.5;
let path = AcceleratedPath::new(
DVec3::new(1.0, 2.0, 3.0),
DVec3::new(0.5, rise, 0.0),
DVec3::new(0.0, gravity, 0.0),
2.2 * rise / -gravity,
);
let bounds = path.bounds();
let apex = 2.0 + rise * rise / (2.0 * -gravity);
let end = path.position_at(path.duration);
assert!(end.y < path.start.y, "the ends are below the apex");
assert!(
(bounds.max.y - apex).abs() < EXACT,
"the bounds reach the apex at {apex}: {bounds:?}"
);
assert_eq!(bounds.min.y, end.y);
assert_eq!((bounds.min.x, bounds.max.x), (path.start.x, end.x));
assert_eq!((bounds.min.z, bounds.max.z), (3.0, 3.0));
let rising = AcceleratedPath {
duration: 0.5 * rise / -gravity,
..path
};
assert_eq!(rising.bounds().max.y, rising.position_at(rising.duration).y);
}
#[test]
fn the_first_root_is_the_earlier_zero_or_none() {
let value =
|ahead: f64, rate: f64, curve: f64, s: f64| ahead + rate * s + 0.5 * curve * s * s;
for (ahead, rate, curve) in [
(1.0, -2.0, 0.0),
(1.0, -2.0, 1.0),
(1.0, -2.0, -3.0),
(1.0, 0.0, -2.0),
(1.0, 3.0, -2.0),
(1e-12, -5.0, 9.81),
] {
let s = first_root(ahead, rate, curve).expect("it reaches zero");
assert!(s > 0.0);
assert!(
value(ahead, rate, curve, s).abs() < EXACT,
"({ahead}, {rate}, {curve}) at {s}"
);
let earlier = s * 0.999;
assert!(value(ahead, rate, curve, earlier) > 0.0);
}
assert_eq!(first_root(1.0, -1.0, 1.0), None, "it turns back first");
assert_eq!(first_root(1.0, 0.0, 0.0), None, "it never moves");
assert_eq!(first_root(1.0, 2.0, 1.0), None, "it heads away");
}
}