use crcbl_core::Pool;
use glam::{DQuat, DVec3};
use super::broadphase::ProxyId;
use super::island::Islands;
use super::manifold::{LINEAR_SLOP, gap};
use super::shape::ContactShape;
use super::{Bodies, ContactPipeline, Owner, owner_side};
use crate::collider::Aabb;
use crate::components::{ColliderComponent, Transform};
use crate::system::{AwakeSet, BodyRecord, StaticSet};
const FAST_FRACTION: f64 = 0.5;
const TOLERANCE: f64 = 0.25 * LINEAR_SLOP;
const MAX_ADVANCES: usize = 32;
#[derive(Debug, Default)]
pub(crate) struct Scratch {
starts: Vec<Transform>,
candidates: Vec<ProxyId>,
}
#[derive(Clone, Copy, Debug)]
struct Path {
start: Transform,
end_rotation: DQuat,
travel: DVec3,
turn_rate: f64,
}
impl Path {
fn new(start: &Transform, end: &Transform) -> Self {
let end_rotation = if start.rotation.dot(end.rotation) < 0.0 {
-end.rotation
} else {
end.rotation
};
let turn = end_rotation * start.rotation.conjugate();
let (cos, sin) = (turn.w.max(0.0), turn.xyz().length());
Self {
start: *start,
end_rotation,
travel: end.position - start.position,
turn_rate: 4.0 * sin / (1.0 + cos),
}
}
fn at(&self, t: f64) -> Transform {
let from = self.start.rotation;
Transform::new(
self.start.position + self.travel * t,
(from + (self.end_rotation - from) * t).normalize(),
)
}
}
#[derive(Clone, Copy, Debug)]
struct Extent {
inner: f64,
reach: f64,
core_reach: f64,
}
impl Extent {
fn of(component: &ColliderComponent, transform: &Transform) -> Option<Self> {
let mut extent: Option<Self> = None;
for part in 0..component.part_count() {
let Some(shape) = ContactShape::placed_part(component, part, transform) else {
continue;
};
let inner = match shape {
ContactShape::Sphere { radius, .. } | ContactShape::Capsule { radius, .. } => {
radius
}
ContactShape::Box { half, .. } => half.min_element(),
ContactShape::Triangle { .. } | ContactShape::Plane { .. } => continue,
};
let this = Self {
inner,
reach: shape.reach_from(transform.position),
core_reach: core_reach(&shape, transform.position),
};
extent = Some(extent.map_or(this, |e| Self {
inner: e.inner.min(this.inner),
reach: e.reach.max(this.reach),
core_reach: e.core_reach.max(this.core_reach),
}));
}
extent
}
}
fn core_reach(shape: &ContactShape, centre: DVec3) -> f64 {
match *shape {
ContactShape::Sphere { centre: c, .. } => (c - centre).length(),
ContactShape::Capsule { a, b, .. } => (a - centre).length().max((b - centre).length()),
ContactShape::Box {
centre: c, half, ..
} => (c - centre).length() + half.length(),
ContactShape::Triangle { .. } => shape.reach_from(centre),
ContactShape::Plane { .. } => 0.0,
}
}
impl ContactPipeline {
pub(crate) fn remember_starts(&mut self, awake: &AwakeSet) {
self.continuous.starts.clear();
self.continuous.starts.extend_from_slice(&awake.transforms);
}
pub(crate) fn sweep(
&mut self,
records: &Pool<BodyRecord>,
statics: &StaticSet,
awake: &mut AwakeSet,
islands: &Islands,
dt: f64,
) {
self.counters.swept = 0;
self.counters.sweep_candidates = 0;
self.counters.sweep_hits = 0;
self.counters.dropped_time = 0.0;
if !self.settings.continuous {
return;
}
let mut scratch = std::mem::take(&mut self.continuous);
for bullets in [false, true] {
for index in 0..awake.ids.len() {
let body = &awake.bodies[index];
if !body.is_dynamic() || body.bullet != bullets {
continue;
}
let id = awake.ids[index];
let Some(record) = records.get(id) else {
continue;
};
let Some((_, component)) = record.collider.as_ref() else {
continue;
};
let (Some(start), end) = (scratch.starts.get(index), awake.transforms[index])
else {
continue;
};
let Some(extent) = Extent::of(component, &end) else {
continue;
};
let path = Path::new(start, &end);
let moved = path.travel.length() + path.turn_rate * extent.core_reach;
let fast = if bullets {
moved > 0.0
} else {
moved >= FAST_FRACTION * extent.inner
};
if !fast {
continue;
}
self.counters.swept += 1;
let bounds = Aabb::new(
start.position.min(end.position),
start.position.max(end.position),
)
.inflated(extent.reach);
self.broadphase
.query_path(&bounds, bullets, &mut scratch.candidates);
let lent = Bodies {
records,
statics,
awake,
islands,
};
let mut fraction = 1.0;
for &proxy in &scratch.candidates {
if matches!(self.owners.get(proxy as usize), Some(Some(Owner::Body(other, _))) if *other == id)
{
continue;
}
let Some(obstacle) = owner_side(&self.owners, &self.planes, proxy, lent) else {
continue;
};
if obstacle.awake.is_some_and(|other| {
awake.bodies[other].bullet && awake.bodies[other].is_dynamic()
}) {
continue;
}
for part in 0..component.part_count() {
let Some(shape) = ContactShape::placed_part(component, part, &end) else {
continue;
};
self.counters.sweep_candidates += 1;
let spin = path.turn_rate * core_reach(&shape, end.position);
let place = |t: f64| {
ContactShape::placed_part(component, part, &path.at(t))
.expect("placed at the end, so placed anywhere")
};
if let Some(t) =
time_of_impact(&obstacle.shape, place, path.travel, spin, fraction)
{
fraction = t;
}
}
}
if fraction < 1.0 {
awake.transforms[index] = path.at(fraction);
self.counters.sweep_hits += 1;
self.counters.dropped_time += (1.0 - fraction) * dt;
}
}
}
self.continuous = scratch;
}
}
fn time_of_impact(
obstacle: &ContactShape,
place: impl Fn(f64) -> ContactShape,
travel: DVec3,
spin: f64,
limit: f64,
) -> Option<f64> {
let start = gap(obstacle, &place(0.0));
let deep = (start.0 - 2.0 * TOLERANCE).min(-LINEAR_SLOP);
let hit = advance(obstacle, &place, travel, spin, start, deep, limit)?;
if start.0 > LINEAR_SLOP + TOLERANCE {
Some(advance(obstacle, &place, travel, spin, start, LINEAR_SLOP, hit).unwrap_or(hit))
} else {
Some(hit)
}
}
pub(crate) fn time_of_contact(
obstacle: &ContactShape,
place: impl Fn(f64) -> ContactShape,
travel: DVec3,
start: (f64, DVec3),
) -> Option<f64> {
advance(obstacle, &place, travel, 0.0, start, 0.0, 1.0)
}
fn advance(
obstacle: &ContactShape,
place: &impl Fn(f64) -> ContactShape,
travel: DVec3,
spin: f64,
start: (f64, DVec3),
target: f64,
limit: f64,
) -> Option<f64> {
let (mut t, (mut distance, mut normal)) = (0.0, start);
for _ in 0..MAX_ADVANCES {
let closing = (-travel.dot(normal)).max(0.0) + spin;
if closing <= 0.0 {
return None;
}
t += (distance - target) / closing;
if t >= limit {
return None;
}
(distance, normal) = gap(obstacle, &place(t));
if distance <= target + TOLERANCE {
return Some(t);
}
}
Some(t)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_path_runs_from_start_to_end_and_bounds_its_turn() {
let start = Transform::new(DVec3::new(1.0, 2.0, 3.0), DQuat::IDENTITY);
let angle = 1.2;
let end = Transform::new(
DVec3::new(4.0, 2.0, 3.0),
crate::rotation_from_scaled_axis(DVec3::Y * angle),
);
let path = Path::new(&start, &end);
assert_eq!(path.at(0.0).position, start.position);
assert!((path.at(1.0).position - end.position).length() < 1e-12);
assert!(path.at(1.0).rotation.dot(end.rotation).abs() > 1.0 - 1e-12);
let expected =
4.0 * crcbl_core::trig::sin(angle / 4.0) / crcbl_core::trig::cos(angle / 4.0);
assert!(
(path.turn_rate - expected).abs() < 1e-12,
"{}",
path.turn_rate
);
assert!(path.turn_rate > angle);
let steps = 1000;
let rate = (0..steps)
.map(|k| {
let (a, b) = (
path.at(f64::from(k) / f64::from(steps)).rotation,
path.at(f64::from(k + 1) / f64::from(steps)).rotation,
);
2.0 * (b * a.conjugate()).xyz().length() * f64::from(steps)
})
.fold(0.0, f64::max);
assert!(rate <= path.turn_rate + 1e-6, "{rate} > {}", path.turn_rate);
assert!(rate > 0.999 * path.turn_rate, "{rate}");
}
#[test]
fn a_ball_through_a_plate_is_stopped_short_of_it() {
let plate = ContactShape::Box {
centre: DVec3::ZERO,
rotation: DQuat::IDENTITY,
half: DVec3::new(0.005, 1.0, 1.0),
};
let radius = 0.05;
let start = DVec3::new(-1.0, 0.0, 0.0);
let travel = DVec3::new(2.0, 0.0, 0.0);
let place = |t: f64| ContactShape::Sphere {
centre: start + travel * t,
radius,
};
let t = time_of_impact(&plate, place, travel, 0.0, 1.0).expect("it crosses the plate");
let (d, _) = gap(&plate, &place(t));
assert!(
(d - LINEAR_SLOP).abs() <= TOLERANCE,
"stopped {d} m from the surface"
);
let to_touch = DVec3::X * (-start.x - 0.005 - radius);
let landing = |t: f64| ContactShape::Sphere {
centre: start + to_touch * t,
radius,
};
assert_eq!(time_of_impact(&plate, landing, to_touch, 0.0, 1.0), None);
let away = |t: f64| ContactShape::Sphere {
centre: start - travel * t,
radius,
};
assert_eq!(time_of_impact(&plate, away, -travel, 0.0, 1.0), None);
assert_eq!(time_of_impact(&plate, place, travel, 0.0, 0.3), None);
}
}