use glam::{DQuat, DVec3};
use crate::broadphase::{Bvh, BvhHit, Ray, Segment};
use crate::collider::{Aabb, BoxCollider, Capsule, LyingCapsule, Sphere};
use crate::components::Transform;
use crate::compound_shape::CompoundShape;
use crate::contact::manifold::gap;
use crate::contact::shape::ContactShape;
use crate::mesh::{MeshScratch, PlacedMesh, TriangleMesh};
use crate::query::{self, OverlapHit, Penetration, ShapeHit, TurnedCapsule};
mod arc_sweep;
mod candidate_sweeps;
mod capsule_sweep;
pub(crate) use capsule_sweep::CapsuleSweepShape;
mod entry;
mod placement;
use entry::{ColliderEntry, PlacedCompound, Primitive};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ColliderId {
index: u32,
generation: u32,
}
impl ColliderId {
#[inline]
#[must_use]
pub const fn index(self) -> u32 {
self.index
}
#[inline]
const fn new(index: u32, generation: u32) -> Self {
Self { index, generation }
}
}
const NO_ELEMENT: u32 = u32::MAX;
pub const ALL_LAYERS: u32 = u32::MAX;
const BROADPHASE_REBUILD_COST_RATIO: f64 = 1.2;
const BROADPHASE_QUALITY_CHECK_REFIT_PASSES: usize = 4;
#[derive(Debug, Clone)]
struct ColliderSlot {
entry: ColliderEntry,
is_trigger: bool,
layers: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryFilter {
pub exclude: Option<ColliderId>,
pub mask: u32,
pub layer_match: LayerMatch,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LayerMatch {
#[default]
Shares,
Within,
}
impl LayerMatch {
const fn admits(self, layers: u32, mask: u32) -> bool {
match self {
Self::Shares => layers & mask != 0,
Self::Within => layers & mask != 0 && layers & !mask == 0,
}
}
}
impl QueryFilter {
pub const ALL: Self = Self {
exclude: None,
mask: ALL_LAYERS,
layer_match: LayerMatch::Shares,
};
#[must_use]
pub const fn excluding(exclude: Option<ColliderId>) -> Self {
Self {
exclude,
mask: ALL_LAYERS,
layer_match: LayerMatch::Shares,
}
}
#[must_use]
pub const fn masked(mask: u32) -> Self {
Self {
exclude: None,
mask,
layer_match: LayerMatch::Shares,
}
}
#[must_use]
pub const fn within(mask: u32) -> Self {
Self {
exclude: None,
mask,
layer_match: LayerMatch::Within,
}
}
#[must_use]
pub const fn with_mask(self, mask: u32) -> Self {
Self { mask, ..self }
}
#[must_use]
pub const fn with_exclude(self, exclude: Option<ColliderId>) -> Self {
Self { exclude, ..self }
}
#[must_use]
pub const fn with_layer_match(self, layer_match: LayerMatch) -> Self {
Self {
layer_match,
..self
}
}
}
impl Default for QueryFilter {
fn default() -> Self {
Self::ALL
}
}
#[derive(Debug, Clone, Copy)]
struct ResolvedFilter {
skip: Option<usize>,
mask: u32,
layer_match: LayerMatch,
solid: bool,
}
impl ResolvedFilter {
fn solid(colliders: &[Option<ColliderSlot>], generations: &[u32], filter: QueryFilter) -> Self {
Self::resolve(colliders, generations, filter, true)
}
fn overlap(
colliders: &[Option<ColliderSlot>],
generations: &[u32],
filter: QueryFilter,
) -> Self {
Self::resolve(colliders, generations, filter, false)
}
fn resolve(
colliders: &[Option<ColliderSlot>],
generations: &[u32],
filter: QueryFilter,
solid: bool,
) -> Self {
Self {
skip: filter
.exclude
.and_then(|id| slot_of_in(colliders, generations, id)),
mask: filter.mask,
layer_match: filter.layer_match,
solid,
}
}
fn admits(&self, idx: usize, slot: &ColliderSlot) -> bool {
Some(idx) != self.skip
&& self.layer_match.admits(slot.layers, self.mask)
&& !(self.solid && slot.is_trigger)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BroadphaseStats {
pub elements: usize,
pub nodes: usize,
pub depth: usize,
pub surface_area_cost: f64,
pub refits: u64,
pub updates_without_refit: u64,
pub rebuilds: u64,
}
#[derive(Debug, Clone, Copy, Default)]
struct BroadphaseCounters {
refits: u64,
updates_without_refit: u64,
rebuilds: u64,
}
pub struct PhysicsWorld {
colliders: Vec<Option<ColliderSlot>>,
generations: Vec<u32>,
free_slots: Vec<u32>,
live_count: usize,
bvh: Option<Bvh>,
bvh_quality_baseline: Option<f64>,
refits_since_quality_check: usize,
counters: BroadphaseCounters,
bvh_slot_to_elem: Vec<u32>,
scratch: QueryScratch,
}
#[derive(Debug, Default)]
pub struct QueryScratch {
stack: Vec<u32>,
candidates: Vec<u32>,
ray_hits: Vec<BvhHit>,
pub(crate) ids: Vec<ColliderId>,
pub(crate) hits: Vec<(ColliderId, OverlapHit)>,
mesh: MeshScratch,
}
impl QueryScratch {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Copy, Debug)]
pub struct OverlapQueries<'a> {
colliders: &'a [Option<ColliderSlot>],
generations: &'a [u32],
bvh: &'a Bvh,
}
impl OverlapQueries<'_> {
pub fn overlap_sphere_into(
&self,
centre: DVec3,
radius: f64,
scratch: &mut QueryScratch,
out: &mut Vec<(ColliderId, OverlapHit)>,
) {
self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, scratch, out);
}
pub fn overlap_sphere_filtered_into(
&self,
centre: DVec3,
radius: f64,
filter: QueryFilter,
scratch: &mut QueryScratch,
out: &mut Vec<(ColliderId, OverlapHit)>,
) {
out.clear();
overlap_sphere_core(
self.bvh,
self.colliders,
self.generations,
&Sphere::new(centre, radius),
filter,
scratch,
|id, hit| out.push((id, hit)),
);
}
pub fn overlap_sphere_ids_into(
&self,
centre: DVec3,
radius: f64,
scratch: &mut QueryScratch,
out: &mut Vec<ColliderId>,
) {
out.clear();
overlap_sphere_core(
self.bvh,
self.colliders,
self.generations,
&Sphere::new(centre, radius),
QueryFilter::ALL,
scratch,
|id, _| out.push(id),
);
}
pub fn overlap_aabb_into(
&self,
aabb: &Aabb,
scratch: &mut QueryScratch,
out: &mut Vec<ColliderId>,
) {
self.overlap_aabb_filtered_into(aabb, QueryFilter::ALL, scratch, out);
}
pub fn overlap_aabb_filtered_into(
&self,
aabb: &Aabb,
filter: QueryFilter,
scratch: &mut QueryScratch,
out: &mut Vec<ColliderId>,
) {
overlap_aabb_core(
self.bvh,
self.colliders,
self.generations,
aabb,
filter,
scratch,
out,
);
}
#[must_use]
pub fn cast_ray(
&self,
ray: &Ray,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
self.cast_ray_excluding(ray, None, scratch)
}
#[must_use]
pub fn cast_ray_excluding(
&self,
ray: &Ray,
exclude: Option<ColliderId>,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
self.cast_ray_filtered(ray, QueryFilter::excluding(exclude), scratch)
}
#[must_use]
pub fn cast_ray_filtered(
&self,
ray: &Ray,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
cast_ray_core(
self.bvh,
self.colliders,
self.generations,
ray,
filter,
scratch,
)
}
#[must_use]
pub fn sweep_sphere(
&self,
segment: &Segment,
radius: f64,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_sphere_excluding(segment, radius, None, scratch)
}
#[must_use]
pub fn sweep_sphere_excluding(
&self,
segment: &Segment,
radius: f64,
exclude: Option<ColliderId>,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_sphere_filtered(segment, radius, QueryFilter::excluding(exclude), scratch)
}
#[must_use]
pub fn sweep_sphere_filtered(
&self,
segment: &Segment,
radius: f64,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
let mut closest = None;
sweep_sphere_hits(*self, segment, radius, filter, scratch, |id, hit| {
keep_closest(&mut closest, id, hit);
});
closest
}
#[must_use]
pub fn sweep_capsule(
&self,
segment: &Segment,
radius: f64,
half_height: f64,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_capsule_excluding(segment, radius, half_height, None, scratch)
}
#[must_use]
pub fn sweep_capsule_excluding(
&self,
segment: &Segment,
radius: f64,
half_height: f64,
exclude: Option<ColliderId>,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_capsule_filtered(
segment,
radius,
half_height,
QueryFilter::excluding(exclude),
scratch,
)
}
#[must_use]
pub fn sweep_capsule_filtered(
&self,
segment: &Segment,
radius: f64,
half_height: f64,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
let capsule = Capsule::new(segment.start, radius, half_height);
self.sweep_upright_where(&capsule, segment.end, filter, scratch, |_| true)
}
pub fn capsule_penetrations_into(
&self,
capsule: &Capsule,
exclude: Option<ColliderId>,
scratch: &mut QueryScratch,
out: &mut Vec<(ColliderId, Penetration)>,
) {
self.capsule_penetrations_filtered_into(
capsule,
QueryFilter::excluding(exclude),
scratch,
out,
);
}
pub fn capsule_penetrations_filtered_into(
&self,
capsule: &Capsule,
filter: QueryFilter,
scratch: &mut QueryScratch,
out: &mut Vec<(ColliderId, Penetration)>,
) {
capsule_penetrations_core(
self.bvh,
self.colliders,
self.generations,
capsule,
filter,
scratch,
out,
);
}
pub(crate) fn capsule_contact_normals_into(
&self,
capsule: &Capsule,
filter: QueryFilter,
scratch: &mut QueryScratch,
out: &mut Vec<DVec3>,
) {
let filter = ResolvedFilter::solid(self.colliders, self.generations, filter);
self.bvh
.traverse_aabb_into(&capsule.aabb(), &mut scratch.stack, &mut scratch.candidates);
for &element in scratch.candidates.iter() {
let idx = element as usize;
let Some(Some(slot)) = self.colliders.get(idx) else {
continue;
};
if !filter.admits(idx, slot) {
continue;
}
for (_, shape) in slot.entry.primitives() {
let penetration = match shape {
Primitive::Sphere(s) => query::capsule_penetration_vs_sphere(capsule, s),
Primitive::Box(b) => query::capsule_penetration_vs_box(capsule, b),
Primitive::Capsule(c) => {
query::capsule_penetration_vs_turned_capsule(capsule, c)
}
Primitive::Mesh(m) => {
m.capsule_contact_normals(capsule, &mut scratch.mesh, out);
None
}
};
out.extend(penetration.map(|penetration| penetration.normal));
}
}
}
#[must_use]
pub fn lying_capsule_blocker(
&self,
capsule: &LyingCapsule,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<ColliderId> {
lying_capsule_blocker_core(
self.bvh,
self.colliders,
self.generations,
capsule,
filter,
scratch,
)
}
pub(crate) fn sweep_lying_capsule(
&self,
capsule: &LyingCapsule,
motion: DVec3,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, SweptContact)> {
self.sweep_capsule_shape(
CapsuleSweepShape::Lying(*capsule),
motion,
filter,
scratch,
|_| true,
)
.map(|(id, hit)| (id, hit.contact))
}
}
fn overlap_sphere_core(
bvh: &Bvh,
colliders: &[Option<ColliderSlot>],
generations: &[u32],
query_sphere: &Sphere,
filter: QueryFilter,
scratch: &mut QueryScratch,
mut keep: impl FnMut(ColliderId, OverlapHit),
) {
let filter = ResolvedFilter::overlap(colliders, generations, filter);
let query_aabb = Aabb::from_centre_half(query_sphere.centre, DVec3::splat(query_sphere.radius));
bvh.traverse_aabb_into(&query_aabb, &mut scratch.stack, &mut scratch.candidates);
for &element in scratch.candidates.iter() {
let idx = element as usize;
let Some(Some(slot)) = colliders.get(idx) else {
continue;
};
if !filter.admits(idx, slot) {
continue;
}
let mut deepest: Option<OverlapHit> = None;
for (part, shape) in slot.entry.primitives() {
let hit = match shape {
Primitive::Sphere(s) => query::sphere_overlap_vs_sphere(query_sphere, s),
Primitive::Box(b) => query::sphere_overlap_vs_box(query_sphere, b),
Primitive::Capsule(c) => query::sphere_overlap_vs_turned_capsule(query_sphere, c),
Primitive::Mesh(m) => m.sphere_overlap(query_sphere, &mut scratch.mesh),
};
if let Some(hit) = hit
&& deepest.is_none_or(|deepest| hit.depth > deepest.depth)
{
deepest = Some(OverlapHit { part, ..hit });
}
}
if let Some(hit) = deepest {
keep(id_for_slot_in(generations, element), hit);
}
}
}
fn overlap_aabb_core(
bvh: &Bvh,
colliders: &[Option<ColliderSlot>],
generations: &[u32],
aabb: &Aabb,
filter: QueryFilter,
scratch: &mut QueryScratch,
out: &mut Vec<ColliderId>,
) {
let filter = ResolvedFilter::overlap(colliders, generations, filter);
bvh.traverse_aabb_into(aabb, &mut scratch.stack, &mut scratch.candidates);
out.clear();
for &slot in &scratch.candidates {
let admitted = colliders
.get(slot as usize)
.and_then(|s| s.as_ref())
.filter(|data| filter.admits(slot as usize, data))
.is_some_and(|data| {
data.entry.primitives().any(|(_, shape)| match shape {
Primitive::Mesh(m) => m.overlaps_aabb(aabb, &mut scratch.mesh),
Primitive::Box(b) => query::aabb_overlaps_box(aabb, b),
Primitive::Sphere(_) | Primitive::Capsule(_) => true,
})
});
if admitted {
out.push(id_for_slot_in(generations, slot));
}
}
}
fn cast_ray_core(
bvh: &Bvh,
colliders: &[Option<ColliderSlot>],
generations: &[u32],
ray: &Ray,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
let mut hits = core::mem::take(&mut scratch.ray_hits);
bvh.traverse_ray_into(ray, &mut scratch.stack, &mut hits);
let filter = ResolvedFilter::solid(colliders, generations, filter);
let best = closest_hit_core(
colliders,
generations,
ray,
&hits,
filter,
&mut scratch.mesh,
);
scratch.ray_hits = hits;
best
}
fn sweep_sphere_hits(
view: OverlapQueries<'_>,
segment: &Segment,
radius: f64,
filter: QueryFilter,
scratch: &mut QueryScratch,
visit: impl FnMut(ColliderId, ShapeHit),
) {
let filter = ResolvedFilter::solid(view.colliders, view.generations, filter);
let bounds = swept_bounds(segment, DVec3::splat(radius));
view.bvh
.traverse_aabb_into(&bounds, &mut scratch.stack, &mut scratch.candidates);
swept_hits_core(
view.colliders,
view.generations,
&scratch.candidates,
filter,
|_, _, shape| match shape {
Primitive::Sphere(s) => query::swept_sphere_vs_sphere(segment, radius, s),
Primitive::Box(b) => query::swept_sphere_vs_box(segment, radius, b),
Primitive::Capsule(c) => query::swept_sphere_vs_turned_capsule(segment, radius, c),
Primitive::Mesh(m) => m.sweep(segment, radius, DVec3::ZERO, &mut scratch.mesh),
},
visit,
);
}
fn sweep_capsule_hits(
view: OverlapQueries<'_>,
capsule: &Capsule,
end: DVec3,
filter: QueryFilter,
scratch: &mut QueryScratch,
accept: impl Fn(&ShapeHit) -> bool,
visit: impl FnMut(ColliderId, ShapeHit),
) {
let Capsule {
radius,
half_height,
..
} = *capsule;
let segment = &Segment::new(capsule.centre, end);
let filter = ResolvedFilter::solid(view.colliders, view.generations, filter);
let bounds = swept_bounds(segment, DVec3::new(radius, radius + half_height, radius));
view.bvh
.traverse_aabb_into(&bounds, &mut scratch.stack, &mut scratch.candidates);
swept_hits_core(
view.colliders,
view.generations,
&scratch.candidates,
filter,
|_, _, shape| {
let hit = match shape {
Primitive::Sphere(s) => {
query::swept_capsule_vs_sphere(segment, radius, half_height, s)
}
Primitive::Box(b) => query::swept_capsule_vs_box(segment, radius, half_height, b),
Primitive::Capsule(c) => {
query::swept_capsule_vs_turned_capsule(segment, radius, half_height, c)
}
Primitive::Mesh(m) => m.sweep_where(
segment,
radius,
DVec3::Y * half_height,
&mut scratch.mesh,
&accept,
),
}?;
accept(&hit).then_some(hit)
},
visit,
);
}
fn capsule_penetrations_core(
bvh: &Bvh,
colliders: &[Option<ColliderSlot>],
generations: &[u32],
capsule: &Capsule,
filter: QueryFilter,
scratch: &mut QueryScratch,
out: &mut Vec<(ColliderId, Penetration)>,
) {
out.clear();
let filter = ResolvedFilter::solid(colliders, generations, filter);
bvh.traverse_aabb_into(&capsule.aabb(), &mut scratch.stack, &mut scratch.candidates);
for &element in scratch.candidates.iter() {
let idx = element as usize;
let Some(Some(slot)) = colliders.get(idx) else {
continue;
};
if !filter.admits(idx, slot) {
continue;
}
let mut deepest: Option<Penetration> = None;
for (_, shape) in slot.entry.primitives() {
let penetration = match shape {
Primitive::Sphere(s) => query::capsule_penetration_vs_sphere(capsule, s),
Primitive::Box(b) => query::capsule_penetration_vs_box(capsule, b),
Primitive::Capsule(c) => query::capsule_penetration_vs_turned_capsule(capsule, c),
Primitive::Mesh(m) => m.capsule_penetration(capsule, &mut scratch.mesh),
};
if let Some(penetration) = penetration
&& deepest.is_none_or(|deepest| penetration.depth > deepest.depth)
{
deepest = Some(penetration);
}
}
if let Some(penetration) = deepest {
out.push((id_for_slot_in(generations, element), penetration));
}
}
}
fn lying_capsule_blocker_core(
bvh: &Bvh,
colliders: &[Option<ColliderSlot>],
generations: &[u32],
capsule: &LyingCapsule,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<ColliderId> {
let filter = ResolvedFilter::solid(colliders, generations, filter);
bvh.traverse_aabb_into(&capsule.aabb(), &mut scratch.stack, &mut scratch.candidates);
let (head, feet) = (capsule.head, capsule.feet());
let lying = ContactShape::Capsule {
a: head,
b: feet,
radius: capsule.radius,
};
let inside = |target: ContactShape| gap(&lying, &target).0 < 0.0;
for &element in scratch.candidates.iter() {
let idx = element as usize;
let Some(Some(slot)) = colliders.get(idx) else {
continue;
};
if !filter.admits(idx, slot) {
continue;
}
let blocked = slot.entry.primitives().any(|(_, shape)| match shape {
Primitive::Sphere(s) => inside(ContactShape::Sphere {
centre: s.centre,
radius: s.radius,
}),
Primitive::Box(b) => inside(query::contact_box(b)),
Primitive::Capsule(c) => inside(c.contact_shape()),
Primitive::Mesh(m) => m
.turned_capsule_penetration(
(head + feet) * 0.5,
(head - feet) * 0.5,
capsule.radius,
&mut scratch.mesh,
)
.is_some(),
});
if blocked {
return Some(id_for_slot_in(generations, element));
}
}
None
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct SweptContact {
pub(crate) t: f64,
pub(crate) normal: DVec3,
pub(crate) started_inside: bool,
pub(crate) part: usize,
}
impl From<ShapeHit> for SweptContact {
fn from(hit: ShapeHit) -> Self {
Self {
t: hit.t,
normal: hit.normal,
started_inside: hit.started_inside,
part: hit.part,
}
}
}
fn swept_bounds(segment: &Segment, half_extents: DVec3) -> Aabb {
Aabb::new(
segment.start.min(segment.end) - half_extents,
segment.start.max(segment.end) + half_extents,
)
}
fn closest_hit_core(
colliders: &[Option<ColliderSlot>],
generations: &[u32],
ray: &Ray,
bvh_hits: &[BvhHit],
filter: ResolvedFilter,
mesh: &mut MeshScratch,
) -> Option<(ColliderId, ShapeHit)> {
let mut best: Option<(f64, ColliderId, ShapeHit)> = None;
for bvh_hit in bvh_hits {
let idx = bvh_hit.element_id as usize;
let Some(Some(slot)) = colliders.get(idx) else {
continue;
};
if !filter.admits(idx, slot) {
continue;
}
for (part, shape) in slot.entry.primitives() {
let hit = match shape {
Primitive::Sphere(s) => query::ray_vs_sphere(ray, s),
Primitive::Box(b) => query::ray_vs_box(ray, b),
Primitive::Capsule(c) => query::ray_vs_turned_capsule(ray, c),
Primitive::Mesh(m) => m.cast_ray(ray, mesh),
};
if let Some(hit) = hit
&& hit.t < best.as_ref().map_or(f64::INFINITY, |&(t, _, _)| t)
{
let id = id_for_slot_in(generations, bvh_hit.element_id);
best = Some((hit.t, id, ShapeHit { part, ..hit }));
}
}
}
best.map(|(_, id, hit)| (id, hit))
}
fn swept_hits_core<H: SweptHit>(
colliders: &[Option<ColliderSlot>],
generations: &[u32],
candidates: &[u32],
filter: ResolvedFilter,
mut narrow: impl FnMut(ColliderId, usize, Primitive<'_>) -> Option<H>,
mut visit: impl FnMut(ColliderId, H),
) {
for &element in candidates {
let idx = element as usize;
let Some(Some(slot)) = colliders.get(idx) else {
continue;
};
if !filter.admits(idx, slot) {
continue;
}
for (part, shape) in slot.entry.primitives() {
if let Some(hit) = narrow(id_for_slot_in(generations, element), part, shape)
&& hit.t() < f64::INFINITY
{
visit(id_for_slot_in(generations, element), hit.with_part(part));
}
}
}
}
fn closest_swept_core<H: SweptHit>(
colliders: &[Option<ColliderSlot>],
generations: &[u32],
candidates: &[u32],
filter: ResolvedFilter,
mut narrow: impl FnMut(Primitive<'_>) -> Option<H>,
) -> Option<(ColliderId, H)> {
let mut closest = None;
swept_hits_core(
colliders,
generations,
candidates,
filter,
|_, _, shape| narrow(shape),
|id, hit| {
keep_closest(&mut closest, id, hit);
},
);
closest
}
fn keep_closest<H: SweptHit>(closest: &mut Option<(ColliderId, H)>, id: ColliderId, hit: H) {
if closest.as_ref().is_none_or(|&(best, best_hit)| {
sweep_order(
(id, hit.part_index(), hit.t()),
(best, best_hit.part_index(), best_hit.t()),
)
.is_lt()
}) {
*closest = Some((id, hit));
}
}
fn sweep_order(a: (ColliderId, usize, f64), b: (ColliderId, usize, f64)) -> std::cmp::Ordering {
if a.2 < b.2 {
std::cmp::Ordering::Less
} else if b.2 < a.2 {
std::cmp::Ordering::Greater
} else {
(a.0.index, a.1).cmp(&(b.0.index, b.1))
}
}
trait SweptHit: Copy {
fn t(&self) -> f64;
fn part_index(&self) -> usize;
#[must_use]
fn with_part(self, part: usize) -> Self;
}
impl SweptHit for ShapeHit {
fn t(&self) -> f64 {
self.t
}
fn part_index(&self) -> usize {
self.part
}
fn with_part(self, part: usize) -> Self {
Self { part, ..self }
}
}
impl SweptHit for SweptContact {
fn t(&self) -> f64 {
self.t
}
fn part_index(&self) -> usize {
self.part
}
fn with_part(self, part: usize) -> Self {
Self { part, ..self }
}
}
fn slot_of_in(
colliders: &[Option<ColliderSlot>],
generations: &[u32],
id: ColliderId,
) -> Option<usize> {
let slot = id.index as usize;
if generations.get(slot).copied() != Some(id.generation) {
return None;
}
colliders.get(slot).and_then(|s| s.as_ref()).map(|_| slot)
}
fn id_for_slot_in(generations: &[u32], slot: u32) -> ColliderId {
ColliderId::new(slot, generations[slot as usize])
}
impl PhysicsWorld {
#[must_use]
pub fn new() -> Self {
Self {
colliders: Vec::new(),
generations: Vec::new(),
free_slots: Vec::new(),
live_count: 0,
bvh: None,
bvh_quality_baseline: None,
refits_since_quality_check: 0,
counters: BroadphaseCounters::default(),
bvh_slot_to_elem: Vec::new(),
scratch: QueryScratch::new(),
}
}
pub fn add_sphere(&mut self, sphere: Sphere) -> ColliderId {
self.add(ColliderEntry::Sphere(sphere))
}
pub fn add_box(&mut self, box_collider: BoxCollider) -> ColliderId {
self.add(ColliderEntry::Box(box_collider))
}
pub fn add_capsule(&mut self, capsule: Capsule) -> ColliderId {
self.add(ColliderEntry::Capsule(TurnedCapsule::upright(capsule)))
}
pub(crate) fn add_turned_capsule(&mut self, capsule: Capsule, rotation: DQuat) -> ColliderId {
self.add(ColliderEntry::Capsule(TurnedCapsule::new(
capsule, rotation,
)))
}
pub fn add_mesh(&mut self, mesh: TriangleMesh, transform: Transform) -> ColliderId {
self.add(ColliderEntry::Mesh(PlacedMesh::new(mesh, transform)))
}
pub fn add_compound(
&mut self,
shape: &CompoundShape,
offset: DVec3,
transform: &Transform,
) -> ColliderId {
self.add(ColliderEntry::Compound(PlacedCompound::place(
Vec::new(),
shape,
offset,
transform,
)))
}
pub fn set_sphere(&mut self, id: ColliderId, sphere: Sphere) -> bool {
self.set(id, ColliderEntry::Sphere(sphere))
}
pub fn set_box(&mut self, id: ColliderId, box_collider: BoxCollider) -> bool {
self.set(id, ColliderEntry::Box(box_collider))
}
pub fn set_capsule(&mut self, id: ColliderId, capsule: Capsule) -> bool {
self.set(id, ColliderEntry::Capsule(TurnedCapsule::upright(capsule)))
}
pub(crate) fn set_turned_capsule(
&mut self,
id: ColliderId,
capsule: Capsule,
rotation: DQuat,
) -> bool {
self.set(
id,
ColliderEntry::Capsule(TurnedCapsule::new(capsule, rotation)),
)
}
pub fn set_mesh(&mut self, id: ColliderId, mesh: TriangleMesh, transform: Transform) -> bool {
self.set(id, ColliderEntry::Mesh(PlacedMesh::new(mesh, transform)))
}
pub fn set_compound(
&mut self,
id: ColliderId,
shape: &CompoundShape,
offset: DVec3,
transform: &Transform,
) -> bool {
let Some(slot) = self.slot_of(id) else {
return false;
};
let buffer = match self.colliders[slot].as_mut().map(|s| &mut s.entry) {
Some(ColliderEntry::Compound(placed)) => placed.take_parts(),
_ => Vec::new(),
};
self.set(
id,
ColliderEntry::Compound(PlacedCompound::place(buffer, shape, offset, transform)),
)
}
pub fn set_trigger(&mut self, id: ColliderId, is_trigger: bool) -> bool {
let Some(slot) = self.slot_of(id) else {
return false;
};
if let Some(slot_data) = self.colliders[slot].as_mut() {
slot_data.is_trigger = is_trigger;
}
true
}
pub fn is_trigger(&self, id: ColliderId) -> bool {
self.slot_of(id)
.is_some_and(|slot| self.colliders[slot].as_ref().is_some_and(|s| s.is_trigger))
}
pub fn set_layers(&mut self, id: ColliderId, bits: u32) -> bool {
let Some(slot) = self.slot_of(id) else {
return false;
};
if let Some(slot_data) = self.colliders[slot].as_mut() {
slot_data.layers = bits;
}
true
}
#[must_use]
pub fn layers(&self, id: ColliderId) -> Option<u32> {
let slot = self.slot_of(id)?;
self.colliders[slot].as_ref().map(|s| s.layers)
}
pub fn remove(&mut self, id: ColliderId) -> bool {
let Some(slot) = self.slot_of(id) else {
return false;
};
self.colliders[slot] = None;
self.generations[slot] = self.generations[slot].wrapping_add(1);
self.free_slots.push(slot as u32);
self.live_count -= 1;
if let Some(bvh) = self.bvh.as_mut() {
match self.bvh_slot_to_elem.get(slot).copied() {
Some(elem) if elem != NO_ELEMENT && bvh.remove(elem as usize) => {
self.bvh_slot_to_elem[slot] = NO_ELEMENT;
self.bvh_quality_baseline = None;
self.refits_since_quality_check = 0;
}
_ => self.invalidate_bvh(),
}
}
true
}
pub fn rebuild(&mut self) {
let elements: Vec<_> = self
.colliders
.iter()
.enumerate()
.filter_map(|(idx, slot)| slot.as_ref().map(|s| (s.entry.aabb(), idx as u32)))
.collect();
self.bvh_slot_to_elem = vec![NO_ELEMENT; self.colliders.len()];
for (elem_idx, (_, slot)) in elements.iter().enumerate() {
self.bvh_slot_to_elem[*slot as usize] = elem_idx as u32;
}
let bvh = Bvh::build(elements);
self.bvh_quality_baseline = Some(bvh.normalized_surface_area_cost());
self.refits_since_quality_check = 0;
self.bvh = Some(bvh);
self.counters.rebuilds += 1;
}
#[must_use]
pub fn len(&self) -> usize {
self.live_count
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.live_count == 0
}
#[must_use]
pub fn overlap_sphere(&mut self, centre: DVec3, radius: f64) -> Vec<(ColliderId, OverlapHit)> {
let mut out = Vec::new();
self.overlap_sphere_into(centre, radius, &mut out);
out
}
pub fn overlap_sphere_into(
&mut self,
centre: DVec3,
radius: f64,
out: &mut Vec<(ColliderId, OverlapHit)>,
) {
self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, out);
}
#[must_use]
pub fn overlap_sphere_filtered(
&mut self,
centre: DVec3,
radius: f64,
filter: QueryFilter,
) -> Vec<(ColliderId, OverlapHit)> {
let mut out = Vec::new();
self.overlap_sphere_filtered_into(centre, radius, filter, &mut out);
out
}
pub fn overlap_sphere_filtered_into(
&mut self,
centre: DVec3,
radius: f64,
filter: QueryFilter,
out: &mut Vec<(ColliderId, OverlapHit)>,
) {
let mut scratch = core::mem::take(&mut self.scratch);
self.overlap_queries().overlap_sphere_filtered_into(
centre,
radius,
filter,
&mut scratch,
out,
);
self.scratch = scratch;
}
pub fn overlap_queries(&mut self) -> OverlapQueries<'_> {
self.overlap_queries_with_scratch().0
}
pub(crate) fn overlap_queries_with_scratch(
&mut self,
) -> (OverlapQueries<'_>, &mut QueryScratch) {
self.ensure_bvh();
let view = OverlapQueries {
colliders: &self.colliders,
generations: &self.generations,
bvh: self.bvh.as_ref().expect("ensure_bvh built it"),
};
(view, &mut self.scratch)
}
#[must_use]
pub fn overlap_aabb(&mut self, aabb: &Aabb) -> Vec<ColliderId> {
self.overlap_aabb_filtered(aabb, QueryFilter::ALL)
}
#[must_use]
pub fn overlap_aabb_filtered(&mut self, aabb: &Aabb, filter: QueryFilter) -> Vec<ColliderId> {
let mut scratch = core::mem::take(&mut self.scratch);
let mut out = Vec::new();
self.overlap_queries()
.overlap_aabb_filtered_into(aabb, filter, &mut scratch, &mut out);
self.scratch = scratch;
out
}
#[must_use]
pub fn cast_ray(&mut self, ray: &Ray) -> Option<(ColliderId, ShapeHit)> {
self.cast_ray_excluding(ray, None)
}
#[must_use]
pub fn cast_ray_excluding(
&mut self,
ray: &Ray,
exclude: Option<ColliderId>,
) -> Option<(ColliderId, ShapeHit)> {
self.cast_ray_filtered(ray, QueryFilter::excluding(exclude))
}
#[must_use]
pub fn cast_ray_filtered(
&mut self,
ray: &Ray,
filter: QueryFilter,
) -> Option<(ColliderId, ShapeHit)> {
let mut scratch = core::mem::take(&mut self.scratch);
let hit = self
.overlap_queries()
.cast_ray_filtered(ray, filter, &mut scratch);
self.scratch = scratch;
hit
}
#[must_use]
pub fn sweep_sphere(
&mut self,
segment: &Segment,
radius: f64,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_sphere_excluding(segment, radius, None)
}
#[must_use]
pub fn sweep_sphere_excluding(
&mut self,
segment: &Segment,
radius: f64,
exclude: Option<ColliderId>,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_sphere_filtered(segment, radius, QueryFilter::excluding(exclude))
}
#[must_use]
pub fn sweep_sphere_filtered(
&mut self,
segment: &Segment,
radius: f64,
filter: QueryFilter,
) -> Option<(ColliderId, ShapeHit)> {
let mut scratch = core::mem::take(&mut self.scratch);
let hit =
self.overlap_queries()
.sweep_sphere_filtered(segment, radius, filter, &mut scratch);
self.scratch = scratch;
hit
}
#[must_use]
pub fn sweep_capsule(
&mut self,
segment: &Segment,
radius: f64,
half_height: f64,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_capsule_excluding(segment, radius, half_height, None)
}
#[must_use]
pub fn sweep_capsule_excluding(
&mut self,
segment: &Segment,
radius: f64,
half_height: f64,
exclude: Option<ColliderId>,
) -> Option<(ColliderId, ShapeHit)> {
self.sweep_capsule_filtered(
segment,
radius,
half_height,
QueryFilter::excluding(exclude),
)
}
#[must_use]
pub fn sweep_capsule_filtered(
&mut self,
segment: &Segment,
radius: f64,
half_height: f64,
filter: QueryFilter,
) -> Option<(ColliderId, ShapeHit)> {
let mut scratch = core::mem::take(&mut self.scratch);
let hit = self.overlap_queries().sweep_capsule_filtered(
segment,
radius,
half_height,
filter,
&mut scratch,
);
self.scratch = scratch;
hit
}
pub fn capsule_penetrations_into(
&mut self,
capsule: &Capsule,
exclude: Option<ColliderId>,
out: &mut Vec<(ColliderId, Penetration)>,
) {
self.capsule_penetrations_filtered_into(capsule, QueryFilter::excluding(exclude), out);
}
pub fn capsule_penetrations_filtered_into(
&mut self,
capsule: &Capsule,
filter: QueryFilter,
out: &mut Vec<(ColliderId, Penetration)>,
) {
let mut scratch = core::mem::take(&mut self.scratch);
self.overlap_queries().capsule_penetrations_filtered_into(
capsule,
filter,
&mut scratch,
out,
);
self.scratch = scratch;
}
#[must_use]
pub fn lying_capsule_blocker(
&mut self,
capsule: &LyingCapsule,
filter: QueryFilter,
) -> Option<ColliderId> {
let mut scratch = core::mem::take(&mut self.scratch);
let blocker = self
.overlap_queries()
.lying_capsule_blocker(capsule, filter, &mut scratch);
self.scratch = scratch;
blocker
}
#[cfg(test)]
pub(crate) fn sweep_lying_capsule(
&mut self,
capsule: &LyingCapsule,
motion: DVec3,
filter: QueryFilter,
) -> Option<(ColliderId, SweptContact)> {
let (view, scratch) = self.overlap_queries_with_scratch();
view.sweep_lying_capsule(capsule, motion, filter, scratch)
}
#[must_use]
pub fn aabb_of(&self, id: ColliderId) -> Option<Aabb> {
let slot = self.slot_of(id)?;
self.colliders[slot].as_ref().map(|s| s.entry.aabb())
}
#[must_use]
pub fn broadphase_stats(&mut self) -> BroadphaseStats {
self.ensure_bvh();
let bvh = self.bvh.as_ref().expect("ensure_bvh built it");
BroadphaseStats {
elements: bvh.len(),
nodes: bvh.node_count(),
depth: bvh.depth(),
surface_area_cost: bvh.surface_area_cost(),
refits: self.counters.refits,
updates_without_refit: self.counters.updates_without_refit,
rebuilds: self.counters.rebuilds,
}
}
fn slot_of(&self, id: ColliderId) -> Option<usize> {
slot_of_in(&self.colliders, &self.generations, id)
}
fn id_for_slot(&self, slot: u32) -> ColliderId {
id_for_slot_in(&self.generations, slot)
}
fn add(&mut self, entry: ColliderEntry) -> ColliderId {
let aabb = entry.aabb();
let slot_data = ColliderSlot {
entry,
is_trigger: false,
layers: ALL_LAYERS,
};
let index = if let Some(slot) = self.free_slots.pop() {
self.colliders[slot as usize] = Some(slot_data);
slot
} else {
let idx = self.colliders.len() as u32;
self.colliders.push(Some(slot_data));
self.generations.push(0);
idx
};
self.live_count += 1;
if let Some(bvh) = self.bvh.as_mut() {
let elem = bvh.insert(aabb, index);
if self.bvh_slot_to_elem.len() <= index as usize {
self.bvh_slot_to_elem.resize(index as usize + 1, NO_ELEMENT);
}
self.bvh_slot_to_elem[index as usize] = elem as u32;
self.bvh_quality_baseline = None;
self.refits_since_quality_check = 0;
}
self.id_for_slot(index)
}
fn invalidate_bvh(&mut self) {
self.bvh = None;
self.bvh_quality_baseline = None;
self.refits_since_quality_check = 0;
self.bvh_slot_to_elem.clear();
}
fn set(&mut self, id: ColliderId, entry: ColliderEntry) -> bool {
let Some(slot) = self.slot_of(id) else {
return false;
};
let new_aabb = entry.aabb();
if let Some(slot_data) = self.colliders[slot].as_mut() {
slot_data.entry = entry;
}
let refit = match self.bvh {
Some(ref mut bvh) => match self.bvh_slot_to_elem.get(slot).copied() {
Some(elem) if elem != NO_ELEMENT => bvh.update_aabb(elem as usize, new_aabb),
_ => false,
},
None => false,
};
if refit {
self.counters.refits += 1;
self.refits_since_quality_check = self.refits_since_quality_check.saturating_add(1);
} else {
self.counters.updates_without_refit += 1;
self.invalidate_bvh();
}
true
}
fn ensure_bvh(&mut self) {
if self.bvh.is_none() {
self.rebuild();
return;
}
let bvh = self.bvh.as_ref().expect("the absent tree returned above");
if self.bvh_quality_baseline.is_none() {
self.bvh_quality_baseline = Some(bvh.normalized_surface_area_cost());
self.refits_since_quality_check = 0;
return;
}
let refits_per_check = self
.live_count
.saturating_mul(BROADPHASE_QUALITY_CHECK_REFIT_PASSES)
.max(1);
if self.refits_since_quality_check < refits_per_check {
return;
}
let current_cost = bvh.normalized_surface_area_cost();
self.refits_since_quality_check = 0;
let baseline = self
.bvh_quality_baseline
.expect("the absent baseline returned above");
if current_cost > baseline * BROADPHASE_REBUILD_COST_RATIO {
self.rebuild();
}
}
}
impl Default for PhysicsWorld {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for PhysicsWorld {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PhysicsWorld")
.field("collider_count", &self.len())
.field("bvh_cached", &self.bvh.is_some())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
pub(super) fn ids_of(hits: &[(ColliderId, OverlapHit)]) -> Vec<ColliderId> {
hits.iter().map(|&(id, _)| id).collect()
}
#[test]
fn empty_world_is_empty() {
let world = PhysicsWorld::new();
assert!(world.is_empty());
assert_eq!(world.len(), 0);
}
#[test]
fn broadphase_stats_report_the_trees_shape() {
let mut world = PhysicsWorld::new();
assert_eq!(
world.broadphase_stats(),
BroadphaseStats {
elements: 0,
nodes: 0,
depth: 0,
surface_area_cost: 0.0,
refits: 0,
updates_without_refit: 0,
rebuilds: 1,
},
"an empty world has an empty tree, built by the reading itself"
);
for x in 0..16 {
world.add_sphere(Sphere::new(DVec3::new(f64::from(x), 0.0, 0.0), 0.4));
}
let stats = world.broadphase_stats();
assert_eq!(stats.elements, 16, "every collider is a leaf");
assert!(
stats.nodes >= 16,
"a binary tree holds at least one node per leaf; got {stats:?}"
);
assert!(
stats.depth >= 1,
"a non-empty tree has a depth; got {stats:?}"
);
}
fn line_of_spheres(n: u32) -> (PhysicsWorld, Vec<ColliderId>) {
let mut world = PhysicsWorld::new();
let ids = (0..n)
.map(|x| world.add_sphere(Sphere::new(DVec3::new(f64::from(x), 0.0, 0.0), 0.4)))
.collect();
(world, ids)
}
#[test]
fn a_small_update_is_counted_as_a_refit() {
let (mut world, ids) = line_of_spheres(16);
let before = world.broadphase_stats();
assert_eq!(before.rebuilds, 1, "the reading itself built the tree");
assert_eq!(before.refits, 0, "and nothing has been updated yet");
assert!(world.set_sphere(ids[7], Sphere::new(DVec3::new(7.05, 0.0, 0.0), 0.4)));
let after = world.broadphase_stats();
assert_eq!(
after.refits,
before.refits + 1,
"the update should have refit the tree in place; got {after:?}"
);
assert_eq!(
after.updates_without_refit, before.updates_without_refit,
"nothing should have been left for a rebuild; got {after:?}"
);
assert_eq!(
after.rebuilds, before.rebuilds,
"and no rebuild should have happened; got {after:?}"
);
}
#[test]
fn a_teleport_refits_rather_than_rebuilding() {
let (mut world, ids) = line_of_spheres(16);
let before = world.broadphase_stats();
assert!(world.set_sphere(ids[7], Sphere::new(DVec3::new(0.0, 900.0, 0.0), 0.4)));
let after = world.broadphase_stats();
assert_eq!(
after.refits,
before.refits + 1,
"a teleport is still a refit; got {after:?}"
);
assert_eq!(
after.rebuilds, before.rebuilds,
"and costs no rebuild; got {after:?}"
);
assert_eq!(
after.updates_without_refit, before.updates_without_refit,
"and leaves nothing for one; got {after:?}"
);
assert_eq!(
ids_of(&world.overlap_sphere(DVec3::new(0.0, 900.0, 0.0), 0.1)),
vec![ids[7]],
"the refit tree must answer at the new place"
);
assert!(
world
.overlap_sphere(DVec3::new(7.0, 0.0, 0.0), 0.1)
.is_empty(),
"and no longer at the old one"
);
}
#[test]
fn a_spatially_loose_tree_rebuilds_when_the_quality_check_is_due() {
let (mut world, ids) = line_of_spheres(16);
let before = world.broadphase_stats();
for _ in 0..BROADPHASE_QUALITY_CHECK_REFIT_PASSES {
for (x, &id) in (0_u32..).zip(&ids) {
let side = if x % 2 == 0 { -1.0 } else { 1.0 };
let centre = DVec3::new(side * (1_000.0 + f64::from(x)), 0.0, 0.0);
assert!(world.set_sphere(id, Sphere::new(centre, 0.4)));
}
world.overlap_queries();
}
let after = world.broadphase_stats();
assert_eq!(
after.rebuilds,
before.rebuilds + 1,
"the interleaved distant leaves should be repartitioned: {after:?}"
);
}
#[test]
fn uniform_world_scaling_does_not_look_like_tree_degradation() {
let mut world = PhysicsWorld::new();
let ids: Vec<_> = (0..16)
.map(|x| {
world.add_box(BoxCollider::new(
DVec3::new(f64::from(x), 0.0, 0.0),
DVec3::splat(0.4),
))
})
.collect();
let before = world.broadphase_stats();
for _ in 0..BROADPHASE_QUALITY_CHECK_REFIT_PASSES {
for (x, &id) in (0_u32..).zip(&ids) {
let scaled =
BoxCollider::new(DVec3::new(f64::from(x) * 10.0, 0.0, 0.0), DVec3::splat(4.0));
assert!(world.set_box(id, scaled));
}
world.overlap_queries();
}
let after = world.broadphase_stats();
assert_eq!(
after.rebuilds, before.rebuilds,
"scaling preserved the partition and should not rebuild it: {after:?}"
);
}
#[test]
fn an_update_with_no_element_to_refit_invalidates_and_the_next_query_rebuilds() {
let (mut world, ids) = line_of_spheres(16);
let before = world.broadphase_stats();
assert!(world.bvh.is_some(), "the reading built the tree");
world.bvh_slot_to_elem[ids[3].index() as usize] = NO_ELEMENT;
assert!(world.set_sphere(ids[3], Sphere::new(DVec3::new(3.0, 40.0, 0.0), 0.4)));
assert!(
world.bvh.is_none(),
"an update that could not refit must drop the tree rather than \
leave it holding the old bounds"
);
let after = world.broadphase_stats();
assert_eq!(
after.updates_without_refit,
before.updates_without_refit + 1,
"the update should be counted as one that did not refit; got {after:?}"
);
assert_eq!(
after.refits, before.refits,
"and must not also count as a refit; got {after:?}"
);
assert_eq!(
after.rebuilds,
before.rebuilds + 1,
"the reading after it should have rebuilt; got {after:?}"
);
assert_eq!(
after.elements, 16,
"and rebuilt the whole set; got {after:?}"
);
assert_eq!(
ids_of(&world.overlap_sphere(DVec3::new(3.0, 40.0, 0.0), 0.1)),
vec![ids[3]],
"the rebuilt tree must answer at the new place"
);
}
#[test]
fn updates_with_no_tree_yet_are_counted_per_update_not_per_rebuild() {
let (mut world, ids) = line_of_spheres(16);
assert!(world.set_sphere(ids[0], Sphere::new(DVec3::new(0.0, 1.0, 0.0), 0.4)));
assert!(world.set_sphere(ids[1], Sphere::new(DVec3::new(1.0, 1.0, 0.0), 0.4)));
let stats = world.broadphase_stats();
assert_eq!(
stats.updates_without_refit, 2,
"one per update, with no tree to refit; got {stats:?}"
);
assert_eq!(stats.refits, 0, "nothing was refit; got {stats:?}");
assert_eq!(
stats.rebuilds, 1,
"and one rebuild between the two of them; got {stats:?}"
);
assert!(world.remove(ids[5]));
let before = world.broadphase_stats();
assert!(!world.set_sphere(ids[5], Sphere::new(DVec3::ZERO, 0.4)));
let after = world.broadphase_stats();
assert_eq!(
(after.refits, after.updates_without_refit),
(before.refits, before.updates_without_refit),
"a set_* on a stale id is counted by neither; got {after:?}"
);
}
#[test]
fn the_shared_view_finds_exactly_what_a_scan_would() {
let mut world = PhysicsWorld::new();
let mut expected: Vec<(ColliderId, Sphere)> = Vec::new();
for x in -3..=3 {
for y in -3..=3 {
let sphere = Sphere::new(DVec3::new(f64::from(x), f64::from(y), 0.0), 0.4);
expected.push((world.add_sphere(sphere), sphere));
}
}
let capsule = Capsule::new(DVec3::ZERO, 0.3, 1.0);
let capsule_id = world.add_capsule(capsule);
let boxed = BoxCollider::new(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.5));
let box_id = world.add_box(boxed);
let centres = [
DVec3::ZERO,
DVec3::new(1.2, -0.7, 0.0),
DVec3::new(-2.5, 2.5, 0.0),
DVec3::new(50.0, 50.0, 0.0),
];
let mut scratch = QueryScratch::new();
let mut biggest = 0usize;
for centre in centres {
for radius in [0.1, 0.75, 2.0] {
let probe = Sphere::new(centre, radius);
let mut scanned: Vec<(ColliderId, OverlapHit)> = expected
.iter()
.filter_map(|(id, s)| Some((*id, query::sphere_overlap_vs_sphere(&probe, s)?)))
.collect();
if let Some(hit) = query::sphere_overlap_vs_capsule(&probe, &capsule) {
scanned.push((capsule_id, hit));
}
if let Some(hit) = query::sphere_overlap_vs_aabb(&probe, &boxed.aabb()) {
scanned.push((box_id, hit));
}
scanned.sort_unstable_by_key(|(id, _)| id.index());
let mut shared = Vec::new();
world.overlap_queries().overlap_sphere_into(
centre,
radius,
&mut scratch,
&mut shared,
);
shared.sort_unstable_by_key(|(id, _)| id.index());
assert_eq!(scanned, shared, "at {centre} r{radius}");
biggest = biggest.max(shared.len());
}
}
assert!(
biggest > 4,
"the widest query in the fixture found {biggest} colliders, so the \
comparison above was mostly two empty vectors",
);
}
#[derive(Debug, PartialEq)]
struct ProbeAnswers {
rays: Vec<Option<(ColliderId, ShapeHit)>>,
sweeps: Vec<Option<(ColliderId, ShapeHit)>>,
excluded_sweeps: Vec<Option<(ColliderId, ShapeHit)>>,
aabbs: Vec<Vec<ColliderId>>,
}
fn scan_ray_one(ray: &Ray, entry: &ColliderEntry) -> Option<ShapeHit> {
match entry {
ColliderEntry::Sphere(s) => query::ray_vs_sphere(ray, s),
ColliderEntry::Box(b) => query::ray_vs_box(ray, b),
ColliderEntry::Capsule(c) => query::ray_vs_capsule(ray, &c.capsule),
ColliderEntry::Mesh(_) | ColliderEntry::Compound(_) => {
unreachable!("the fixture holds no meshes or compounds")
}
}
}
fn scan_sweep_one(segment: &Segment, radius: f64, entry: &ColliderEntry) -> Option<ShapeHit> {
match entry {
ColliderEntry::Sphere(s) => query::swept_sphere_vs_sphere(segment, radius, s),
ColliderEntry::Box(b) => query::swept_sphere_vs_box(segment, radius, b),
ColliderEntry::Capsule(c) => {
query::swept_sphere_vs_capsule(segment, radius, &c.capsule)
}
ColliderEntry::Mesh(_) | ColliderEntry::Compound(_) => {
unreachable!("the fixture holds no meshes or compounds")
}
}
}
#[test]
fn the_shared_view_casts_sweeps_and_boxes_like_a_scan_would() {
let mut world = PhysicsWorld::new();
let mut fixture: Vec<(ColliderId, ColliderEntry, bool)> = Vec::new();
let mut row_start = None;
for x in -3..=3 {
for y in -3..=3 {
let sphere = Sphere::new(DVec3::new(f64::from(x), f64::from(y), 0.0), 0.4);
let id = world.add_sphere(sphere);
if x == -3 && y == 0 {
row_start = Some(id);
}
fixture.push((id, ColliderEntry::Sphere(sphere), false));
}
}
let row_start = row_start.expect("the lattice contains (-3, 0, 0)");
let capsule = Capsule::new(DVec3::new(0.0, 0.0, 3.0), 0.3, 1.0);
fixture.push((
world.add_capsule(capsule),
ColliderEntry::Capsule(TurnedCapsule::upright(capsule)),
true,
));
let boxed = BoxCollider::new(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.5));
fixture.push((world.add_box(boxed), ColliderEntry::Box(boxed), false));
let trigger = Sphere::new(DVec3::new(-5.0, 0.0, 0.0), 0.5);
let trigger_id = world.add_sphere(trigger);
assert!(world.set_trigger(trigger_id, true), "the trigger was added");
fixture.push((trigger_id, ColliderEntry::Sphere(trigger), true));
let rays = [
Ray::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::X),
Ray::new(DVec3::new(-10.0, 2.0, 0.0), DVec3::X),
Ray::new(DVec3::new(0.0, 0.0, -10.0), DVec3::Z),
Ray::new(DVec3::new(-10.0, 1.5, 0.0), DVec3::X),
Ray::new(DVec3::new(-10.0, -10.0, 0.0), DVec3::new(1.0, 1.0, 0.0)),
Ray::new(DVec3::new(-10.0, 20.0, 0.0), DVec3::X),
Ray::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::X).with_bounds(0.0, 5.0),
];
let sweeps = [
(
Segment::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::new(10.0, 0.0, 0.0)),
0.2,
),
(
Segment::new(DVec3::new(-10.0, 0.7, 0.0), DVec3::new(10.0, 0.7, 0.0)),
0.35,
),
(
Segment::new(DVec3::new(0.0, 3.0, -10.0), DVec3::new(0.0, 3.0, 10.0)),
0.1,
),
(
Segment::new(DVec3::new(0.0, 3.0, 0.0), DVec3::new(0.1, 3.0, 0.0)),
0.2,
),
(
Segment::new(DVec3::new(20.0, 20.0, 20.0), DVec3::new(30.0, 30.0, 30.0)),
0.5,
),
];
let aabbs = [
Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.2)),
Aabb::from_centre_half(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.6)),
Aabb::from_centre_half(DVec3::new(50.0, 50.0, 0.0), DVec3::splat(1.0)),
Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(10.0)),
];
let plain_sweeps: Vec<Option<(ColliderId, ShapeHit)>> = sweeps
.iter()
.map(|(segment, radius)| world.sweep_sphere(segment, *radius))
.collect();
let mut excluded_sweeps: Vec<(Segment, f64, ColliderId)> = sweeps
.iter()
.zip(&plain_sweeps)
.filter_map(|((segment, radius), hit)| hit.map(|(id, _)| (*segment, *radius, id)))
.collect();
excluded_sweeps.push((sweeps[2].0, sweeps[2].1, row_start));
let exclusive = ProbeAnswers {
rays: rays.iter().map(|ray| world.cast_ray(ray)).collect(),
sweeps: plain_sweeps,
excluded_sweeps: excluded_sweeps
.iter()
.map(|(segment, radius, skip)| {
world.sweep_sphere_excluding(segment, *radius, Some(*skip))
})
.collect(),
aabbs: aabbs
.iter()
.map(|aabb| {
let mut ids = world.overlap_aabb(aabb);
ids.sort_unstable_by_key(|id| id.index());
ids
})
.collect(),
};
let solid = |skip: Option<ColliderId>| {
fixture
.iter()
.filter(move |(id, _, is_trigger)| !is_trigger && Some(*id) != skip)
};
let closest =
|hits: &mut dyn Iterator<Item = ShapeHit>| hits.map(|hit| hit.t).min_by(f64::total_cmp);
let entry_of = |wanted: ColliderId| {
fixture
.iter()
.find(|(id, _, _)| *id == wanted)
.map(|(_, entry, is_trigger)| (entry.clone(), *is_trigger))
.expect("the query named a collider the fixture does not hold")
};
let mut rays_that_hit = 0usize;
for (ray, answer) in rays.iter().zip(&exclusive.rays) {
let scanned =
closest(&mut solid(None).filter_map(|(_, entry, _)| scan_ray_one(ray, entry)));
assert_eq!(
answer.map(|(_, hit)| hit.t),
scanned,
"the closest solid hit along {ray:?}",
);
if let Some((id, hit)) = answer {
let (entry, is_trigger) = entry_of(*id);
assert!(!is_trigger, "a cast reported a trigger: {ray:?}");
assert_eq!(
scan_ray_one(ray, &entry),
Some(*hit),
"the collider the cast named does not produce the hit it reported",
);
rays_that_hit += 1;
}
}
assert!(
rays_that_hit >= 4 && rays_that_hit < rays.len(),
"{rays_that_hit} of {} ray probes hit, so the comparison above was \
mostly empty on one side or never exercised a miss",
rays.len(),
);
let with_triggers = closest(
&mut fixture
.iter()
.filter_map(|(_, entry, _)| scan_ray_one(&rays[0], entry)),
);
assert!(
with_triggers < exclusive.rays[0].map(|(_, hit)| hit.t),
"the trigger is not in front of the first ray's solid hits, so \
nothing here would notice if triggers stopped being skipped",
);
let mut sweeps_that_hit = 0usize;
for ((segment, radius), answer) in sweeps.iter().zip(&exclusive.sweeps) {
let scanned = closest(
&mut solid(None)
.filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
);
assert_eq!(
answer.map(|(_, hit)| hit.t),
scanned,
"the closest solid hit sweeping r{radius} along {segment:?}",
);
if let Some((id, hit)) = answer {
let (entry, is_trigger) = entry_of(*id);
assert!(!is_trigger, "a sweep reported a trigger: {segment:?}");
assert_eq!(
scan_sweep_one(segment, *radius, &entry),
Some(*hit),
"the collider the sweep named does not produce the hit it reported",
);
sweeps_that_hit += 1;
}
}
assert!(
sweeps_that_hit >= 3 && sweeps_that_hit < sweeps.len(),
"{sweeps_that_hit} of {} sweep probes hit, so the comparison above \
was mostly empty on one side or never exercised a miss",
sweeps.len(),
);
let mut exclusion_mattered = 0usize;
let mut exclusion_was_moot = 0usize;
for ((segment, radius, skip), answer) in
excluded_sweeps.iter().zip(&exclusive.excluded_sweeps)
{
let scanned = closest(
&mut solid(Some(*skip))
.filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
);
assert_eq!(
answer.map(|(_, hit)| hit.t),
scanned,
"the closest hit excluding {skip:?}, sweeping r{radius} along {segment:?}",
);
assert_ne!(
answer.map(|(id, _)| id),
Some(*skip),
"the excluded collider came back anyway",
);
let unexcluded = closest(
&mut solid(None)
.filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
);
if unexcluded == scanned {
exclusion_was_moot += 1;
} else {
exclusion_mattered += 1;
}
}
assert!(
exclusion_mattered >= 3 && exclusion_was_moot >= 1,
"{exclusion_mattered} exclusions changed the answer and \
{exclusion_was_moot} did not, so one of the two cases never ran",
);
let mut widest = 0usize;
for (aabb, answer) in aabbs.iter().zip(&exclusive.aabbs) {
let mut scanned: Vec<ColliderId> = fixture
.iter()
.filter(|(_, entry, _)| entry.aabb().intersects(aabb))
.map(|(id, _, _)| *id)
.collect();
scanned.sort_unstable_by_key(|id| id.index());
assert_eq!(&scanned, answer, "the AABBs meeting {aabb:?}");
widest = widest.max(answer.len());
}
assert!(
widest > 4,
"the widest AABB probe found {widest} colliders, so the comparison \
above was mostly two empty vectors",
);
let ask = |queries: &OverlapQueries<'_>| {
let mut scratch = QueryScratch::new();
let mut ids = Vec::new();
ProbeAnswers {
rays: rays
.iter()
.map(|ray| queries.cast_ray(ray, &mut scratch))
.collect(),
sweeps: sweeps
.iter()
.map(|(segment, radius)| queries.sweep_sphere(segment, *radius, &mut scratch))
.collect(),
excluded_sweeps: excluded_sweeps
.iter()
.map(|(segment, radius, skip)| {
queries.sweep_sphere_excluding(segment, *radius, Some(*skip), &mut scratch)
})
.collect(),
aabbs: aabbs
.iter()
.map(|aabb| {
queries.overlap_aabb_into(aabb, &mut scratch, &mut ids);
let mut found = ids.clone();
found.sort_unstable_by_key(|id| id.index());
found
})
.collect(),
}
};
let queries = world.overlap_queries();
assert_eq!(ask(&queries), exclusive, "the calling thread's own answers");
std::thread::scope(|scope| {
let handles: Vec<_> = (0..4).map(|_| scope.spawn(|| ask(&queries))).collect();
for handle in handles {
assert_eq!(
handle.join().expect("a query thread panicked"),
exclusive,
"a thread sharing the view disagreed with the scan",
);
}
});
}
#[test]
fn a_sphere_overlap_is_expanded_by_the_colliders_own_radius() {
let mut world = PhysicsWorld::new();
let body = world.add_sphere(Sphere::new(DVec3::ZERO, 0.5));
let mut scratch = QueryScratch::new();
let mut out = Vec::new();
let queries = world.overlap_queries();
let query_radius = 1.0;
let boundary = query_radius + 0.5;
queries.overlap_sphere_into(
DVec3::new(boundary - 0.01, 0.0, 0.0),
query_radius,
&mut scratch,
&mut out,
);
assert_eq!(
ids_of(&out),
vec![body],
"a body whose centre is inside R + r_b is returned"
);
queries.overlap_sphere_into(
DVec3::new(boundary + 0.01, 0.0, 0.0),
query_radius,
&mut scratch,
&mut out,
);
assert!(
out.is_empty(),
"a body whose centre is outside R + r_b is not returned"
);
queries.overlap_sphere_into(
DVec3::new(query_radius + 0.25, 0.0, 0.0),
query_radius,
&mut scratch,
&mut out,
);
assert_eq!(
ids_of(&out),
vec![body],
"the query radius is expanded by the collider's own radius, not used raw"
);
queries.overlap_sphere_into(
DVec3::new(1.05, 1.05, 0.0),
query_radius,
&mut scratch,
&mut out,
);
assert_eq!(
ids_of(&out),
vec![body],
"a body within the circle of radius R + r_b is returned even off-axis"
);
queries.overlap_sphere_into(
DVec3::new(1.07, 1.07, 0.0),
query_radius,
&mut scratch,
&mut out,
);
assert!(
out.is_empty(),
"a body outside the circle of radius R + r_b is not returned, \
even where the broadphase AABB would admit it"
);
}
#[test]
fn a_reused_scratch_does_not_leak_one_query_into_the_next() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::ZERO, 0.5));
world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 0.5));
let mut scratch = QueryScratch::new();
let mut out = Vec::new();
let queries = world.overlap_queries();
queries.overlap_sphere_into(DVec3::ZERO, 1.0, &mut scratch, &mut out);
assert_eq!(out.len(), 1);
queries.overlap_sphere_into(DVec3::new(0.0, 100.0, 0.0), 1.0, &mut scratch, &mut out);
assert!(out.is_empty(), "a stale candidate survived the next query");
queries.overlap_sphere_into(DVec3::new(20.0, 0.0, 0.0), 1.0, &mut scratch, &mut out);
assert_eq!(out.len(), 1);
}
#[test]
fn adding_and_removing_a_collider_leaves_the_world_empty_again() {
let mut world = PhysicsWorld::new();
let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
assert_eq!(world.len(), 1);
assert!(!world.is_empty());
assert!(world.remove(id));
assert!(world.is_empty());
}
#[test]
fn remove_invalid_id_returns_false() {
let mut world = PhysicsWorld::new();
assert!(!world.remove(ColliderId::new(999, 0)));
let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
assert!(world.remove(id));
assert!(!world.remove(id));
}
#[test]
fn add_sphere_then_cast_ray_hits() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
let ray = Ray::new(DVec3::ZERO, DVec3::X);
let result = world.cast_ray(&ray);
assert!(result.is_some());
let (_id, hit) = result.unwrap();
assert!((hit.t - 4.0).abs() < 0.001);
}
#[test]
fn cast_ray_misses_when_no_colliders() {
let mut world = PhysicsWorld::new();
let ray = Ray::new(DVec3::ZERO, DVec3::X);
assert!(world.cast_ray(&ray).is_none());
}
#[test]
fn add_multiple_and_cast_ray_finds_closest() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
let close = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
let ray = Ray::new(DVec3::ZERO, DVec3::X);
let (id, hit) = world.cast_ray(&ray).unwrap();
assert_eq!(id, close);
assert!((hit.t - 4.0).abs() < 0.001);
}
#[test]
fn sweep_sphere_excluding_keeps_the_next_closest_hit() {
let mut world = PhysicsWorld::new();
let near = world.add_sphere(Sphere::new(DVec3::new(0.0, 0.0, 0.0), 1.0));
let far = world.add_sphere(Sphere::new(DVec3::new(3.0, 0.0, 0.0), 1.0));
let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
let (id, _) = world.sweep_sphere(&seg, 0.5).expect("the sweep hits both");
assert_eq!(id, near, "the unfiltered sweep answers the closest");
let (id, hit) = world
.sweep_sphere_excluding(&seg, 0.5, Some(near))
.expect("the one behind it is still there");
assert_eq!(id, far, "excluding the closest must not lose the rest");
assert!(
(hit.t - 0.65).abs() < 0.001,
"expected ~0.65, got {}",
hit.t
);
let (id, _) = world
.sweep_sphere_excluding(&seg, 0.5, Some(ColliderId::new(999, 0)))
.expect("an id the world never issued excludes nothing");
assert_eq!(id, near);
assert!(world.remove(near), "the collider was live");
let reused = world.add_sphere(Sphere::new(DVec3::new(0.0, 0.0, 0.0), 1.0));
assert_eq!(
reused.index, near.index,
"this test only says anything while the slot is actually reused"
);
assert_ne!(
reused.generation, near.generation,
"and the id has moved on"
);
let (id, _) = world
.sweep_sphere_excluding(&seg, 0.5, Some(near))
.expect("the stale id must not hide the collider that took its slot");
assert_eq!(
id, reused,
"a generation that has moved on excludes nothing, so the sweep still \
answers the shape occupying that slot"
);
}
#[test]
fn sweep_sphere_hits_box() {
let mut world = PhysicsWorld::new();
world.add_box(BoxCollider::new(DVec3::ZERO, DVec3::splat(1.0)));
let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
let result = world.sweep_sphere(&seg, 0.5);
assert!(result.is_some());
let (_id, hit) = result.unwrap();
assert!(
(hit.t - 0.35).abs() < 0.001,
"expected ~0.35, got {}",
hit.t
);
assert_eq!(hit.normal, DVec3::NEG_X);
}
#[test]
fn sweep_sphere_hits_a_box_its_centre_line_misses() {
let mut world = PhysicsWorld::new();
world.add_box(BoxCollider::new(
DVec3::new(0.0, -1.0, 0.0),
DVec3::splat(1.0),
));
let along = Segment::new(DVec3::new(-5.0, 0.3, 0.0), DVec3::new(5.0, 0.3, 0.0));
let (_, hit) = world
.sweep_sphere(&along, 0.5)
.expect("a sphere grazing the top face touches it");
assert!(hit.point.y <= 0.0 + 1e-9, "contact on the box: {hit:?}");
let onto = Segment::new(DVec3::new(0.0, 1.0, 0.0), DVec3::new(0.0, 0.3, 0.0));
let (_, hit) = world
.sweep_sphere(&onto, 0.5)
.expect("a sphere landing on the face touches it");
assert!(hit.normal.y > 0.5, "the top face's normal: {hit:?}");
let clear = Segment::new(DVec3::new(-5.0, 0.6, 0.0), DVec3::new(5.0, 0.6, 0.0));
assert!(
world.sweep_sphere(&clear, 0.5).is_none(),
"a sphere that does not reach the box must not report a hit",
);
}
#[test]
fn rebuilding_after_the_last_removal_leaves_nothing_for_a_ray_to_hit() {
let mut world = PhysicsWorld::new();
let id = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
world.remove(id);
world.rebuild(); let ray = Ray::new(DVec3::ZERO, DVec3::X);
assert!(world.cast_ray(&ray).is_none());
}
#[test]
fn churn_after_the_first_query_keeps_the_tree() {
let mut world = PhysicsWorld::new();
let keep = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
assert!(world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).is_some());
assert!(format!("{world:?}").contains("bvh_cached: true"));
let bullet = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 0.5));
assert!(
format!("{world:?}").contains("bvh_cached: true"),
"adding a collider threw the tree away"
);
let (hit_id, _) = world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).unwrap();
assert_eq!(hit_id, bullet);
assert!(world.remove(bullet));
assert!(
format!("{world:?}").contains("bvh_cached: true"),
"removing a collider threw the tree away"
);
let (hit_id, _) = world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).unwrap();
assert_eq!(hit_id, keep, "the removed collider still answers queries");
assert_eq!(world.len(), 1);
}
#[test]
fn churn_through_a_recycled_slot_tracks_the_right_element() {
let mut world = PhysicsWorld::new();
let far = world.add_sphere(Sphere::new(DVec3::new(100.0, 0.0, 0.0), 1.0));
let doomed = world.add_sphere(Sphere::new(DVec3::new(10.0, 0.0, 0.0), 1.0));
assert!(world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).is_some());
assert!(world.remove(doomed));
let reused = world.add_sphere(Sphere::new(DVec3::new(30.0, 0.0, 0.0), 1.0));
assert_eq!(reused.index(), doomed.index(), "the slot must be recycled");
assert!(world.set_sphere(reused, Sphere::new(DVec3::new(3.0, 0.0, 0.0), 1.0)));
assert_eq!(
ids_of(&world.overlap_sphere(DVec3::new(3.0, 0.0, 0.0), 0.5)),
vec![reused],
"the refit did not move the collider that was asked to move"
);
assert!(
world
.overlap_sphere(DVec3::new(30.0, 0.0, 0.0), 0.5)
.is_empty()
);
assert_eq!(
world.aabb_of(far).unwrap().centre(),
DVec3::new(100.0, 0.0, 0.0)
);
}
#[test]
fn aabb_of_returns_correct_bounds() {
let mut world = PhysicsWorld::new();
let id = world.add_sphere(Sphere::new(DVec3::new(1.0, 2.0, 3.0), 0.5));
let aabb = world.aabb_of(id).unwrap();
assert_eq!(aabb.min, DVec3::new(0.5, 1.5, 2.5));
assert_eq!(aabb.max, DVec3::new(1.5, 2.5, 3.5));
}
#[test]
fn aabb_of_unknown_id_returns_none() {
let world = PhysicsWorld::new();
assert!(world.aabb_of(ColliderId::new(42, 0)).is_none());
}
#[test]
fn stale_id_does_not_address_the_slot_s_new_occupant() {
let mut world = PhysicsWorld::new();
let old = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
assert!(world.remove(old));
let new = world.add_sphere(Sphere::new(DVec3::new(9.0, 0.0, 0.0), 2.0));
assert_eq!(new.index(), old.index(), "the slot must be recycled");
assert_ne!(new, old, "but the id must not be");
assert!(world.aabb_of(old).is_none());
assert!(!world.remove(old));
assert!(!world.set_trigger(old, true));
assert!(!world.is_trigger(old));
assert!(!world.set_sphere(old, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));
let aabb = world.aabb_of(new).unwrap();
assert_eq!(aabb.centre(), DVec3::new(9.0, 0.0, 0.0));
assert_eq!(world.len(), 1);
}
#[test]
fn the_worlds_debug_output_reports_how_many_colliders_it_holds() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
let s = format!("{world:?}");
assert!(s.contains("collider_count: 1"));
}
#[test]
fn overlap_sphere_finds_sphere() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
let results = world.overlap_sphere(DVec3::ZERO, 4.0);
assert_eq!(results.len(), 1);
}
#[test]
fn overlap_sphere_misses_distant() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::new(10.0, 0.0, 0.0), 1.0));
let results = world.overlap_sphere(DVec3::ZERO, 2.0);
assert!(results.is_empty());
}
#[test]
fn overlap_sphere_finds_box() {
let mut world = PhysicsWorld::new();
world.add_box(BoxCollider::new(DVec3::ZERO, DVec3::splat(1.0)));
let results = world.overlap_sphere(DVec3::new(2.0, 0.0, 0.0), 1.5);
assert_eq!(results.len(), 1);
}
#[test]
fn overlap_sphere_finds_capsule() {
let mut world = PhysicsWorld::new();
world.add_capsule(Capsule::new(DVec3::ZERO, 0.5, 2.0));
let results = world.overlap_sphere(DVec3::new(0.0, 0.0, 0.0), 3.0);
assert_eq!(results.len(), 1);
}
#[test]
fn overlap_sphere_finds_multiple() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
world.add_sphere(Sphere::new(DVec3::new(-2.0, 0.0, 0.0), 1.0));
world.add_sphere(Sphere::new(DVec3::new(0.0, 6.0, 0.0), 1.0));
let results = world.overlap_sphere(DVec3::ZERO, 4.0);
assert_eq!(results.len(), 2); }
#[test]
fn overlap_aabb_finds_all_intersecting() {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
world.add_sphere(Sphere::new(DVec3::new(-2.0, 0.0, 0.0), 1.0));
world.add_sphere(Sphere::new(DVec3::new(0.0, 10.0, 0.0), 1.0));
let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(3.0));
let results = world.overlap_aabb(&query);
assert_eq!(results.len(), 2);
}
#[test]
fn overlap_aabb_empty_world() {
let mut world = PhysicsWorld::new();
let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(10.0));
assert!(world.overlap_aabb(&query).is_empty());
}
#[test]
fn set_sphere_moves_collider_in_ray_cast() {
let mut world = PhysicsWorld::new();
let id = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
let ray = Ray::new(DVec3::ZERO, DVec3::X);
assert!(world.cast_ray(&ray).is_some());
assert!(world.set_sphere(id, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));
assert!(world.cast_ray(&ray).is_none());
}
#[test]
fn set_box_updates_overlap_query() {
let mut world = PhysicsWorld::new();
let id = world.add_box(BoxCollider::new(
DVec3::new(5.0, 0.0, 0.0),
DVec3::splat(1.0),
));
let results = world.overlap_sphere(DVec3::ZERO, 2.0);
assert!(results.is_empty());
assert!(world.set_box(
id,
BoxCollider::new(DVec3::new(1.0, 0.0, 0.0), DVec3::splat(1.0))
));
let results = world.overlap_sphere(DVec3::ZERO, 3.0);
assert_eq!(results.len(), 1);
assert_eq!(results[0].0, id);
}
#[test]
fn set_sphere_on_invalid_id_returns_false() {
let mut world = PhysicsWorld::new();
assert!(!world.set_sphere(ColliderId::new(999, 0), Sphere::new(DVec3::ZERO, 1.0)));
}
#[test]
fn set_sphere_refits_the_right_leaf_when_colliders_are_not_centroid_ordered() {
let mut world = PhysicsWorld::new();
let far = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
let near = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
let ray = Ray::new(DVec3::ZERO, DVec3::X);
let (id, hit) = world
.cast_ray(&ray)
.expect("the near sphere is ahead of the ray");
assert_eq!(id, near);
assert!((hit.t - 4.0).abs() < 1e-9, "t = {}", hit.t);
assert!(world.set_sphere(far, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));
let (id, hit) = world
.cast_ray(&ray)
.expect("the untouched sphere must not vanish");
assert_eq!(id, near);
assert!((hit.t - 4.0).abs() < 1e-9, "t = {}", hit.t);
}
#[test]
fn set_capsule_refits_bvh() {
let mut world = PhysicsWorld::new();
let id = world.add_capsule(Capsule::new(DVec3::new(5.0, 0.0, 0.0), 0.5, 1.0));
let ray = Ray::new(DVec3::ZERO, DVec3::X);
assert!(world.cast_ray(&ray).is_some());
assert!(world.set_capsule(id, Capsule::new(DVec3::new(-30.0, 30.0, 0.0), 0.5, 1.0)));
assert!(world.cast_ray(&ray).is_none());
}
#[test]
fn set_sphere_after_removal_fails() {
let mut world = PhysicsWorld::new();
let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
world.remove(id);
assert!(!world.set_sphere(id, Sphere::new(DVec3::new(1.0, 0.0, 0.0), 1.0)));
}
#[test]
fn sweep_sphere_hits_capsule_exact() {
let mut world = PhysicsWorld::new();
world.add_capsule(Capsule::new(DVec3::ZERO, 0.5, 2.0));
let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
let result = world.sweep_sphere(&seg, 0.5);
assert!(result.is_some());
}
#[test]
fn sweep_sphere_misses_distant_capsule() {
let mut world = PhysicsWorld::new();
world.add_capsule(Capsule::new(DVec3::new(100.0, 0.0, 0.0), 0.5, 2.0));
let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
assert!(world.sweep_sphere(&seg, 0.5).is_none());
}
#[test]
fn trigger_defaults_to_false() {
let mut world = PhysicsWorld::new();
let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
assert!(!world.is_trigger(id));
}
#[test]
fn set_trigger_toggles_flag() {
let mut world = PhysicsWorld::new();
let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
assert!(world.set_trigger(id, true));
assert!(world.is_trigger(id));
assert!(world.set_trigger(id, false));
assert!(!world.is_trigger(id));
}
#[test]
fn set_trigger_on_invalid_id_returns_false() {
let mut world = PhysicsWorld::new();
assert!(!world.set_trigger(ColliderId::new(42, 0), true));
}
#[test]
fn trigger_is_transparent_to_rays_and_sweeps() {
let mut world = PhysicsWorld::new();
let trigger = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
assert!(world.set_trigger(trigger, true));
let ray = Ray::new(DVec3::ZERO, DVec3::X);
assert!(
world.cast_ray(&ray).is_none(),
"a trigger must not stop a bullet"
);
let seg = Segment::new(DVec3::ZERO, DVec3::new(10.0, 0.0, 0.0));
assert!(world.sweep_sphere(&seg, 0.5).is_none());
}
#[test]
fn trigger_still_shows_up_in_overlap_queries() {
let mut world = PhysicsWorld::new();
let trigger = world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
assert!(world.set_trigger(trigger, true));
assert_eq!(
ids_of(&world.overlap_sphere(DVec3::ZERO, 4.0)),
vec![trigger]
);
let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(4.0));
assert_eq!(world.overlap_aabb(&query), vec![trigger]);
}
#[test]
fn solid_collider_behind_a_trigger_is_still_hit() {
let mut world = PhysicsWorld::new();
let trigger = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
world.set_trigger(trigger, true);
let solid = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
let ray = Ray::new(DVec3::ZERO, DVec3::X);
let (id, hit) = world.cast_ray(&ray).expect("the solid sphere is behind it");
assert_eq!(id, solid);
assert!((hit.t - 19.0).abs() < 1e-9, "t = {}", hit.t);
}
#[test]
fn a_capsule_sweeps_broadphase_reaches_a_ledge_the_sphere_sweeps_does_not() {
let (radius, half_height) = (0.4, 1.5);
let mut world = PhysicsWorld::new();
let ledge = world.add_box(BoxCollider::new(
DVec3::new(2.0, 1.1, 0.0),
DVec3::new(1.0, 0.1, 1.0),
));
let segment = Segment::new(DVec3::new(-3.0, 0.0, 0.0), DVec3::new(3.0, 0.0, 0.0));
assert!(
world.sweep_sphere(&segment, radius).is_none(),
"the sphere passes under the ledge, or the capsule reaching it proves nothing",
);
let (id, hit) = world
.sweep_capsule(&segment, radius, half_height)
.expect("the capsule's shoulder is level with the ledge");
assert_eq!(id, ledge);
assert_eq!(hit.normal, DVec3::NEG_X);
}
#[test]
fn a_capsule_sweep_excluding_its_own_collider_keeps_the_wall_behind_it() {
let (radius, half_height) = (0.4, 0.9);
let mut world = PhysicsWorld::new();
let character = world.add_capsule(Capsule::new(DVec3::ZERO, radius, half_height));
let wall = world.add_box(BoxCollider::new(
DVec3::new(3.0, 0.0, 0.0),
DVec3::new(0.5, 5.0, 5.0),
));
let segment = Segment::new(DVec3::ZERO, DVec3::new(4.0, 0.0, 0.0));
let (self_id, self_hit) = world
.sweep_capsule(&segment, radius, half_height)
.expect("without the exclusion the character finds itself");
assert_eq!(self_id, character);
assert_eq!(self_hit.t, 0.0);
let (id, hit) = world
.sweep_capsule_excluding(&segment, radius, half_height, Some(character))
.expect("the wall survives the exclusion");
assert_eq!(id, wall);
assert!((hit.t - 0.525).abs() < 1e-12, "t = {}", hit.t);
}
#[test]
fn a_capsule_sweep_passes_through_a_trigger_to_the_solid_behind_it() {
let (radius, half_height) = (0.4, 0.9);
let mut world = PhysicsWorld::new();
let trigger = world.add_box(BoxCollider::new(
DVec3::new(2.0, 0.0, 0.0),
DVec3::new(0.5, 5.0, 5.0),
));
assert!(world.set_trigger(trigger, true));
let solid = world.add_box(BoxCollider::new(
DVec3::new(6.0, 0.0, 0.0),
DVec3::new(0.5, 5.0, 5.0),
));
let segment = Segment::new(DVec3::ZERO, DVec3::new(10.0, 0.0, 0.0));
let (id, hit) = world
.sweep_capsule(&segment, radius, half_height)
.expect("the solid slab is behind the trigger");
assert_eq!(
id, solid,
"the trigger is in the way and must be passed through"
);
assert!((hit.t - 0.51).abs() < 1e-12, "t = {}", hit.t);
}
}
#[cfg(test)]
#[path = "world/ray_exclusion_tests.rs"]
mod ray_exclusion_tests;
#[cfg(test)]
#[path = "world/query_filter_tests.rs"]
mod query_filter_tests;
#[cfg(test)]
#[path = "world/overlap_hit_tests.rs"]
mod overlap_hit_tests;
#[cfg(test)]
#[path = "world/lying_capsule_tests.rs"]
mod lying_capsule_tests;
#[cfg(test)]
#[path = "world/turned_box_tests.rs"]
mod turned_box_tests;
#[cfg(test)]
#[path = "world/candidate_sweep_tests.rs"]
mod candidate_sweep_tests;
#[cfg(test)]
#[path = "world/query_digest_tests.rs"]
mod query_digest_tests;
#[cfg(test)]
#[path = "world/turned_body_tests.rs"]
mod turned_body_tests;
#[cfg(test)]
#[path = "world/compound_tests.rs"]
mod compound_tests;
#[cfg(test)]
#[path = "world/turned_capsule_tests.rs"]
mod turned_capsule_tests;
#[cfg(test)]
#[path = "world/arc_selection_tests.rs"]
mod arc_selection_tests;
#[cfg(test)]
#[path = "world/arc_sweep_tests.rs"]
mod arc_sweep_tests;