mod clearance;
mod collision_filter;
mod debug;
mod ignored_contacts;
mod joints;
pub use collision_filter::CollisionFilter;
pub use debug::{CONTACT_NORMAL_LENGTH, PhysicsDebugLine};
pub use ignored_contacts::ContactPairError;
use std::collections::HashMap;
use crcbl_core::{Handle, Pool};
use crcbl_ecs::{Access, DebugCtx, Entity, SystemTrait};
use glam::DVec3;
use crate::collider::Aabb;
use crate::components::{ColliderComponent, RigidBody, Transform};
use crate::contact::broadphase::ProxyId;
use crate::contact::island::{self, IslandId, Islands};
use crate::contact::{
Bodies, ContactCounters, ContactPipeline, ContactReport, ContactSettings, KineticContact,
PlaneId, StageTimes,
};
use crate::forces::ForceProvider;
use crate::integrator::{Integrator as _, SemiImplicitEuler};
use crate::material::SurfaceMaterial;
use crate::query::{OverlapHit, ShapeHit};
use crate::world::{
ALL_LAYERS, ColliderId, OverlapQueries, PhysicsWorld, QueryFilter, QueryScratch,
};
use crate::{Ray, Segment};
pub(crate) type BodyId = Handle<BodyRecord>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BodySet {
Static,
Awake,
Sleeping,
}
#[derive(Debug)]
pub(crate) struct BodyRecord {
pub(crate) entity: Entity,
pub(crate) set: BodySet,
pub(crate) index: usize,
pub(crate) collider: Option<(ColliderId, ColliderComponent)>,
pub(crate) layers: u32,
pub(crate) material: SurfaceMaterial,
pub(crate) proxies: Vec<ProxyId>,
pub(crate) island: Option<IslandId>,
pub(crate) substeps: u32,
pub(crate) filter: CollisionFilter,
}
#[derive(Debug, Default)]
pub(crate) struct StaticSet {
pub(crate) ids: Vec<BodyId>,
pub(crate) transforms: Vec<Transform>,
}
#[derive(Debug, Default)]
pub(crate) struct AwakeSet {
pub(crate) ids: Vec<BodyId>,
pub(crate) transforms: Vec<Transform>,
pub(crate) bodies: Vec<RigidBody>,
pub(crate) sleep_times: Vec<f64>,
}
impl StaticSet {
fn push(&mut self, id: BodyId, transform: Transform) -> usize {
self.ids.push(id);
self.transforms.push(transform);
self.ids.len() - 1
}
fn swap_remove(&mut self, index: usize) -> (Transform, Option<BodyId>) {
self.ids.swap_remove(index);
let transform = self.transforms.swap_remove(index);
(transform, self.ids.get(index).copied())
}
}
impl AwakeSet {
pub(crate) fn push(&mut self, id: BodyId, transform: Transform, body: RigidBody) -> usize {
self.ids.push(id);
self.transforms.push(transform);
self.bodies.push(body);
self.sleep_times.push(0.0);
self.ids.len() - 1
}
pub(crate) fn swap_remove(&mut self, index: usize) -> (Transform, RigidBody, Option<BodyId>) {
self.ids.swap_remove(index);
let transform = self.transforms.swap_remove(index);
let body = self.bodies.swap_remove(index);
self.sleep_times.swap_remove(index);
(transform, body, self.ids.get(index).copied())
}
}
pub struct PhysicsSystem {
world: PhysicsWorld,
records: Pool<BodyRecord>,
entity_to_body: HashMap<Entity, BodyId>,
statics: StaticSet,
awake: AwakeSet,
islands: Islands,
collider_count: usize,
collider_to_entity: Vec<Option<Entity>>,
force_providers: Vec<Box<dyn ForceProvider>>,
scratch: QueryScratch,
contacts: Option<Box<ContactPipeline>>,
}
#[derive(Clone, Copy, Debug)]
pub struct EntityOverlapQueries<'a> {
queries: OverlapQueries<'a>,
collider_to_entity: &'a [Option<Entity>],
}
impl EntityOverlapQueries<'_> {
pub fn overlap_sphere_into(
&self,
centre: DVec3,
radius: f64,
scratch: &mut QueryScratch,
out: &mut Vec<(Entity, 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<(Entity, OverlapHit)>,
) {
out.clear();
let mut hits = std::mem::take(&mut scratch.hits);
self.queries
.overlap_sphere_filtered_into(centre, radius, filter, scratch, &mut hits);
for &(id, hit) in hits.iter() {
let Some(entity) = self.entity_for(id) else {
continue;
};
out.push((entity, hit));
}
scratch.hits = hits;
}
pub fn overlap_sphere_entities_into(
&self,
centre: DVec3,
radius: f64,
scratch: &mut QueryScratch,
out: &mut Vec<Entity>,
) {
out.clear();
let mut ids = std::mem::take(&mut scratch.ids);
self.queries
.overlap_sphere_ids_into(centre, radius, scratch, &mut ids);
out.extend(ids.iter().filter_map(|&id| self.entity_for(id)));
scratch.ids = ids;
}
pub fn overlap_aabb_into(
&self,
aabb: &Aabb,
scratch: &mut QueryScratch,
out: &mut Vec<Entity>,
) {
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<Entity>,
) {
out.clear();
let mut ids = std::mem::take(&mut scratch.ids);
self.queries
.overlap_aabb_filtered_into(aabb, filter, scratch, &mut ids);
for id in ids.iter() {
let Some(entity) = self.entity_for(*id) else {
continue;
};
out.push(entity);
}
scratch.ids = ids;
}
#[must_use]
pub fn cast_ray(&self, ray: &Ray, scratch: &mut QueryScratch) -> Option<(Entity, ShapeHit)> {
self.cast_ray_filtered(ray, QueryFilter::ALL, scratch)
}
#[must_use]
pub fn cast_ray_filtered(
&self,
ray: &Ray,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<(Entity, ShapeHit)> {
let (id, hit) = self.queries.cast_ray_filtered(ray, filter, scratch)?;
Some((self.entity_for(id)?, hit))
}
#[must_use]
pub fn sweep_sphere(
&self,
segment: &Segment,
radius: f64,
scratch: &mut QueryScratch,
) -> Option<(Entity, ShapeHit)> {
self.sweep_sphere_filtered(segment, radius, QueryFilter::ALL, scratch)
}
#[must_use]
pub fn sweep_sphere_filtered(
&self,
segment: &Segment,
radius: f64,
filter: QueryFilter,
scratch: &mut QueryScratch,
) -> Option<(Entity, ShapeHit)> {
let (id, hit) = self
.queries
.sweep_sphere_filtered(segment, radius, filter, scratch)?;
Some((self.entity_for(id)?, hit))
}
fn entity_for(&self, id: ColliderId) -> Option<Entity> {
entity_for_in(self.collider_to_entity, id)
}
}
fn entity_for_in(collider_to_entity: &[Option<Entity>], id: ColliderId) -> Option<Entity> {
collider_to_entity.get(id.index() as usize).and_then(|e| *e)
}
impl PhysicsSystem {
pub const NAME: &'static str = "physics";
#[must_use]
pub fn new() -> Self {
Self {
world: PhysicsWorld::new(),
records: Pool::new(),
entity_to_body: HashMap::new(),
statics: StaticSet::default(),
awake: AwakeSet::default(),
islands: Islands::default(),
collider_count: 0,
collider_to_entity: Vec::new(),
force_providers: Vec::new(),
scratch: QueryScratch::new(),
contacts: None,
}
}
#[must_use]
pub fn with_contacts(settings: ContactSettings) -> Self {
Self {
contacts: Some(Box::new(ContactPipeline::new(settings))),
..Self::new()
}
}
#[must_use]
pub fn contact_settings(&self) -> Option<&ContactSettings> {
self.contacts.as_ref().map(|pipeline| &pipeline.settings)
}
pub fn contact_settings_mut(&mut self) -> Option<&mut ContactSettings> {
self.contacts
.as_mut()
.map(|pipeline| &mut pipeline.settings)
}
pub fn add_plane(&mut self, normal: DVec3, offset: f64, material: SurfaceMaterial) -> PlaneId {
assert!(
(normal.length_squared() - 1.0).abs() < 1e-9,
"a plane's normal has unit length: {normal:?}"
);
self.contacts
.as_mut()
.expect("planes are contact geometry: build the system with_contacts")
.add_plane(normal, offset, material)
}
#[must_use]
pub fn contact_counters(&self) -> ContactCounters {
self.contacts
.as_ref()
.map_or_else(ContactCounters::default, |pipeline| pipeline.counters)
}
#[must_use]
pub fn kinetic_contacts(&self) -> &[KineticContact] {
self.contacts
.as_ref()
.map_or(&[], |pipeline| pipeline.kinetic.as_slice())
}
#[must_use]
pub fn contacts(&self) -> Vec<ContactReport> {
self.contacts
.as_ref()
.map_or_else(Vec::new, |pipeline| pipeline.reports(&self.records))
}
#[must_use]
pub fn collider_count(&self) -> usize {
self.collider_count
}
#[must_use]
pub fn body_count(&self) -> usize {
self.awake.bodies.len() + self.islands.sleeping_bodies()
}
#[must_use]
pub fn is_sleeping(&self, entity: Entity) -> bool {
self.record(entity)
.is_some_and(|record| record.set == BodySet::Sleeping)
}
pub fn put_to_sleep(&mut self, entity: Entity) -> bool {
let sleeps = self
.contacts
.as_ref()
.is_some_and(|pipeline| pipeline.settings.sleep);
let Some(&id) = self.entity_to_body.get(&entity) else {
return false;
};
if !sleeps {
return false;
}
self.islands.reconcile(&mut self.records, &self.awake);
let Some(record) = self.records.get(id) else {
return false;
};
if record.set == BodySet::Awake
&& let Some(island) = record.island
{
self.islands
.sleep(&mut self.records, &mut self.awake, island);
}
let asleep = self.is_sleeping(entity);
if asleep && let Some(pipeline) = self.contacts.as_mut() {
let island = self.records.get(id).and_then(|record| record.island);
match island.map(|island| self.islands.members(island)) {
Some(members) if !members.is_empty() => {
for &member in members {
pipeline.body_restored_asleep(member);
}
}
_ => pipeline.body_restored_asleep(id),
}
}
asleep
}
pub fn set_body(&mut self, entity: Entity, body: RigidBody) {
let id = self.record_for(entity, Transform::IDENTITY);
self.wake(id);
let record = self.records.get(id).expect("a live record");
assert!(
!body.is_dynamic()
|| !matches!(record.collider, Some((_, ColliderComponent::Mesh { .. }))),
"a triangle mesh is for static and kinematic bodies, not dynamic ones"
);
let index = record.index;
match record.set {
BodySet::Awake => self.awake.bodies[index] = body,
BodySet::Sleeping => unreachable!("woken above"),
BodySet::Static => {
let (transform, moved) = self.statics.swap_remove(index);
self.reindex_to(moved, index);
let awake_index = self.awake.push(id, transform, body);
let record = self.records.get_mut(id).expect("a live record");
record.set = BodySet::Awake;
record.index = awake_index;
if let Some(pipeline) = self.contacts.as_mut() {
for &proxy in &record.proxies {
pipeline.body_changed_set(proxy, BodySet::Awake);
}
}
}
}
}
pub fn set_transform(&mut self, entity: Entity, transform: Transform) {
let id = self.record_for(entity, transform);
self.disturb(id);
*self.transform_slot(id) = transform;
self.sync_collider(id);
if let Some(pipeline) = self.contacts.as_mut() {
pipeline.body_placed(
id,
Bodies {
records: &self.records,
statics: &self.statics,
awake: &self.awake,
islands: &self.islands,
},
);
}
}
#[must_use]
pub fn body(&self, entity: Entity) -> Option<&RigidBody> {
let record = self.record(entity)?;
match record.set {
BodySet::Awake => Some(&self.awake.bodies[record.index]),
BodySet::Sleeping => Some(self.islands.body(record.island, record.index)),
BodySet::Static => None,
}
}
#[must_use]
pub fn body_mut(&mut self, entity: Entity) -> Option<&mut RigidBody> {
let &id = self.entity_to_body.get(&entity)?;
self.wake(id);
let record = self.records.get(id)?;
match record.set {
BodySet::Awake => Some(&mut self.awake.bodies[record.index]),
BodySet::Static | BodySet::Sleeping => None,
}
}
#[must_use]
pub fn transform(&self, entity: Entity) -> Option<&Transform> {
let record = self.record(entity)?;
Some(match record.set {
BodySet::Awake => &self.awake.transforms[record.index],
BodySet::Static => &self.statics.transforms[record.index],
BodySet::Sleeping => self.islands.transform(record.island, record.index),
})
}
pub fn set_material(&mut self, entity: Entity, material: SurfaceMaterial) -> bool {
let Some(&id) = self.entity_to_body.get(&entity) else {
return false;
};
self.disturb(id);
match self.records.get_mut(id) {
Some(record) => {
record.material = material;
true
}
None => false,
}
}
#[must_use]
pub fn material(&self, entity: Entity) -> Option<SurfaceMaterial> {
self.record(entity).map(|record| record.material)
}
pub fn add_force_provider(&mut self, provider: Box<dyn ForceProvider>) {
self.force_providers.push(provider);
}
pub fn apply_force(&mut self, entity: Entity, force: DVec3) -> bool {
match self.body_mut(entity) {
Some(body) => {
body.apply_force(force);
true
}
None => false,
}
}
pub fn apply_torque(&mut self, entity: Entity, torque: DVec3) -> bool {
match self.body_mut(entity) {
Some(body) => {
body.apply_torque(torque);
true
}
None => false,
}
}
pub fn set_collider(
&mut self,
entity: Entity,
component: &ColliderComponent,
transform: &Transform,
) {
let id = self.record_for(entity, *transform);
self.wake(id);
if matches!(component, ColliderComponent::Mesh { .. }) {
let record = self.records.get(id).expect("a live record");
assert!(
record.set != BodySet::Awake || !self.awake.bodies[record.index].is_dynamic(),
"a triangle mesh is for static and kinematic bodies, not dynamic ones"
);
}
*self.transform_slot(id) = *transform;
self.remove_collider(entity);
let collider = self.world.add_collider(component, transform);
let record = self.records.get_mut(id).expect("a live record");
record.collider = Some((collider, component.clone()));
self.world.set_layers(collider, record.layers);
if let Some(pipeline) = self.contacts.as_mut() {
let proxies = pipeline.create_body_proxies(
id,
Bodies {
records: &self.records,
statics: &self.statics,
awake: &self.awake,
islands: &self.islands,
},
);
self.records.get_mut(id).expect("a live record").proxies = proxies;
}
self.collider_count += 1;
let slot = collider.index() as usize;
if slot >= self.collider_to_entity.len() {
self.collider_to_entity.resize(slot + 1, None);
}
self.collider_to_entity[slot] = Some(entity);
}
pub fn remove_entity(&mut self, entity: Entity) {
if let Some(&id) = self.entity_to_body.get(&entity) {
self.take_out_joints_of(id);
}
self.remove_collider(entity);
let Some(id) = self.entity_to_body.remove(&entity) else {
return;
};
if let Some(pipeline) = self.contacts.as_mut() {
pipeline.ignored.forget_body(id);
}
let Some(record) = self.records.remove(id) else {
return;
};
if let Some(island) = record.island {
self.islands.remove_member(island, id);
}
match record.set {
BodySet::Static => {
let (_, moved) = self.statics.swap_remove(record.index);
self.reindex_to(moved, record.index);
}
BodySet::Awake => {
let (_, _, moved) = self.awake.swap_remove(record.index);
self.reindex_to(moved, record.index);
}
BodySet::Sleeping => unreachable!("remove_collider woke it"),
}
}
pub fn remove_collider(&mut self, entity: Entity) {
let Some(&id) = self.entity_to_body.get(&entity) else {
return;
};
self.disturb(id);
let Some(record) = self.records.get_mut(id) else {
return;
};
let proxies = std::mem::take(&mut record.proxies);
if let Some(pipeline) = self.contacts.as_mut()
&& !proxies.is_empty()
{
pipeline.destroy_proxies(&proxies);
if let Some(island) = record.island {
self.islands.mark_removed(island);
}
}
if let Some((collider, _)) = record.collider.take() {
self.world.remove(collider);
self.collider_count -= 1;
let slot = collider.index() as usize;
if slot < self.collider_to_entity.len() {
self.collider_to_entity[slot] = None;
}
}
}
pub fn set_collider_layers(&mut self, entity: Entity, bits: u32) -> bool {
let Some(&id) = self.entity_to_body.get(&entity) else {
return false;
};
let Some(record) = self.records.get_mut(id) else {
return false;
};
let Some((collider, _)) = record.collider else {
return false;
};
record.layers = bits;
self.world.set_layers(collider, bits)
}
#[must_use]
pub fn collider_of(&self, entity: Entity) -> Option<ColliderId> {
self.record(entity)?
.collider
.as_ref()
.map(|(collider, _)| *collider)
}
#[must_use]
pub fn entity_of(&self, collider: ColliderId) -> Option<Entity> {
let entity = self.entity_for(collider)?;
(self.collider_of(entity) == Some(collider)).then_some(entity)
}
pub fn step(&mut self, dt: f64) {
self.step_with_clock(dt, None);
}
pub fn step_timed(&mut self, dt: f64, clock: &mut dyn FnMut() -> f64) {
self.step_with_clock(dt, Some(clock));
}
fn step_with_clock(&mut self, dt: f64, clock: Option<&mut dyn FnMut() -> f64>) {
if self.contacts.is_some() {
self.step_contacts(dt, clock);
} else {
apply_forces(&mut self.awake, &self.force_providers, dt);
let AwakeSet {
transforms, bodies, ..
} = &mut self.awake;
for (body, transform) in bodies.iter_mut().zip(transforms.iter_mut()) {
SemiImplicitEuler.step(body, transform, dt);
}
sync_colliders(&mut self.world, &self.records, &self.awake);
}
}
fn step_contacts(&mut self, dt: f64, mut clock: Option<&mut dyn FnMut() -> f64>) {
let Some(pipeline) = self.contacts.as_mut() else {
return;
};
let settings = pipeline.settings;
let mut read = || clock.as_mut().map(|clock| clock());
let start = read();
if !settings.sleep && self.islands.sleeping_bodies() > 0 {
self.islands.wake_all(&mut self.records, &mut self.awake);
}
self.islands.reconcile(&mut self.records, &self.awake);
let reconciled = read();
let lent = Bodies {
records: &self.records,
statics: &self.statics,
awake: &self.awake,
islands: &self.islands,
};
pipeline.update_pairs(lent, dt);
let paired = read();
pipeline.collide(lent, dt);
pipeline.joints.island_events(lent, &mut pipeline.events);
let collided = read();
let events = std::mem::take(&mut pipeline.events);
for &id in &events.wake {
self.islands
.wake_body(&mut self.records, &mut self.awake, id);
}
for &(a, b) in &events.links {
self.islands.link(&mut self.records, &mut self.awake, a, b);
}
for &id in &events.unlinks {
if let Some(island) = self.records.get(id).and_then(|record| record.island) {
self.islands.mark_removed(island);
}
}
let linked = read();
apply_forces(&mut self.awake, &self.force_providers, dt);
pipeline.remember_starts(&self.awake);
pipeline.solve(
&self.records,
&self.statics,
&mut self.awake,
&self.islands,
dt,
);
let solved = read();
pipeline.sweep(
&self.records,
&self.statics,
&mut self.awake,
&self.islands,
dt,
);
let swept = read();
sync_colliders(&mut self.world, &self.records, &self.awake);
pipeline.count_joints(Bodies {
records: &self.records,
statics: &self.statics,
awake: &self.awake,
islands: &self.islands,
});
let broken = std::mem::take(&mut pipeline.joints.broken);
pipeline.counters.broken_joints = broken.len();
for joint_break in &broken {
self.take_out_joint(joint_break.joint);
}
let Some(pipeline) = self.contacts.as_mut() else {
return;
};
pipeline.joints.broken = broken;
let synced = read();
if settings.sleep {
let records = &self.records;
island::update_timers(
&mut self.awake,
settings.sleep_speed,
settings.sleep_angular_speed,
|id| {
records
.get(id)
.and_then(|record| record.collider.as_ref())
.map_or(0.0, |(_, collider)| collider.max_extent())
},
dt,
);
for &id in &events.stirred {
if let Some(record) = self.records.get(id)
&& record.set == BodySet::Awake
{
self.awake.sleep_times[record.index] = 0.0;
}
}
if let Some(island) =
self.islands
.split_candidate(&self.records, &self.awake, settings.time_to_sleep)
{
let edges = pipeline.island_edges(&self.records, island);
self.islands.split(&mut self.records, island, edges);
}
self.islands
.sleep_ready(&mut self.records, &mut self.awake, settings.time_to_sleep);
}
let settled = read();
pipeline.events = events;
let counters = &mut pipeline.counters;
counters.bodies = self.awake.ids.len();
counters.sleeping = self.islands.sleeping_bodies();
counters.islands = self.islands.awake_islands();
counters.sleeping_islands = self.islands.sleeping_islands();
counters.stages = match (
start, reconciled, paired, collided, linked, solved, swept, synced, settled,
) {
(
Some(start),
Some(reconciled),
Some(paired),
Some(collided),
Some(linked),
Some(solved),
Some(swept),
Some(synced),
Some(settled),
) => Some(StageTimes {
broadphase: paired - reconciled,
narrow_phase: collided - paired,
solver: solved - linked,
islands: (reconciled - start) + (linked - collided) + (settled - synced),
continuous: swept - solved,
}),
_ => None,
};
}
#[must_use]
pub fn cast_ray(&mut self, ray: &Ray) -> Option<(Entity, ShapeHit)> {
self.cast_ray_filtered(ray, QueryFilter::ALL)
}
#[must_use]
pub fn cast_ray_filtered(
&mut self,
ray: &Ray,
filter: QueryFilter,
) -> Option<(Entity, ShapeHit)> {
let mut scratch = std::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<(Entity, ShapeHit)> {
self.sweep_sphere_filtered(segment, radius, QueryFilter::ALL)
}
#[must_use]
pub fn sweep_sphere_filtered(
&mut self,
segment: &Segment,
radius: f64,
filter: QueryFilter,
) -> Option<(Entity, ShapeHit)> {
let mut scratch = std::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_body(
&mut self,
entity: Entity,
dt: f64,
radius: f64,
) -> Option<(Entity, ShapeHit)> {
self.sweep_body_filtered(entity, dt, radius, ALL_LAYERS)
}
#[must_use]
pub fn sweep_body_filtered(
&mut self,
entity: Entity,
dt: f64,
radius: f64,
mask: u32,
) -> Option<(Entity, ShapeHit)> {
let body = self.body(entity).copied()?;
let transform = self.transform(entity).copied()?;
let segment = Segment {
start: transform.position - body.velocity * dt,
end: transform.position,
};
let filter = QueryFilter::excluding(self.collider_of(entity)).with_mask(mask);
let (id, hit) = self.world.sweep_sphere_filtered(&segment, radius, filter)?;
Some((self.entity_for(id)?, hit))
}
#[must_use]
pub fn overlap_sphere(&mut self, centre: DVec3, radius: f64) -> Vec<(Entity, 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<(Entity, 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<(Entity, 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<(Entity, OverlapHit)>,
) {
let mut scratch = std::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) -> EntityOverlapQueries<'_> {
let Self {
world,
collider_to_entity,
..
} = self;
EntityOverlapQueries {
queries: world.overlap_queries(),
collider_to_entity,
}
}
#[must_use]
pub fn overlap_aabb(&mut self, aabb: &Aabb) -> Vec<Entity> {
self.overlap_aabb_filtered(aabb, QueryFilter::ALL)
}
#[must_use]
pub fn overlap_aabb_filtered(&mut self, aabb: &Aabb, filter: QueryFilter) -> Vec<Entity> {
let mut scratch = std::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 world(&self) -> &PhysicsWorld {
&self.world
}
pub fn world_mut(&mut self) -> &mut PhysicsWorld {
&mut self.world
}
fn entity_for(&self, id: ColliderId) -> Option<Entity> {
entity_for_in(&self.collider_to_entity, id)
}
fn record(&self, entity: Entity) -> Option<&BodyRecord> {
self.records.get(*self.entity_to_body.get(&entity)?)
}
fn record_for(&mut self, entity: Entity, transform: Transform) -> BodyId {
if let Some(&id) = self.entity_to_body.get(&entity) {
return id;
}
let id = self.records.insert(BodyRecord {
entity,
set: BodySet::Static,
index: 0,
collider: None,
layers: ALL_LAYERS,
material: SurfaceMaterial::DEFAULT,
proxies: Vec::new(),
island: None,
substeps: 0,
filter: CollisionFilter::DEFAULT,
});
let index = self.statics.push(id, transform);
self.records.get_mut(id).expect("just inserted").index = index;
self.entity_to_body.insert(entity, id);
id
}
fn transform_slot(&mut self, id: BodyId) -> &mut Transform {
self.wake(id);
let record = self.records.get(id).expect("a live record");
match record.set {
BodySet::Awake => &mut self.awake.transforms[record.index],
BodySet::Static => &mut self.statics.transforms[record.index],
BodySet::Sleeping => unreachable!("woken above"),
}
}
fn wake(&mut self, id: BodyId) {
self.islands
.wake_body(&mut self.records, &mut self.awake, id);
}
fn disturb(&mut self, id: BodyId) {
self.wake(id);
if self.islands.sleeping_bodies() == 0 {
return;
}
let (Some(pipeline), Some(record)) = (self.contacts.as_ref(), self.records.get(id)) else {
return;
};
if record.proxies.is_empty() {
return;
}
let mut touching = Vec::new();
pipeline.touching_bodies(&record.proxies, &mut touching);
for other in touching {
self.wake(other);
}
}
fn reindex_to(&mut self, moved: Option<BodyId>, index: usize) {
if let Some(record) = moved.and_then(|id| self.records.get_mut(id)) {
record.index = index;
}
}
fn sync_collider(&mut self, id: BodyId) {
let Some(record) = self.records.get(id) else {
return;
};
let Some((collider, component)) = &record.collider else {
return;
};
let transform = match record.set {
BodySet::Awake => &self.awake.transforms[record.index],
BodySet::Static => &self.statics.transforms[record.index],
BodySet::Sleeping => self.islands.transform(record.island, record.index),
};
self.world.place_collider(*collider, component, transform);
}
}
fn apply_forces(awake: &mut AwakeSet, providers: &[Box<dyn ForceProvider>], dt: f64) {
let AwakeSet {
transforms, bodies, ..
} = awake;
for (body, transform) in bodies.iter_mut().zip(transforms.iter()) {
for provider in providers {
provider.apply(body, transform, dt);
}
}
}
fn sync_colliders(world: &mut PhysicsWorld, records: &Pool<BodyRecord>, awake: &AwakeSet) {
for (id, transform) in awake.ids.iter().zip(awake.transforms.iter()) {
if let Some((collider, component)) = records.get(*id).and_then(|r| r.collider.as_ref()) {
world.place_collider(*collider, component, transform);
}
}
}
pub(crate) fn canonical_bits(value: f64) -> u64 {
if value == 0.0 {
0
} else if value.is_nan() {
f64::NAN.to_bits()
} else {
value.to_bits()
}
}
impl Default for PhysicsSystem {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for PhysicsSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PhysicsSystem")
.field("collider_count", &self.collider_count)
.field("body_count", &self.body_count())
.field("force_provider_count", &self.force_providers.len())
.finish()
}
}
impl SystemTrait for PhysicsSystem {
fn name(&self) -> &str {
Self::NAME
}
fn access(&self) -> Access {
Access::none()
}
fn tick(&mut self, dt: f64) {
self.step(dt);
}
fn entity_count(&self) -> usize {
self.collider_count
}
fn sweep(&mut self, dead: &[Entity]) {
for &entity in dead {
self.remove_entity(entity);
}
}
fn debug_draw(&mut self, _ctx: &DebugCtx) {}
fn hash_state(&self, hasher: &mut dyn std::hash::Hasher) {
let mut entities: Vec<(u64, &BodyRecord)> = self
.records
.iter()
.map(|(_, record)| (record.entity.to_bits(), record))
.collect();
entities.sort_unstable_by_key(|(bits, _)| *bits);
for (bits, record) in entities {
hasher.write(&bits.to_le_bytes());
let (transform, body) = match record.set {
BodySet::Awake => (
&self.awake.transforms[record.index],
Some(&self.awake.bodies[record.index]),
),
BodySet::Sleeping => (
self.islands.transform(record.island, record.index),
Some(self.islands.body(record.island, record.index)),
),
BodySet::Static => (&self.statics.transforms[record.index], None),
};
hasher.write(&[1]);
for value in [
transform.position.x,
transform.position.y,
transform.position.z,
transform.rotation.x,
transform.rotation.y,
transform.rotation.z,
transform.rotation.w,
] {
hasher.write(&canonical_bits(value).to_le_bytes());
}
match body {
Some(body) => {
hasher.write(&[1]);
for value in [
body.mass,
body.inverse_mass,
body.velocity.x,
body.velocity.y,
body.velocity.z,
body.force_accum.x,
body.force_accum.y,
body.force_accum.z,
body.angular_velocity.x,
body.angular_velocity.y,
body.angular_velocity.z,
body.torque_accum.x,
body.torque_accum.y,
body.torque_accum.z,
]
.into_iter()
.chain(body.local_inertia.to_cols_array())
{
hasher.write(&canonical_bits(value).to_le_bytes());
}
if body.bullet {
hasher.write(&[3]);
}
if record.substeps != 0 {
hasher.write(&[5]);
hasher.write(&record.substeps.to_le_bytes());
}
if self.contacts.is_some() {
match record.set {
BodySet::Awake => {
hasher.write(&[0]);
let still = self.awake.sleep_times[record.index];
hasher.write(&canonical_bits(still).to_le_bytes());
}
BodySet::Sleeping | BodySet::Static => hasher.write(&[1]),
}
}
}
None => hasher.write(&[0]),
}
if record.filter != CollisionFilter::DEFAULT {
hasher.write(&[7]);
hasher.write(&record.filter.category.to_le_bytes());
hasher.write(&record.filter.mask.to_le_bytes());
}
}
if let Some(pipeline) = &self.contacts {
hasher.write(&[2]);
pipeline.hash_state(&self.records, hasher);
}
}
fn contributes_to_hash(&self) -> bool {
true
}
fn replicate(&self, out: &mut Vec<u8>) -> bool {
let mut entries: Vec<(u64, &Transform)> = self
.records
.iter()
.map(|(_, record)| {
let transform = match record.set {
BodySet::Awake => &self.awake.transforms[record.index],
BodySet::Static => &self.statics.transforms[record.index],
BodySet::Sleeping => self.islands.transform(record.island, record.index),
};
(record.entity.to_bits(), transform)
})
.collect();
entries.sort_unstable_by_key(|(bits, _)| *bits);
let mut component = Vec::with_capacity(Transform::ENCODED_LEN);
for (bits, transform) in &entries {
component.clear();
transform.encode_wire(&mut component);
out.extend_from_slice(&bits.to_le_bytes());
out.extend_from_slice(&(component.len() as u32).to_le_bytes());
out.extend_from_slice(&component);
}
!entries.is_empty()
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::forces::GravityForce;
use glam::DVec3;
fn test_entity(idx: u32) -> Entity {
Entity::from_bits(((1u64) << 32) | idx as u64).expect("test entity")
}
#[test]
fn empty_system_has_no_colliders() {
let phys = PhysicsSystem::new();
assert_eq!(phys.collider_count(), 0);
}
#[test]
fn the_view_names_the_right_entities_from_every_thread_at_once() {
const RADIUS: f64 = 0.45;
const REACH: f64 = 1.5;
let mut phys = PhysicsSystem::new();
let mut placed: Vec<(Entity, DVec3)> = Vec::new();
for idx in 0..40u32 {
let entity = test_entity(idx);
let position = DVec3::new(f64::from(idx % 7), f64::from(idx / 7), 0.0);
let transform = Transform::from_position(position);
phys.set_collider(
entity,
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: RADIUS,
is_trigger: false,
},
&transform,
);
phys.set_transform(entity, transform);
placed.push((entity, position));
}
let centres: Vec<DVec3> = placed.iter().map(|(_, p)| *p).collect();
let oracle = |centre: DVec3| {
let mut hits: Vec<Entity> = placed
.iter()
.filter(|(_, p)| p.distance(centre) <= REACH + RADIUS)
.map(|(e, _)| *e)
.collect();
hits.sort_unstable_by_key(|e| e.to_bits());
hits
};
let expected: Vec<Vec<Entity>> = centres.iter().map(|c| oracle(*c)).collect();
let biggest = expected.iter().map(Vec::len).max().unwrap_or(0);
assert!(
biggest > 4,
"the widest query in the fixture reaches {biggest} entities, which \
is not a neighbourhood",
);
let ask = |queries: &EntityOverlapQueries<'_>| {
let mut scratch = crate::world::QueryScratch::new();
let mut out = Vec::new();
centres
.iter()
.map(|centre| {
queries.overlap_sphere_into(*centre, REACH, &mut scratch, &mut out);
let mut hits: Vec<Entity> = out.iter().map(|&(entity, _)| entity).collect();
hits.sort_unstable_by_key(|entity| entity.to_bits());
hits
})
.collect::<Vec<_>>()
};
let queries = phys.overlap_queries();
assert_eq!(ask(&queries), expected, "the calling thread's own answers");
std::thread::scope(|scope| {
let handles: Vec<_> = (0..4)
.map(|_| scope.spawn(|| ask(&queries)))
.collect::<Vec<_>>();
for handle in handles {
assert_eq!(
handle.join().expect("a query thread panicked"),
expected,
"a thread sharing the view disagreed with the scan",
);
}
});
}
#[derive(Debug, PartialEq)]
struct EntityProbeAnswers {
rays: Vec<Option<(Entity, ShapeHit)>>,
sweeps: Vec<Option<(Entity, ShapeHit)>>,
aabbs: Vec<Vec<Entity>>,
}
#[test]
fn the_view_casts_sweeps_and_boxes_for_the_right_entities_from_every_thread() {
const RADIUS: f64 = 0.45;
const ROWS: u32 = 5;
const COLUMNS: u32 = 7;
const SWEEP_RADIUS: f64 = 0.04;
let mut phys = PhysicsSystem::new();
let mut placed: Vec<(Entity, DVec3)> = Vec::new();
for idx in 0..ROWS * COLUMNS {
let entity = test_entity(idx);
let position = DVec3::new(f64::from(idx % COLUMNS), f64::from(idx / COLUMNS), 0.0);
let transform = Transform::from_position(position);
phys.set_collider(
entity,
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: RADIUS,
is_trigger: false,
},
&transform,
);
phys.set_transform(entity, transform);
placed.push((entity, position));
}
let first_in_row = |row: f64| {
placed
.iter()
.filter(|(_, p)| p.y == row)
.min_by(|(_, a), (_, b)| a.x.total_cmp(&b.x))
.map(|(entity, _)| *entity)
};
let rays: Vec<Ray> = (0..ROWS)
.map(|row| Ray::new(DVec3::new(-10.0, f64::from(row), 0.0), DVec3::X))
.chain(std::iter::once(Ray::new(
DVec3::new(-10.0, 1.5, 0.0),
DVec3::X,
)))
.collect();
let expected_rays: Vec<Option<Entity>> = (0..ROWS)
.map(|row| first_in_row(f64::from(row)))
.chain(std::iter::once(None))
.collect();
let sweeps: Vec<(Segment, f64)> = (0..ROWS)
.map(|row| {
(
Segment::new(
DVec3::new(-10.0, f64::from(row), 0.0),
DVec3::new(10.0, f64::from(row), 0.0),
),
SWEEP_RADIUS,
)
})
.chain(std::iter::once((
Segment::new(DVec3::new(-10.0, 1.5, 0.0), DVec3::new(10.0, 1.5, 0.0)),
SWEEP_RADIUS,
)))
.collect();
let expected_sweeps = expected_rays.clone();
let aabbs = [
Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(0.1)),
Aabb::from_centre_half(DVec3::new(3.0, 2.0, 0.0), DVec3::splat(1.0)),
Aabb::from_centre_half(DVec3::new(50.0, 50.0, 0.0), DVec3::splat(1.0)),
];
let expected_aabbs: Vec<Vec<Entity>> = aabbs
.iter()
.map(|aabb| {
let mut hits: Vec<Entity> = placed
.iter()
.filter(|(_, p)| {
Aabb::from_centre_half(*p, DVec3::splat(RADIUS)).intersects(aabb)
})
.map(|(entity, _)| *entity)
.collect();
hits.sort_unstable_by_key(|entity| entity.to_bits());
hits
})
.collect();
let mut named: Vec<Entity> = expected_rays.iter().flatten().copied().collect();
assert_eq!(named.len(), ROWS as usize, "every row has a nearest entity");
named.sort_unstable_by_key(|entity| entity.to_bits());
named.dedup();
assert_eq!(
named.len(),
ROWS as usize,
"two rows expect the same entity, so a slot-to-entity mix-up could \\
pass this",
);
let widest = expected_aabbs.iter().map(Vec::len).max().unwrap_or(0);
assert!(
widest > 4 && expected_aabbs.iter().any(Vec::is_empty),
"the box probes reach at most {widest} entities and never nothing, \\
so one of the two cases never runs",
);
let exclusive = EntityProbeAnswers {
rays: rays.iter().map(|ray| phys.cast_ray(ray)).collect(),
sweeps: sweeps
.iter()
.map(|(segment, radius)| phys.sweep_sphere(segment, *radius))
.collect(),
aabbs: aabbs
.iter()
.map(|aabb| {
let mut hits = phys.overlap_aabb(aabb);
hits.sort_unstable_by_key(|entity| entity.to_bits());
hits
})
.collect(),
};
assert_eq!(
exclusive
.rays
.iter()
.map(|hit| hit.map(|(entity, _)| entity))
.collect::<Vec<_>>(),
expected_rays,
"the entities the casts named",
);
assert_eq!(
exclusive
.sweeps
.iter()
.map(|hit| hit.map(|(entity, _)| entity))
.collect::<Vec<_>>(),
expected_sweeps,
"the entities the sweeps named",
);
assert_eq!(exclusive.aabbs, expected_aabbs, "the entities in the boxes");
let ask = |queries: &EntityOverlapQueries<'_>| {
let mut scratch = crate::world::QueryScratch::new();
let mut found = Vec::new();
EntityProbeAnswers {
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(),
aabbs: aabbs
.iter()
.map(|aabb| {
queries.overlap_aabb_into(aabb, &mut scratch, &mut found);
let mut hits = found.clone();
hits.sort_unstable_by_key(|entity| entity.to_bits());
hits
})
.collect(),
}
};
let queries = phys.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 placements",
);
}
});
}
fn replicated_entries(out: &[u8]) -> Vec<(u64, Vec<u8>)> {
let mut cursor = 0usize;
let mut entries = Vec::new();
while cursor < out.len() {
let bits = u64::from_le_bytes(out[cursor..cursor + 8].try_into().unwrap());
cursor += 8;
let len = u32::from_le_bytes(out[cursor..cursor + 4].try_into().unwrap()) as usize;
cursor += 4;
entries.push((bits, out[cursor..cursor + len].to_vec()));
cursor += len;
}
entries
}
fn replicated(phys: &PhysicsSystem) -> Vec<u8> {
let mut out = Vec::new();
SystemTrait::replicate(phys, &mut out);
out
}
#[test]
fn replicate_encodes_sorted_transform_blobs() {
let mut phys = PhysicsSystem::new();
let e1 = test_entity(9);
let e2 = test_entity(2);
phys.set_transform(e1, Transform::from_position(DVec3::new(1.0, 2.0, 3.0)));
phys.set_transform(
e2,
Transform::new(
DVec3::new(-4.0, 0.5, 8.0),
glam::DQuat::from_xyzw(0.0, 0.0, 0.0, 1.0),
),
);
let mut out = Vec::new();
assert!(SystemTrait::replicate(&phys, &mut out));
let entity_len = 8 + 4 + Transform::QUANTIZED_LEN;
assert_eq!(
out.len(),
2 * entity_len,
"both inside the range: quantized"
);
let decoded: Vec<_> = replicated_entries(&out)
.into_iter()
.map(|(bits, data)| (bits, Transform::decode_wire(&data).unwrap()))
.collect();
assert_eq!(decoded[0].0, e2.to_bits(), "sorted by entity bits");
assert_eq!(decoded[1].0, e1.to_bits());
assert_eq!(decoded[0].1.position, DVec3::new(-4.0, 0.5, 8.0));
assert_eq!(decoded[1].1.position, DVec3::new(1.0, 2.0, 3.0));
let empty = PhysicsSystem::new();
let mut out = Vec::new();
assert!(!SystemTrait::replicate(&empty, &mut out));
assert!(out.is_empty());
}
#[test]
fn a_sub_quantum_move_replicates_the_same_bytes_and_a_larger_one_does_not() {
let q = Transform::WIRE_POSITION.quantum();
let entity = test_entity(1);
let at = |x: f64| {
let mut phys = PhysicsSystem::new();
phys.set_transform(
entity,
Transform::new(
DVec3::new(x, 1.0, -2.0),
crate::rotation_from_scaled_axis(DVec3::Y * 0.3),
),
);
phys
};
let still = replicated(&at(10.0));
assert_eq!(replicated(&at(10.0 + q / 4.0)), still, "a quarter quantum");
assert_eq!(replicated(&at(10.0 - q / 4.0)), still);
assert_ne!(replicated(&at(10.0 + q)), still, "a whole quantum");
}
#[test]
fn the_determinism_hash_sees_what_quantization_rounds_away() {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let q = Transform::WIRE_POSITION.quantum();
let entity = test_entity(1);
let at = |x: f64| {
let mut phys = PhysicsSystem::new();
phys.set_transform(entity, Transform::from_position(DVec3::new(x, 0.0, 0.0)));
phys
};
let (a, b) = (at(3.0), at(3.0 + q / 8.0));
assert_eq!(
replicated(&a),
replicated(&b),
"the wire cannot tell them apart"
);
let hash = |phys: &PhysicsSystem| {
let mut hasher = DefaultHasher::new();
SystemTrait::hash_state(phys, &mut hasher);
hasher.finish()
};
assert_ne!(hash(&a), hash(&b), "the hash can");
}
#[test]
fn transform_encode_decode_roundtrips_and_lerp_midpoint() {
let t = Transform::new(
DVec3::new(1.25, -2.5, 3.75),
crate::rotation_from_scaled_axis(DVec3::Y),
);
let mut buf = Vec::new();
t.encode(&mut buf);
assert_eq!(buf.len(), t.encoded_len());
let decoded = Transform::decode(&buf).unwrap();
assert_eq!(decoded.position, t.position);
assert!((decoded.rotation.dot(t.rotation) - 1.0).abs() < 1e-12);
assert!(Transform::decode(&buf[..buf.len() - 1]).is_none());
assert!(Transform::decode(&[]).is_none());
let a = Transform::from_position(DVec3::new(0.0, 0.0, 0.0));
let b = Transform::from_position(DVec3::new(10.0, -4.0, 2.0));
let mid = a.lerp(&b, 0.5);
assert_eq!(mid.position, DVec3::new(5.0, -2.0, 1.0));
let at_a = a.lerp(&b, 0.0);
let at_b = a.lerp(&b, 1.0);
assert_eq!(at_a.position, a.position);
assert_eq!(at_b.position, b.position);
}
#[test]
fn set_and_remove_collider() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let transform = Transform::from_position(DVec3::new(1.0, 2.0, 3.0));
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
phys.set_collider(e, &comp, &transform);
assert_eq!(phys.collider_count(), 1);
phys.remove_collider(e);
assert_eq!(phys.collider_count(), 0);
}
#[test]
fn ray_cast_hits_entity() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let transform = Transform::from_position(DVec3::new(5.0, 0.0, 0.0));
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
phys.set_collider(e, &comp, &transform);
let ray = Ray::new(DVec3::ZERO, DVec3::X);
let result = phys.cast_ray(&ray);
assert!(result.is_some());
let (hit_entity, _) = result.unwrap();
assert_eq!(hit_entity, e);
}
#[test]
fn ray_cast_misses_when_no_collider() {
let mut phys = PhysicsSystem::new();
let ray = Ray::new(DVec3::ZERO, DVec3::X);
assert!(phys.cast_ray(&ray).is_none());
}
#[test]
fn overlap_aabb_finds_entity() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let transform = Transform::from_position(DVec3::new(2.0, 0.0, 0.0));
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
phys.set_collider(e, &comp, &transform);
let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(3.0));
let hits = phys.overlap_aabb(&query);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0], e);
}
#[test]
fn sweep_removes_dead_entities() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let transform = Transform::IDENTITY;
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
phys.set_collider(e, &comp, &transform);
assert_eq!(phys.collider_count(), 1);
phys.sweep(&[e]);
assert_eq!(phys.collider_count(), 0);
}
#[test]
fn the_entity_count_starts_at_zero_and_follows_the_colliders_that_are_set() {
let mut phys = PhysicsSystem::new();
assert_eq!(phys.entity_count(), 0);
let e = test_entity(0);
phys.set_collider(
e,
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
},
&Transform::IDENTITY,
);
assert_eq!(phys.entity_count(), 1);
}
#[test]
fn replacing_collider_keeps_count_stable() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let transform = Transform::IDENTITY;
let comp1 = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
let comp2 = ColliderComponent::Box {
offset: DVec3::ZERO,
half_extents: DVec3::splat(2.0),
is_trigger: true,
};
phys.set_collider(e, &comp1, &transform);
phys.set_collider(e, &comp2, &transform);
assert_eq!(phys.collider_count(), 1);
}
#[test]
fn sweep_sphere_hits_entity() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let transform = Transform::from_position(DVec3::new(5.0, 0.0, 0.0));
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
phys.set_collider(e, &comp, &transform);
let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
let result = phys.sweep_sphere(&seg, 0.5);
assert!(result.is_some());
let (hit_entity, _) = result.unwrap();
assert_eq!(hit_entity, e);
}
#[test]
fn sweep_body_catches_a_crossing_a_stationary_overlap_would_miss() {
let mut phys = PhysicsSystem::new();
let bullet = test_entity(0);
let rock = test_entity(1);
let mut body = RigidBody::new_kinematic();
body.velocity = DVec3::new(10.0, 0.0, 0.0);
phys.set_body(bullet, body);
phys.set_transform(bullet, Transform::from_position(DVec3::ZERO));
phys.set_collider(
rock,
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
},
&Transform::from_position(DVec3::new(-5.0, 0.0, 0.0)),
);
let (hit_entity, hit) = phys
.sweep_body(bullet, 1.0, 0.5)
.expect("the sweep crossed the rock");
assert_eq!(hit_entity, rock, "the sweep hit the wrong entity");
assert_eq!(hit.normal, DVec3::NEG_X, "the sweep ran the wrong way");
}
#[test]
fn a_stationary_body_sweeps_nothing_it_does_not_already_touch() {
let mut phys = PhysicsSystem::new();
let bullet = test_entity(0);
phys.set_body(bullet, RigidBody::new_kinematic());
phys.set_transform(bullet, Transform::from_position(DVec3::ZERO));
phys.set_collider(
test_entity(1),
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
},
&Transform::from_position(DVec3::new(1.4, 1.4, 0.0)),
);
assert_eq!(phys.sweep_body(bullet, 1.0, 0.5), None);
}
#[test]
fn sweep_body_leaves_the_swept_colliders_registration_alone() {
let mut phys = PhysicsSystem::new();
let mover = test_entity(0);
let mut body = RigidBody::new_kinematic();
body.velocity = DVec3::new(10.0, 0.0, 0.0);
phys.set_body(mover, body);
phys.set_collider(
mover,
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
},
&Transform::from_position(DVec3::ZERO),
);
let collider_of = |phys: &PhysicsSystem| {
phys.record(mover)
.and_then(|record| record.collider.as_ref())
.map(|(collider, _)| *collider)
.expect("the mover has a collider")
};
let before = collider_of(&phys);
for _ in 0..8 {
let _ = phys.sweep_body(mover, 1.0, 0.5);
}
assert_eq!(
collider_of(&phys),
before,
"the sweep re-registered the collider it swept"
);
assert_eq!(phys.collider_count(), 1);
}
#[test]
fn sweep_body_never_hits_the_body_it_sweeps() {
let sphere = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
let mut phys = PhysicsSystem::new();
let mover = test_entity(0);
let wall = test_entity(1);
let mut body = RigidBody::new_kinematic();
body.velocity = DVec3::new(10.0, 0.0, 0.0);
phys.set_body(mover, body);
phys.set_collider(mover, &sphere, &Transform::from_position(DVec3::ZERO));
assert_eq!(
phys.sweep_body(mover, 1.0, 0.5),
None,
"the only collider in the world is the mover's own"
);
phys.set_collider(
wall,
&sphere,
&Transform::from_position(DVec3::new(0.5, 0.0, 0.0)),
);
let (hit_entity, hit) = phys
.sweep_body(mover, 1.0, 0.5)
.expect("the wall is on the segment");
assert_eq!(hit_entity, wall, "the mover masked the wall with itself");
assert!((hit.t - 0.90).abs() < 1e-9, "expected ~0.90, got {}", hit.t);
}
#[test]
fn overlap_sphere_into_answers_the_owned_form_and_reuses_the_buffer() {
let mut phys = PhysicsSystem::new();
for (index, x) in [0.0, 1.0, 2.0, 40.0].into_iter().enumerate() {
let e = test_entity(index as u32);
let at = Transform::from_position(DVec3::new(x, 0.0, 0.0));
phys.set_collider(
e,
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 0.5,
is_trigger: false,
},
&at,
);
}
let owned = phys.overlap_sphere(DVec3::ZERO, 2.0);
assert!(
owned.len() > 1 && owned.len() < 4,
"the fixture must include some colliders and exclude some: {}",
owned.len(),
);
let mut out = Vec::new();
phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
assert_eq!(out, owned, "the two forms disagree");
out.push((test_entity(99), owned[0].1));
phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
assert_eq!(
out, owned,
"the buffer was appended to rather than refilled"
);
let capacity = out.capacity();
for _ in 0..64 {
phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
}
assert_eq!(
out.capacity(),
capacity,
"the buffer grew on a repeat query, so the loop still allocates",
);
let mut scratch = crate::world::QueryScratch::new();
let view = phys.overlap_queries();
out.push((test_entity(99), owned[0].1));
view.overlap_sphere_filtered_into(
DVec3::ZERO,
2.0,
QueryFilter::ALL,
&mut scratch,
&mut out,
);
assert_eq!(out, owned, "the view's buffer was appended to");
let mut entities = vec![test_entity(99)];
view.overlap_sphere_entities_into(DVec3::ZERO, 2.0, &mut scratch, &mut entities);
let named: Vec<Entity> = owned.iter().map(|&(entity, _)| entity).collect();
assert_eq!(entities, named, "the entities-only form disagrees");
}
#[test]
fn a_velocity_written_through_body_mut_is_the_one_that_integrates() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
phys.set_body(e, RigidBody::new_kinematic());
phys.set_transform(e, Transform::from_position(DVec3::ZERO));
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 0.5,
is_trigger: false,
};
phys.set_collider(e, &comp, &Transform::from_position(DVec3::ZERO));
phys.apply_force(e, DVec3::new(1000.0, 0.0, 0.0));
phys.step(1.0 / 60.0);
assert_eq!(
phys.transform(e).expect("a transform").position,
DVec3::ZERO,
"a force moved a kinematic body",
);
phys.body_mut(e).expect("a body").velocity = DVec3::new(3.0, 0.0, 0.0);
let dt = 1.0 / 60.0;
phys.step(dt);
assert!(
(phys.transform(e).expect("a transform").position.x - 3.0 * dt).abs() < 1e-12,
"the written velocity did not reach the integrator: {:?}",
phys.transform(e).expect("a transform").position,
);
assert_eq!(
phys.body(e).expect("a body").velocity,
DVec3::new(3.0, 0.0, 0.0),
"the write did not survive the step",
);
}
#[test]
fn a_steered_body_reaches_the_broadphase_on_the_step_and_not_before() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
phys.set_body(e, RigidBody::new_kinematic());
let at = Transform::from_position(DVec3::new(10.0, 0.0, 0.0));
phys.set_transform(e, at);
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 0.5,
is_trigger: false,
};
phys.set_collider(e, &comp, &at);
phys.body_mut(e).expect("a body").velocity = DVec3::new(0.0, 600.0, 0.0);
assert_eq!(
phys.overlap_sphere(DVec3::new(10.0, 0.0, 0.0), 1.0).len(),
1,
"writing a velocity moved the collider before anything stepped",
);
phys.step(1.0 / 60.0);
assert!(
phys.overlap_sphere(DVec3::new(10.0, 0.0, 0.0), 1.0)
.is_empty(),
"the step moved the body and the broadphase did not hear about it",
);
assert_eq!(
phys.overlap_sphere(phys.transform(e).expect("a transform").position, 1.0)
.len(),
1,
"the collider is not where the body now is",
);
}
#[test]
fn body_falls_under_gravity() {
let mut phys = PhysicsSystem::new();
phys.add_force_provider(Box::new(GravityForce::EARTH));
let e = test_entity(0);
phys.set_body(e, RigidBody::new_dynamic(1.0));
phys.set_transform(e, Transform::from_position(DVec3::new(0.0, 100.0, 0.0)));
let dt = 1.0 / 60.0;
for _ in 0..60 {
phys.step(dt);
}
let t = phys.transform(e).unwrap();
assert!(
t.position.y < 96.0 && t.position.y > 94.0,
"expected pos.y ~95.1, got {}",
t.position.y
);
let b = phys.body(e).unwrap();
assert!(
b.velocity.y < -9.0 && b.velocity.y > -10.5,
"expected vy ~-9.81, got {}",
b.velocity.y
);
}
#[test]
fn kinematic_body_stays_put() {
let mut phys = PhysicsSystem::new();
phys.add_force_provider(Box::new(GravityForce::EARTH));
let e = test_entity(0);
phys.set_body(e, RigidBody::new_kinematic());
phys.set_transform(e, Transform::from_position(DVec3::new(5.0, 5.0, 5.0)));
phys.step(1.0 / 60.0);
let t = phys.transform(e).unwrap();
assert_eq!(t.position, DVec3::new(5.0, 5.0, 5.0));
}
#[test]
fn collider_moves_with_body_after_integration() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let body = {
let mut b = RigidBody::new_dynamic(1.0);
b.velocity = DVec3::new(10.0, 0.0, 0.0);
b
};
let transform = Transform::from_position(DVec3::new(0.0, 0.0, 0.0));
let comp = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
phys.set_body(e, body);
phys.set_collider(e, &comp, &transform);
phys.step(0.5);
let t = phys.transform(e).unwrap();
assert!((t.position.x - 5.0).abs() < 1e-12);
let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X);
let result = phys.cast_ray(&ray);
assert!(result.is_some());
let (hit_entity, hit) = result.unwrap();
assert_eq!(hit_entity, e);
assert!((hit.t - 9.0).abs() < 0.01, "t = {}", hit.t);
}
#[test]
fn remove_entity_cleans_up_all_data() {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
phys.set_body(e, RigidBody::new_dynamic(1.0));
phys.set_collider(
e,
&ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
},
&Transform::IDENTITY,
);
assert_eq!(phys.body_count(), 1);
assert_eq!(phys.collider_count(), 1);
phys.remove_entity(e);
assert_eq!(phys.body_count(), 0);
assert_eq!(phys.collider_count(), 0);
assert!(phys.body(e).is_none());
assert!(phys.transform(e).is_none());
}
#[test]
fn multiple_bodies_integrate_independently() {
let mut phys = PhysicsSystem::new();
phys.add_force_provider(Box::new(GravityForce::EARTH));
let e1 = test_entity(0);
let e2 = test_entity(1);
phys.set_body(e1, RigidBody::new_dynamic(1.0));
phys.set_transform(e1, Transform::from_position(DVec3::new(0.0, 0.0, 0.0)));
phys.set_body(e2, RigidBody::new_kinematic());
phys.set_transform(e2, Transform::from_position(DVec3::new(10.0, 10.0, 0.0)));
phys.step(1.0 / 60.0);
let t1 = phys.transform(e1).unwrap();
let t2 = phys.transform(e2).unwrap();
assert!(t1.position.y < 0.0, "dynamic body should fall");
assert_eq!(
t2.position,
DVec3::new(10.0, 10.0, 0.0),
"kinematic should not move"
);
}
#[test]
fn a_step_with_no_bodies_applies_no_force_and_creates_nothing() {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug)]
struct CountingGravity(Arc<AtomicUsize>);
impl ForceProvider for CountingGravity {
fn apply(&self, body: &mut RigidBody, transform: &Transform, dt: f64) {
self.0.fetch_add(1, Ordering::SeqCst);
GravityForce::EARTH.apply(body, transform, dt);
}
}
let applications = Arc::new(AtomicUsize::new(0));
let mut phys = PhysicsSystem::new();
phys.add_force_provider(Box::new(CountingGravity(Arc::clone(&applications))));
let mut before = DefaultHasher::new();
SystemTrait::hash_state(&phys, &mut before);
phys.step(1.0 / 60.0);
assert_eq!(
applications.load(Ordering::SeqCst),
0,
"there is no body for a force provider to be applied to"
);
assert_eq!(phys.body_count(), 0);
assert_eq!(phys.collider_count(), 0);
let mut after = DefaultHasher::new();
SystemTrait::hash_state(&phys, &mut after);
assert_eq!(after.finish(), before.finish(), "the step wrote state");
}
#[test]
fn tick_uses_the_schedule_dt_rather_than_an_assumed_rate() {
let simulate = |hz: u32| {
let mut phys = PhysicsSystem::new();
let e = test_entity(0);
let mut body = RigidBody::new_dynamic(1.0);
body.velocity = DVec3::new(10.0, 0.0, 0.0);
phys.set_body(e, body);
phys.set_transform(e, Transform::IDENTITY);
let dt = 1.0 / f64::from(hz);
for _ in 0..hz {
SystemTrait::tick(&mut phys, dt);
}
phys.transform(e).unwrap().position.x
};
let at_60 = simulate(60);
let at_30 = simulate(30);
assert!((at_60 - 10.0).abs() < 1e-9, "x = {at_60}");
assert!((at_30 - 10.0).abs() < 1e-9, "x = {at_30}");
}
#[test]
fn step_visits_bodies_in_canonical_order() {
let build = |reverse: bool| {
let mut phys = PhysicsSystem::new();
phys.add_force_provider(Box::new(GravityForce::EARTH));
let mut indices: Vec<u32> = (0..16).collect();
if reverse {
indices.reverse();
}
for i in indices {
let e = test_entity(i);
let mut body = RigidBody::new_dynamic(1.0 + f64::from(i) * 0.25);
body.velocity = DVec3::new(f64::from(i) * 0.1, 0.0, 0.0);
phys.set_body(e, body);
phys.set_transform(e, Transform::from_position(DVec3::splat(f64::from(i))));
}
for _ in 0..120 {
phys.step(1.0 / 120.0);
}
phys
};
let forward = build(false);
let backward = build(true);
for i in 0..16 {
let e = test_entity(i);
assert_eq!(
forward.transform(e).unwrap().position,
backward.transform(e).unwrap().position,
"entity {i} diverged"
);
}
}
#[test]
fn hash_state_covers_physics_state_in_canonical_order() {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher as _;
fn hash(phys: &PhysicsSystem) -> u64 {
let mut h = DefaultHasher::new();
SystemTrait::hash_state(phys, &mut h);
h.finish()
}
let build = |reverse: bool, y: f64| {
let mut phys = PhysicsSystem::new();
let mut indices: Vec<u32> = (0..8).collect();
if reverse {
indices.reverse();
}
for i in indices {
let e = test_entity(i);
phys.set_body(e, RigidBody::new_dynamic(1.0 + f64::from(i)));
phys.set_transform(
e,
Transform::from_position(DVec3::new(f64::from(i), y, 0.0)),
);
}
phys
};
assert!(SystemTrait::contributes_to_hash(&build(false, 0.0)));
assert_eq!(hash(&build(false, 0.0)), hash(&build(true, 0.0)));
assert_ne!(hash(&build(false, 0.0)), hash(&build(false, 1.0)));
let mut moving = build(false, 0.0);
let e = test_entity(3);
let mut body = *moving.body(e).unwrap();
body.velocity = DVec3::new(0.0, -1.0, 0.0);
moving.set_body(e, body);
assert_ne!(hash(&build(false, 0.0)), hash(&moving));
}
#[test]
fn removing_from_the_middle_of_a_set_leaves_every_other_body_its_own_state() {
let mut phys = PhysicsSystem::new();
let at = |i: u32| DVec3::new(f64::from(i) * 10.0, 0.0, 0.0);
let sphere = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
for i in 0..12u32 {
let e = test_entity(i);
phys.set_collider(e, &sphere, &Transform::from_position(at(i)));
if i % 3 != 0 {
let mut body = RigidBody::new_dynamic(1.0 + f64::from(i));
body.velocity = DVec3::Y;
phys.set_body(e, body);
}
}
for i in [1u32, 3, 7, 0, 11] {
phys.remove_entity(test_entity(i));
}
phys.step(1.0);
for i in 0..12u32 {
let e = test_entity(i);
let removed = [1u32, 3, 7, 0, 11].contains(&i);
if removed {
assert!(phys.transform(e).is_none(), "{i} survived its removal");
continue;
}
let has_body = i % 3 != 0;
let want = at(i) + if has_body { DVec3::Y } else { DVec3::ZERO };
assert_eq!(
phys.transform(e).expect("a transform").position,
want,
"entity {i} has another's transform"
);
assert_eq!(
phys.body(e).map(|body| body.mass),
has_body.then(|| 1.0 + f64::from(i)),
"entity {i} has another's body"
);
let hit = phys
.cast_ray(&Ray::new(want - DVec3::Z * 5.0, DVec3::Z))
.map(|(entity, _)| entity);
assert_eq!(hit, Some(e), "entity {i}'s collider is not where it is");
}
assert_eq!(phys.body_count(), 5);
assert_eq!(phys.collider_count(), 7);
}
#[test]
fn a_body_moves_a_static_entity_into_the_awake_set_with_its_transform() {
let mut phys = PhysicsSystem::new();
let (wall, prop, crate_) = (test_entity(0), test_entity(1), test_entity(2));
phys.set_transform(wall, Transform::from_position(DVec3::X));
phys.set_transform(crate_, Transform::from_position(DVec3::Y));
phys.set_transform(prop, Transform::from_position(DVec3::Z));
let mut body = RigidBody::new_kinematic();
body.velocity = DVec3::X;
phys.set_body(wall, body);
phys.step(1.0);
assert_eq!(
phys.transform(wall).expect("a transform").position,
DVec3::X * 2.0
);
assert_eq!(
phys.transform(crate_).expect("a transform").position,
DVec3::Y
);
assert_eq!(
phys.transform(prop).expect("a transform").position,
DVec3::Z
);
assert!(phys.body(crate_).is_none() && phys.body(prop).is_none());
assert_eq!(phys.body_count(), 1);
}
#[test]
fn a_material_is_carried_on_its_entity_and_defaults_until_set() {
let mut phys = PhysicsSystem::new();
let (ice, floor) = (test_entity(0), test_entity(1));
let ghost = test_entity(2);
phys.set_body(ice, RigidBody::new_dynamic(1.0));
phys.set_transform(floor, Transform::IDENTITY);
assert_eq!(phys.material(ice), Some(SurfaceMaterial::DEFAULT));
let slick = SurfaceMaterial::new(0.02, 0.1);
assert!(phys.set_material(ice, slick));
assert!(phys.set_material(floor, SurfaceMaterial::new(0.9, 0.0)));
assert_eq!(phys.material(ice), Some(slick));
assert_eq!(phys.material(floor).map(|m| m.friction), Some(0.9));
assert!(!phys.set_material(ghost, slick), "an unregistered entity");
assert_eq!(phys.material(ghost), None);
phys.remove_entity(ice);
assert_eq!(phys.material(ice), None, "the material outlived its entity");
}
#[test]
fn the_hash_does_not_tell_a_negative_zero_from_a_positive_one() {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher as _;
let hash = |vx: f64| {
let mut phys = PhysicsSystem::new();
let mut body = RigidBody::new_dynamic(1.0);
body.velocity = DVec3::new(vx, 1.0, 0.0);
phys.set_body(test_entity(0), body);
let mut h = DefaultHasher::new();
SystemTrait::hash_state(&phys, &mut h);
h.finish()
};
assert_eq!(hash(0.0), hash(-0.0));
assert_ne!(
hash(0.0),
hash(f64::MIN_POSITIVE),
"the hash cannot see velocity"
);
}
}
#[cfg(test)]
#[path = "system/query_layer_tests.rs"]
mod query_layer_tests;