Skip to main content

crcbl_phys/
system.rs

1//! ECS physics system: bridges `PhysicsWorld` with entity-component data.
2//!
3//! [`PhysicsSystem`] implements [`crcbl_ecs::SystemTrait`] so it can be
4//! registered in a schedule. It owns a [`crate::PhysicsWorld`], stores
5//! per-entity rigid body and transform data, and drives the integration
6//! loop with configurable force providers.
7//!
8//! # Storage: dense sets behind generational ids
9//!
10//! Contact-solver decision 8 (`docs/notes/simulation.md`) sets the layout,
11//! after Box3D's: a body is named by a **generational id** — a [`Handle`] from
12//! a [`Pool`] of cold records — and the record says which **set** its state
13//! lives in and at which **index**. A set is struct-of-arrays: the ids, the
14//! transforms and, for the set that moves, the bodies, each column packed with
15//! no holes, so [`PhysicsSystem::step`] walks contiguous arrays in their own
16//! order and never touches a hash map or sorts anything. The entity-to-id map
17//! is consulted only where an entity crosses in: the methods that take an
18//! [`Entity`].
19//!
20//! There are three sets. **Static** holds an entity that has a transform and
21//! no [`RigidBody`] — a wall's collider, a replicated prop — and nothing steps
22//! it. **Awake** holds every entity with a body, dynamic or kinematic, that
23//! steps. **Sleeping** is a set per sleeping island, held by the island, in a
24//! system with contacts: see [`crate::contact`]. Whatever changes a sleeping
25//! body — [`PhysicsSystem::body_mut`], [`PhysicsSystem::set_transform`] and
26//! the rest — wakes its island first, so only the awake and static sets are
27//! ever written to from outside a step.
28//!
29//! **Removal swaps.** Taking a body out of a set moves the set's last body into
30//! the hole and rewrites that one record's index, so a set stays dense and its
31//! order is a function of the calls that built it. Two runs of one script
32//! build the same order; two different call histories reaching the same bodies
33//! may not, which is why [`SystemTrait::hash_state`] and
34//! [`SystemTrait::replicate`] still visit entities in ascending order, as
35//! `crcbl_ecs::System` does — they describe state, not the order it was built
36//! in.
37//!
38//! # Where f32 goes later
39//!
40//! Decision 7 makes the solver's interior `f32` over `f64` positions once the
41//! solver is wide, at rung 6. The awake set is where that lands: velocities,
42//! deltas and impulses become a hot column of their own beside `transforms`,
43//! indexed exactly like it, while positions stay in `transforms` as `f64`.
44//! Adding a column is adding a `Vec` to the awake set and a line to its push
45//! and swap-remove; the id, the record and the (set, index) addressing do not
46//! change shape.
47
48mod clearance;
49mod collision_filter;
50mod debug;
51mod ignored_contacts;
52mod joints;
53
54pub use collision_filter::CollisionFilter;
55pub use debug::{CONTACT_NORMAL_LENGTH, PhysicsDebugLine};
56pub use ignored_contacts::ContactPairError;
57
58use std::collections::HashMap;
59
60use crcbl_core::{Handle, Pool};
61use crcbl_ecs::{Access, DebugCtx, Entity, SystemTrait};
62use glam::DVec3;
63
64use crate::collider::Aabb;
65use crate::components::{ColliderComponent, RigidBody, Transform};
66use crate::contact::broadphase::ProxyId;
67use crate::contact::island::{self, IslandId, Islands};
68use crate::contact::{
69    Bodies, ContactCounters, ContactPipeline, ContactReport, ContactSettings, KineticContact,
70    PlaneId, StageTimes,
71};
72use crate::forces::ForceProvider;
73use crate::integrator::{Integrator as _, SemiImplicitEuler};
74use crate::material::SurfaceMaterial;
75use crate::query::{OverlapHit, ShapeHit};
76use crate::world::{
77    ALL_LAYERS, ColliderId, OverlapQueries, PhysicsWorld, QueryFilter, QueryScratch,
78};
79use crate::{Ray, Segment};
80
81// ---------------------------------------------------------------------------
82// Body storage
83// ---------------------------------------------------------------------------
84
85/// A body's generational id: the slot of its [`BodyRecord`].
86pub(crate) type BodyId = Handle<BodyRecord>;
87
88/// Which set a body's state lives in.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub(crate) enum BodySet {
91    /// A transform and no body: never stepped.
92    Static,
93    /// A body, dynamic or kinematic: stepped every [`PhysicsSystem::step`].
94    Awake,
95    /// A dynamic body whose island sleeps: held by the island, and never
96    /// stepped.
97    Sleeping,
98}
99
100/// The cold half of a body: what names it and what the step never reads.
101#[derive(Debug)]
102pub(crate) struct BodyRecord {
103    /// The entity this body belongs to, for mapping hits and hashing.
104    pub(crate) entity: Entity,
105    /// The set its state lives in.
106    pub(crate) set: BodySet,
107    /// Its index in that set's columns.
108    pub(crate) index: usize,
109    /// Its collider in the world, and the component it was built from.
110    pub(crate) collider: Option<(ColliderId, ColliderComponent)>,
111    /// The query layers its collider is put on, kept here so a collider that
112    /// [`PhysicsSystem::set_collider`] replaces is put back on them.
113    pub(crate) layers: u32,
114    /// Its surface's friction and restitution.
115    pub(crate) material: SurfaceMaterial,
116    /// Its collider's proxies in the contact broadphase, one per part in part
117    /// order — one for anything but a compound — in a system with contacts
118    /// and for a collider that is not a trigger. Empty otherwise.
119    pub(crate) proxies: Vec<ProxyId>,
120    /// Its island, for a dynamic body in a system with contacts that has
121    /// stepped since it became one.
122    pub(crate) island: Option<IslandId>,
123    /// The substeps it asks the solver for, or 0 for the system's own: see
124    /// [`PhysicsSystem::set_substeps`].
125    pub(crate) substeps: u32,
126    /// Which bodies the solver lets it touch: see
127    /// [`PhysicsSystem::set_collision_filter`].
128    pub(crate) filter: CollisionFilter,
129}
130
131/// Transforms with no body: struct-of-arrays, dense, indexed alike.
132#[derive(Debug, Default)]
133pub(crate) struct StaticSet {
134    pub(crate) ids: Vec<BodyId>,
135    pub(crate) transforms: Vec<Transform>,
136}
137
138/// Bodies that step: struct-of-arrays, dense, indexed alike.
139#[derive(Debug, Default)]
140pub(crate) struct AwakeSet {
141    pub(crate) ids: Vec<BodyId>,
142    pub(crate) transforms: Vec<Transform>,
143    pub(crate) bodies: Vec<RigidBody>,
144    /// How long each body has been slow enough to sleep, in seconds.
145    pub(crate) sleep_times: Vec<f64>,
146}
147
148impl StaticSet {
149    fn push(&mut self, id: BodyId, transform: Transform) -> usize {
150        self.ids.push(id);
151        self.transforms.push(transform);
152        self.ids.len() - 1
153    }
154
155    /// Removes `index`, returning its transform and the id now at `index`, if
156    /// one moved there.
157    fn swap_remove(&mut self, index: usize) -> (Transform, Option<BodyId>) {
158        self.ids.swap_remove(index);
159        let transform = self.transforms.swap_remove(index);
160        (transform, self.ids.get(index).copied())
161    }
162}
163
164impl AwakeSet {
165    /// Adds a body, its sleep timer at zero, and returns its index.
166    pub(crate) fn push(&mut self, id: BodyId, transform: Transform, body: RigidBody) -> usize {
167        self.ids.push(id);
168        self.transforms.push(transform);
169        self.bodies.push(body);
170        self.sleep_times.push(0.0);
171        self.ids.len() - 1
172    }
173
174    /// Removes `index`, returning its transform and body and the id now at
175    /// `index`, if one moved there.
176    pub(crate) fn swap_remove(&mut self, index: usize) -> (Transform, RigidBody, Option<BodyId>) {
177        self.ids.swap_remove(index);
178        let transform = self.transforms.swap_remove(index);
179        let body = self.bodies.swap_remove(index);
180        self.sleep_times.swap_remove(index);
181        (transform, body, self.ids.get(index).copied())
182    }
183}
184
185// ---------------------------------------------------------------------------
186// PhysicsSystem
187// ---------------------------------------------------------------------------
188
189/// ECS system that owns a [`PhysicsWorld`], stores rigid body dynamics data,
190/// and runs the integration loop with force providers.
191///
192/// See the [module docs](self) for how bodies are stored.
193///
194/// # Integration loop
195///
196/// Each `tick(dt)` calls `step(dt)` once with the schedule's real tick period.
197/// Without contacts the caller is responsible for substepping: call
198/// `step(substep_dt)` multiple times per tick to advance physics at a higher
199/// rate than the game tick. A system made
200/// [`with_contacts`](Self::with_contacts) substeps inside `step` instead,
201/// because collision runs once a tick and the solver several times; see
202/// [`step`](Self::step).
203///
204/// # Entities
205///
206/// An [`Entity`] here is only a key: a generational
207/// `crcbl_core::Handle<EntityMarker>`, compared and hashed and never looked up
208/// anywhere else. It can come from any `crcbl_core::Pool<EntityMarker>` — a
209/// `crcbl_ecs::World`'s, or one a game allocates its own entities from — and
210/// nothing here asks that pool whether a handle is still alive.
211///
212/// That is why [`remove_entity`](Self::remove_entity) belongs **before** the
213/// handle is freed. The system never learns that a pool let one go: until it
214/// is removed the body keeps stepping, its collider stays in the world, and
215/// every query that meets it answers with a handle its pool calls dead. The
216/// old handle still removes the right body afterwards — its generation keeps
217/// it from naming whatever the pool reissues the slot to — but only a caller
218/// that kept it can say which body to remove. A system registered in a
219/// `crcbl_ecs` schedule is told by [`SystemTrait::sweep`], which removes each
220/// dead entity for it; a game with its own pool has to do the same itself.
221pub struct PhysicsSystem {
222    world: PhysicsWorld,
223
224    /// Every registered entity's cold record, issuing its generational id.
225    records: Pool<BodyRecord>,
226    /// Entity → body id: the ECS boundary, and read nowhere else.
227    entity_to_body: HashMap<Entity, BodyId>,
228    /// Transforms with no body.
229    statics: StaticSet,
230    /// Bodies that step.
231    awake: AwakeSet,
232    /// The islands, and the sleeping ones' bodies. Empty without contacts.
233    islands: Islands,
234    /// How many records hold a collider.
235    collider_count: usize,
236    /// ColliderId → Entity reverse mapping.
237    collider_to_entity: Vec<Option<Entity>>,
238
239    /// Force providers applied in order each substep before integration.
240    force_providers: Vec<Box<dyn ForceProvider>>,
241
242    /// The buffers an overlap query works in, kept between calls so
243    /// [`PhysicsSystem::overlap_sphere_into`] allocates nothing. A caller
244    /// querying from several threads brings its own — see
245    /// [`EntityOverlapQueries`].
246    scratch: QueryScratch,
247
248    /// The contact pipeline, for a system made with
249    /// [`with_contacts`](Self::with_contacts).
250    contacts: Option<Box<ContactPipeline>>,
251}
252
253/// Read-only overlap queries by entity, against a broadphase already built.
254///
255/// [`PhysicsSystem::overlap_queries`] is the only thing that makes one, and it
256/// takes `&mut PhysicsSystem` to build the tree before handing back this shared
257/// borrow — so the tree is current for as long as this exists, and nothing can
258/// move a body while it does. [`crate::world::OverlapQueries`] carries the full
259/// argument; the difference here is only that the hits come back as entities.
260///
261/// **This is what a `par_for` over a crowd captures.** It is `Copy` and `Sync`,
262/// every chunk queries through the same one, and each chunk brings a
263/// [`QueryScratch`] of its own.
264#[derive(Clone, Copy, Debug)]
265pub struct EntityOverlapQueries<'a> {
266    queries: OverlapQueries<'a>,
267    collider_to_entity: &'a [Option<Entity>],
268}
269
270impl EntityOverlapQueries<'_> {
271    /// [`PhysicsSystem::overlap_sphere_into`] under a shared borrow, working in
272    /// `scratch` instead of the system's own buffers.
273    ///
274    /// `out` is cleared and then filled, with the same entities in the same
275    /// order the `&mut self` form produces — which is the property a sample
276    /// swapping one for the other depends on, and which holds because the two
277    /// share one traversal rather than because they were compared.
278    /// `crcbl_phys::system::tests::the_view_names_the_right_entities_from_every_thread_at_once`
279    /// checks the entities against the positions they were placed at.
280    pub fn overlap_sphere_into(
281        &self,
282        centre: DVec3,
283        radius: f64,
284        scratch: &mut QueryScratch,
285        out: &mut Vec<(Entity, OverlapHit)>,
286    ) {
287        self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, scratch, out);
288    }
289
290    /// [`overlap_sphere_into`](Self::overlap_sphere_into) naming only the
291    /// entities whose collider `filter` admits — see [`QueryFilter`].
292    pub fn overlap_sphere_filtered_into(
293        &self,
294        centre: DVec3,
295        radius: f64,
296        filter: QueryFilter,
297        scratch: &mut QueryScratch,
298        out: &mut Vec<(Entity, OverlapHit)>,
299    ) {
300        out.clear();
301        let mut hits = std::mem::take(&mut scratch.hits);
302        self.queries
303            .overlap_sphere_filtered_into(centre, radius, filter, scratch, &mut hits);
304        for &(id, hit) in hits.iter() {
305            let Some(entity) = self.entity_for(id) else {
306                continue;
307            };
308            out.push((entity, hit));
309        }
310        // Back where it came from, keeping the capacity for the next call.
311        scratch.hits = hits;
312    }
313
314    /// [`overlap_sphere_into`](Self::overlap_sphere_into) naming the entities
315    /// and dropping their hits: the same entities in the same order.
316    ///
317    /// The fast path for a crowd pass that never reads a hit —
318    /// [`OverlapQueries::overlap_sphere_ids_into`] says what it saves and how
319    /// that was measured.
320    pub fn overlap_sphere_entities_into(
321        &self,
322        centre: DVec3,
323        radius: f64,
324        scratch: &mut QueryScratch,
325        out: &mut Vec<Entity>,
326    ) {
327        out.clear();
328        let mut ids = std::mem::take(&mut scratch.ids);
329        self.queries
330            .overlap_sphere_ids_into(centre, radius, scratch, &mut ids);
331        out.extend(ids.iter().filter_map(|&id| self.entity_for(id)));
332        scratch.ids = ids;
333    }
334
335    /// [`PhysicsSystem::overlap_aabb`] under a shared borrow, writing into a
336    /// buffer the caller owns.
337    ///
338    /// `out` is cleared and then filled with the same entities in the same
339    /// order the `&mut self` form produces, because that form is this one.
340    /// It answers as [`PhysicsSystem::overlap_aabb`] does: a box, a compound
341    /// or a mesh where its shape meets `aabb`, a sphere or a capsule wherever
342    /// the box around it does.
343    pub fn overlap_aabb_into(
344        &self,
345        aabb: &Aabb,
346        scratch: &mut QueryScratch,
347        out: &mut Vec<Entity>,
348    ) {
349        self.overlap_aabb_filtered_into(aabb, QueryFilter::ALL, scratch, out);
350    }
351
352    /// [`overlap_aabb_into`](Self::overlap_aabb_into) naming only the entities
353    /// whose collider `filter` admits — see [`QueryFilter`].
354    pub fn overlap_aabb_filtered_into(
355        &self,
356        aabb: &Aabb,
357        filter: QueryFilter,
358        scratch: &mut QueryScratch,
359        out: &mut Vec<Entity>,
360    ) {
361        out.clear();
362        let mut ids = std::mem::take(&mut scratch.ids);
363        self.queries
364            .overlap_aabb_filtered_into(aabb, filter, scratch, &mut ids);
365        for id in ids.iter() {
366            let Some(entity) = self.entity_for(*id) else {
367                continue;
368            };
369            out.push(entity);
370        }
371        scratch.ids = ids;
372    }
373
374    /// [`PhysicsSystem::cast_ray`] under a shared borrow, working in `scratch`
375    /// instead of the system's own buffers.
376    ///
377    /// Triggers are non-solid and are skipped, and a hit on a collider no
378    /// entity is mapped to answers `None` — both exactly as in the `&mut self`
379    /// form, which calls this one.
380    #[must_use]
381    pub fn cast_ray(&self, ray: &Ray, scratch: &mut QueryScratch) -> Option<(Entity, ShapeHit)> {
382        self.cast_ray_filtered(ray, QueryFilter::ALL, scratch)
383    }
384
385    /// [`cast_ray`](Self::cast_ray) over only the colliders `filter` admits —
386    /// see [`QueryFilter`]. Its exclusion is a [`ColliderId`], which
387    /// [`PhysicsSystem::collider_of`] gives for an entity.
388    #[must_use]
389    pub fn cast_ray_filtered(
390        &self,
391        ray: &Ray,
392        filter: QueryFilter,
393        scratch: &mut QueryScratch,
394    ) -> Option<(Entity, ShapeHit)> {
395        let (id, hit) = self.queries.cast_ray_filtered(ray, filter, scratch)?;
396        Some((self.entity_for(id)?, hit))
397    }
398
399    /// [`PhysicsSystem::sweep_sphere`] under a shared borrow, working in
400    /// `scratch` instead of the system's own buffers.
401    ///
402    /// Every collider in the world is a candidate, including the sweeper's own
403    /// if it has one — there is no entity-level exclusion here, because
404    /// [`PhysicsSystem::sweep_body`] needs the body's velocity and transform to
405    /// build its segment and this view does not carry them.
406    #[must_use]
407    pub fn sweep_sphere(
408        &self,
409        segment: &Segment,
410        radius: f64,
411        scratch: &mut QueryScratch,
412    ) -> Option<(Entity, ShapeHit)> {
413        self.sweep_sphere_filtered(segment, radius, QueryFilter::ALL, scratch)
414    }
415
416    /// [`sweep_sphere`](Self::sweep_sphere) over only the colliders `filter`
417    /// admits — see [`QueryFilter`]. This is how a sweeper whose own entity
418    /// has a collider leaves itself out here: exclude
419    /// [`PhysicsSystem::collider_of`] it.
420    #[must_use]
421    pub fn sweep_sphere_filtered(
422        &self,
423        segment: &Segment,
424        radius: f64,
425        filter: QueryFilter,
426        scratch: &mut QueryScratch,
427    ) -> Option<(Entity, ShapeHit)> {
428        let (id, hit) = self
429            .queries
430            .sweep_sphere_filtered(segment, radius, filter, scratch)?;
431        Some((self.entity_for(id)?, hit))
432    }
433
434    /// The entity a collider id belongs to, or `None` if nothing is mapped to
435    /// its slot. The view's copy of [`PhysicsSystem`]'s own reverse-map
436    /// lookup — both call one free function, so the two borrow shapes cannot
437    /// disagree about which entity a slot is.
438    fn entity_for(&self, id: ColliderId) -> Option<Entity> {
439        entity_for_in(self.collider_to_entity, id)
440    }
441}
442
443/// The entity mapped to a collider id's slot, or `None` if there is none.
444///
445/// Both [`PhysicsSystem`] and [`EntityOverlapQueries`] resolve hits through
446/// this, one holding the reverse map and the other borrowing it.
447fn entity_for_in(collider_to_entity: &[Option<Entity>], id: ColliderId) -> Option<Entity> {
448    collider_to_entity.get(id.index() as usize).and_then(|e| *e)
449}
450
451impl PhysicsSystem {
452    /// The system's name, and so the key its replicated transforms travel
453    /// under: a client finds them by this name's replicated id.
454    pub const NAME: &'static str = "physics";
455
456    /// Create an empty physics system.
457    ///
458    /// Integration is [`SemiImplicitEuler`]; see [`PhysicsSystem::step`].
459    #[must_use]
460    pub fn new() -> Self {
461        Self {
462            world: PhysicsWorld::new(),
463            records: Pool::new(),
464            entity_to_body: HashMap::new(),
465            statics: StaticSet::default(),
466            awake: AwakeSet::default(),
467            islands: Islands::default(),
468            collider_count: 0,
469            collider_to_entity: Vec::new(),
470            force_providers: Vec::new(),
471            scratch: QueryScratch::new(),
472            contacts: None,
473        }
474    }
475
476    /// Create an empty physics system whose bodies collide: see
477    /// [`crate::contact`].
478    ///
479    /// Every collider that is not a trigger takes part, and
480    /// [`step`](Self::step) becomes a whole tick of
481    /// [`ContactSettings::substeps`] solver substeps rather than one
482    /// integration.
483    #[must_use]
484    pub fn with_contacts(settings: ContactSettings) -> Self {
485        Self {
486            contacts: Some(Box::new(ContactPipeline::new(settings))),
487            ..Self::new()
488        }
489    }
490
491    /// The contact settings, or `None` in a system without contacts.
492    #[must_use]
493    pub fn contact_settings(&self) -> Option<&ContactSettings> {
494        self.contacts.as_ref().map(|pipeline| &pipeline.settings)
495    }
496
497    /// The contact settings to change, or `None` in a system without contacts.
498    /// A change takes effect on the next [`step`](Self::step).
499    pub fn contact_settings_mut(&mut self) -> Option<&mut ContactSettings> {
500        self.contacts
501            .as_mut()
502            .map(|pipeline| &mut pipeline.settings)
503    }
504
505    /// Add a static plane: the half-space `normal · x ≤ offset` is solid to
506    /// every body with contacts.
507    ///
508    /// A plane is solver geometry only. It has no entity and no collider in
509    /// [`world`](Self::world), so a ray, a sweep or an overlap query passes
510    /// straight through it.
511    ///
512    /// # Panics
513    ///
514    /// Panics if this system has no contacts, or if `normal` is not of unit
515    /// length.
516    pub fn add_plane(&mut self, normal: DVec3, offset: f64, material: SurfaceMaterial) -> PlaneId {
517        assert!(
518            (normal.length_squared() - 1.0).abs() < 1e-9,
519            "a plane's normal has unit length: {normal:?}"
520        );
521        self.contacts
522            .as_mut()
523            .expect("planes are contact geometry: build the system with_contacts")
524            .add_plane(normal, offset, material)
525    }
526
527    /// What the last [`step`](Self::step) of the contact pipeline did, or
528    /// every counter zero in a system without contacts.
529    #[must_use]
530    pub fn contact_counters(&self) -> ContactCounters {
531        self.contacts
532            .as_ref()
533            .map_or_else(ContactCounters::default, |pipeline| pipeline.counters)
534    }
535
536    /// The [`KineticContact`]s the last [`step`](Self::step) raised, in the
537    /// order its contacts were solved.
538    #[must_use]
539    pub fn kinetic_contacts(&self) -> &[KineticContact] {
540        self.contacts
541            .as_ref()
542            .map_or(&[], |pipeline| pipeline.kinetic.as_slice())
543    }
544
545    /// Every contact, touching or not, as the last [`step`](Self::step) left
546    /// it, in the pool's order.
547    #[must_use]
548    pub fn contacts(&self) -> Vec<ContactReport> {
549        self.contacts
550            .as_ref()
551            .map_or_else(Vec::new, |pipeline| pipeline.reports(&self.records))
552    }
553
554    /// Number of entities with colliders registered.
555    #[must_use]
556    pub fn collider_count(&self) -> usize {
557        self.collider_count
558    }
559
560    /// Number of entities with rigid bodies registered, sleeping ones
561    /// included.
562    #[must_use]
563    pub fn body_count(&self) -> usize {
564        self.awake.bodies.len() + self.islands.sleeping_bodies()
565    }
566
567    /// Whether `entity`'s body sleeps: its island has been still long enough
568    /// that nothing steps it until something wakes it — see
569    /// [`crate::contact`]. `false` for an entity with no body, and always in a
570    /// system without contacts.
571    #[must_use]
572    pub fn is_sleeping(&self, entity: Entity) -> bool {
573        self.record(entity)
574            .is_some_and(|record| record.set == BodySet::Sleeping)
575    }
576
577    /// Puts `entity`'s island to sleep now, without stepping: its bodies stop
578    /// where they are, with their velocities zeroed and their forces cleared,
579    /// exactly as an island that fell asleep on its own does. Returns whether
580    /// the entity's body sleeps afterwards.
581    ///
582    /// This is for restoring a snapshot taken while a body slept: stepping it
583    /// awake instead would re-settle it for [`ContactSettings::time_to_sleep`]
584    /// and leave it a hair from where it was saved. Register the body first
585    /// ([`set_body`](Self::set_body), [`set_transform`](Self::set_transform),
586    /// [`set_collider`](Self::set_collider)), then call this. A body registered
587    /// since the last step is an island of its own, so each restored body
588    /// sleeps alone; one already linked to others by touching contacts takes
589    /// its whole island with it, as sleep never splits an island.
590    ///
591    /// It wakes by every rule a sleeping island wakes by — a contact from an
592    /// awake body, [`set_transform`](Self::set_transform),
593    /// [`body_mut`](Self::body_mut), a force. What a snapshot does not restore
594    /// is the contacts' warm-start impulses: they are rebuilt cold when it
595    /// wakes.
596    ///
597    /// `false`, and nothing changes, for an entity with no dynamic body, in a
598    /// system without contacts, or with [`ContactSettings::sleep`] off.
599    pub fn put_to_sleep(&mut self, entity: Entity) -> bool {
600        let sleeps = self
601            .contacts
602            .as_ref()
603            .is_some_and(|pipeline| pipeline.settings.sleep);
604        let Some(&id) = self.entity_to_body.get(&entity) else {
605            return false;
606        };
607        if !sleeps {
608            return false;
609        }
610        self.islands.reconcile(&mut self.records, &self.awake);
611        let Some(record) = self.records.get(id) else {
612            return false;
613        };
614        if record.set == BodySet::Awake
615            && let Some(island) = record.island
616        {
617            self.islands
618                .sleep(&mut self.records, &mut self.awake, island);
619        }
620        let asleep = self.is_sleeping(entity);
621        if asleep && let Some(pipeline) = self.contacts.as_mut() {
622            // Every body the island took to sleep was put there by hand, not
623            // only this one: each finds its surroundings again on the next
624            // step, and none of those pairs may wake it.
625            let island = self.records.get(id).and_then(|record| record.island);
626            match island.map(|island| self.islands.members(island)) {
627                Some(members) if !members.is_empty() => {
628                    for &member in members {
629                        pipeline.body_restored_asleep(member);
630                    }
631                }
632                _ => pipeline.body_restored_asleep(id),
633            }
634        }
635        asleep
636    }
637
638    // ── Dynamics setup ───────────────────────────────────────────────────
639
640    /// Register a rigid body for `entity`.
641    ///
642    /// Replaces any existing body. The entity will participate in the
643    /// integration loop, from the transform it already has or from
644    /// [`Transform::IDENTITY`] if it has none. A sleeping body's island wakes.
645    ///
646    /// # Panics
647    ///
648    /// Panics if `body` is dynamic and `entity`'s collider is a
649    /// [`ColliderComponent::Mesh`]: a mesh is for static and kinematic bodies.
650    pub fn set_body(&mut self, entity: Entity, body: RigidBody) {
651        let id = self.record_for(entity, Transform::IDENTITY);
652        self.wake(id);
653        let record = self.records.get(id).expect("a live record");
654        assert!(
655            !body.is_dynamic()
656                || !matches!(record.collider, Some((_, ColliderComponent::Mesh { .. }))),
657            "a triangle mesh is for static and kinematic bodies, not dynamic ones"
658        );
659        let index = record.index;
660        match record.set {
661            BodySet::Awake => self.awake.bodies[index] = body,
662            BodySet::Sleeping => unreachable!("woken above"),
663            BodySet::Static => {
664                let (transform, moved) = self.statics.swap_remove(index);
665                self.reindex_to(moved, index);
666                let awake_index = self.awake.push(id, transform, body);
667                let record = self.records.get_mut(id).expect("a live record");
668                record.set = BodySet::Awake;
669                record.index = awake_index;
670                if let Some(pipeline) = self.contacts.as_mut() {
671                    for &proxy in &record.proxies {
672                        pipeline.body_changed_set(proxy, BodySet::Awake);
673                    }
674                }
675            }
676        }
677    }
678
679    /// Set the world-space transform for `entity`.
680    ///
681    /// If the entity has a collider, it is repositioned immediately. A
682    /// teleport wakes the entity's island and every sleeping island touching
683    /// it where it was; one that lands a static body on a sleeping one wakes
684    /// that too, on the next step.
685    pub fn set_transform(&mut self, entity: Entity, transform: Transform) {
686        let id = self.record_for(entity, transform);
687        self.disturb(id);
688        *self.transform_slot(id) = transform;
689        self.sync_collider(id);
690        if let Some(pipeline) = self.contacts.as_mut() {
691            pipeline.body_placed(
692                id,
693                Bodies {
694                    records: &self.records,
695                    statics: &self.statics,
696                    awake: &self.awake,
697                    islands: &self.islands,
698                },
699            );
700        }
701    }
702
703    /// Get a reference to an entity's rigid body. Reading a sleeping body
704    /// does not wake it.
705    #[must_use]
706    pub fn body(&self, entity: Entity) -> Option<&RigidBody> {
707        let record = self.record(entity)?;
708        match record.set {
709            BodySet::Awake => Some(&self.awake.bodies[record.index]),
710            BodySet::Sleeping => Some(self.islands.body(record.island, record.index)),
711            BodySet::Static => None,
712        }
713    }
714
715    /// Get a mutable reference to an entity's rigid body, for a game that
716    /// **chooses** a velocity rather than having one integrated onto it.
717    ///
718    /// [`set_body`](Self::set_body) is the wrong tool for that: it replaces
719    /// the whole body to change one `DVec3`, and a crowd sample does it once
720    /// per agent per tick. [`apply_force`](Self::apply_force) is not the tool
721    /// either — a kinematic body has zero inverse mass, so a force on it is a
722    /// no-op by construction, and kinematic is exactly what a steered agent is.
723    ///
724    /// It hands back the body and nothing else, so it cannot move a collider:
725    /// position lives in the transform, and changing that still goes through
726    /// [`set_transform`](Self::set_transform), which repositions the broadphase.
727    ///
728    /// A sleeping body's island wakes: whatever is written — a velocity, a
729    /// force — must be stepped. Read with [`body`](Self::body) to leave it
730    /// asleep.
731    #[must_use]
732    pub fn body_mut(&mut self, entity: Entity) -> Option<&mut RigidBody> {
733        let &id = self.entity_to_body.get(&entity)?;
734        self.wake(id);
735        let record = self.records.get(id)?;
736        match record.set {
737            BodySet::Awake => Some(&mut self.awake.bodies[record.index]),
738            BodySet::Static | BodySet::Sleeping => None,
739        }
740    }
741
742    /// Get a reference to an entity's transform.
743    #[must_use]
744    pub fn transform(&self, entity: Entity) -> Option<&Transform> {
745        let record = self.record(entity)?;
746        Some(match record.set {
747            BodySet::Awake => &self.awake.transforms[record.index],
748            BodySet::Static => &self.statics.transforms[record.index],
749            BodySet::Sleeping => self.islands.transform(record.island, record.index),
750        })
751    }
752
753    /// Set the surface material of `entity`'s body or collider. Returns `false`
754    /// if the entity is not registered.
755    ///
756    /// Every registered entity starts with [`SurfaceMaterial::DEFAULT`]. In a
757    /// system with contacts, each contact combines its two surfaces' materials
758    /// every tick, so a change takes effect on the next
759    /// [`step`](Self::step); see [`crate::material`]. It wakes the entity's
760    /// island and every sleeping island touching it, whose friction may no
761    /// longer hold them.
762    pub fn set_material(&mut self, entity: Entity, material: SurfaceMaterial) -> bool {
763        let Some(&id) = self.entity_to_body.get(&entity) else {
764            return false;
765        };
766        self.disturb(id);
767        match self.records.get_mut(id) {
768            Some(record) => {
769                record.material = material;
770                true
771            }
772            None => false,
773        }
774    }
775
776    /// The surface material of `entity`, if it is registered.
777    #[must_use]
778    pub fn material(&self, entity: Entity) -> Option<SurfaceMaterial> {
779        self.record(entity).map(|record| record.material)
780    }
781
782    /// Add a force provider. Providers are applied in order before
783    /// integration.
784    ///
785    /// Providers are **global**: every dynamic body gets every provider. That
786    /// is right for a field force — gravity, drag — and wrong for one that
787    /// belongs to a single entity, such as the thrust of the one ship among a
788    /// screenful of rocks. For that, use [`PhysicsSystem::apply_force`].
789    pub fn add_force_provider(&mut self, provider: Box<dyn ForceProvider>) {
790        self.force_providers.push(provider);
791    }
792
793    /// Add a world-space force to one entity's accumulator for the next
794    /// [`PhysicsSystem::step`]. Returns `false` if the entity has no body.
795    ///
796    /// This is how a game applies a force only some entities feel — the
797    /// player's thrust, a shove from a pickup — without a provider that would
798    /// apply it to everything. Like a provider's contribution it lasts one
799    /// substep: the integrator clears the accumulator, so a force held down
800    /// over time is re-applied each tick.
801    ///
802    /// [`crate::ThrustForce::world_force`] computes the thrust vector to pass
803    /// here from a body's orientation, so a per-entity thrust and a pipeline
804    /// one are the same model either way.
805    ///
806    /// A sleeping body's island wakes, as it does for
807    /// [`apply_torque`](Self::apply_torque): a force applied every tick keeps
808    /// a body awake.
809    pub fn apply_force(&mut self, entity: Entity, force: DVec3) -> bool {
810        match self.body_mut(entity) {
811            Some(body) => {
812                body.apply_force(force);
813                true
814            }
815            None => false,
816        }
817    }
818
819    /// Add a world-space torque to one entity's accumulator for the next
820    /// [`PhysicsSystem::step`], on [`apply_force`](Self::apply_force)'s terms.
821    /// Returns `false` if the entity has no body.
822    ///
823    /// A body with no rotational inertia accepts the torque and ignores it;
824    /// see [`RigidBody`].
825    pub fn apply_torque(&mut self, entity: Entity, torque: DVec3) -> bool {
826        match self.body_mut(entity) {
827            Some(body) => {
828                body.apply_torque(torque);
829                true
830            }
831            None => false,
832        }
833    }
834
835    // ── Collider management ────────────────────────────────────────────
836
837    /// Add or replace a collider for `entity`.
838    ///
839    /// The collider sits at `transform.position` plus the component's offset
840    /// turned by `transform.rotation`, as the contact pipeline places it.
841    /// The component is cached so [`PhysicsSystem::step`] can reposition the
842    /// collider after integration.
843    ///
844    /// The new collider has a new [`ColliderId`] — read it again with
845    /// [`collider_of`](Self::collider_of) — but keeps the entity's
846    /// [query layers](Self::set_collider_layers).
847    ///
848    /// Replacing a collider wakes on [`remove_collider`](Self::remove_collider)'s
849    /// terms.
850    ///
851    /// # Panics
852    ///
853    /// Panics if `component` is a [`ColliderComponent::Mesh`] and `entity`
854    /// has a dynamic body: a mesh is for static and kinematic bodies.
855    pub fn set_collider(
856        &mut self,
857        entity: Entity,
858        component: &ColliderComponent,
859        transform: &Transform,
860    ) {
861        let id = self.record_for(entity, *transform);
862        self.wake(id);
863        if matches!(component, ColliderComponent::Mesh { .. }) {
864            let record = self.records.get(id).expect("a live record");
865            assert!(
866                record.set != BodySet::Awake || !self.awake.bodies[record.index].is_dynamic(),
867                "a triangle mesh is for static and kinematic bodies, not dynamic ones"
868            );
869        }
870        *self.transform_slot(id) = *transform;
871        self.remove_collider(entity);
872
873        let collider = self.world.add_collider(component, transform);
874
875        let record = self.records.get_mut(id).expect("a live record");
876        record.collider = Some((collider, component.clone()));
877        self.world.set_layers(collider, record.layers);
878        if let Some(pipeline) = self.contacts.as_mut() {
879            let proxies = pipeline.create_body_proxies(
880                id,
881                Bodies {
882                    records: &self.records,
883                    statics: &self.statics,
884                    awake: &self.awake,
885                    islands: &self.islands,
886                },
887            );
888            self.records.get_mut(id).expect("a live record").proxies = proxies;
889        }
890        self.collider_count += 1;
891        let slot = collider.index() as usize;
892        if slot >= self.collider_to_entity.len() {
893            self.collider_to_entity.resize(slot + 1, None);
894        }
895        self.collider_to_entity[slot] = Some(entity);
896    }
897
898    /// Remove the collider and dynamics data for `entity`, its joints, and
899    /// the pairs [`ignore_contacts`](Self::ignore_contacts) kept it in.
900    ///
901    /// Its island wakes, and so does every sleeping island that touched it:
902    /// see [`remove_collider`](Self::remove_collider).
903    pub fn remove_entity(&mut self, entity: Entity) {
904        if let Some(&id) = self.entity_to_body.get(&entity) {
905            self.take_out_joints_of(id);
906        }
907        self.remove_collider(entity);
908        let Some(id) = self.entity_to_body.remove(&entity) else {
909            return;
910        };
911        if let Some(pipeline) = self.contacts.as_mut() {
912            pipeline.ignored.forget_body(id);
913        }
914        let Some(record) = self.records.remove(id) else {
915            return;
916        };
917        if let Some(island) = record.island {
918            self.islands.remove_member(island, id);
919        }
920        match record.set {
921            BodySet::Static => {
922                let (_, moved) = self.statics.swap_remove(record.index);
923                self.reindex_to(moved, record.index);
924            }
925            BodySet::Awake => {
926                let (_, _, moved) = self.awake.swap_remove(record.index);
927                self.reindex_to(moved, record.index);
928            }
929            BodySet::Sleeping => unreachable!("remove_collider woke it"),
930        }
931    }
932
933    /// Remove only the collider (no-op if none).
934    ///
935    /// A body losing its collider is a support taken away: its island wakes,
936    /// and so does every sleeping island touching it — a crate pulled out
937    /// from under a sleeping stack drops the stack.
938    pub fn remove_collider(&mut self, entity: Entity) {
939        let Some(&id) = self.entity_to_body.get(&entity) else {
940            return;
941        };
942        self.disturb(id);
943        let Some(record) = self.records.get_mut(id) else {
944            return;
945        };
946        let proxies = std::mem::take(&mut record.proxies);
947        if let Some(pipeline) = self.contacts.as_mut()
948            && !proxies.is_empty()
949        {
950            pipeline.destroy_proxies(&proxies);
951            // Its contacts with the rest of its island are gone, so the
952            // island may be in pieces.
953            if let Some(island) = record.island {
954                self.islands.mark_removed(island);
955            }
956        }
957        if let Some((collider, _)) = record.collider.take() {
958            self.world.remove(collider);
959            self.collider_count -= 1;
960            let slot = collider.index() as usize;
961            if slot < self.collider_to_entity.len() {
962                self.collider_to_entity[slot] = None;
963            }
964        }
965    }
966
967    /// Put `entity`'s query collider on the layers in `bits`: see
968    /// [`PhysicsWorld::set_layers`]. For a compound that is the one collider
969    /// holding all its parts.
970    /// Returns `false`, and changes nothing, if the entity has no collider.
971    ///
972    /// The layers belong to the entity rather than to one [`ColliderId`]:
973    /// they stay while [`step`](Self::step) moves the collider, and a
974    /// collider that [`set_collider`](Self::set_collider) replaces — or sets
975    /// again after [`remove_collider`](Self::remove_collider) — is put back
976    /// on them. Keeping them is the rule because a replacement is almost
977    /// always the same thing changing shape: an item re-shaped on pickup is
978    /// still an item, and a rule that reset it would put it back on every
979    /// layer, blocking every sweep, until the caller noticed. Only
980    /// [`remove_entity`](Self::remove_entity) forgets them.
981    ///
982    /// Layers filter queries only. The contact pipeline does not read them, so
983    /// a body on a layer a character's mask leaves out still collides with
984    /// other bodies.
985    pub fn set_collider_layers(&mut self, entity: Entity, bits: u32) -> bool {
986        let Some(&id) = self.entity_to_body.get(&entity) else {
987            return false;
988        };
989        let Some(record) = self.records.get_mut(id) else {
990            return false;
991        };
992        let Some((collider, _)) = record.collider else {
993            return false;
994        };
995        record.layers = bits;
996        self.world.set_layers(collider, bits)
997    }
998
999    /// The query collider [`set_collider`](Self::set_collider) made for
1000    /// `entity` — for a compound, the one collider holding all its parts — or
1001    /// `None` if the entity has no collider.
1002    ///
1003    /// The id changes when the collider is replaced, so read it again after a
1004    /// `set_collider` rather than keeping it: an old one resolves to nothing.
1005    /// It is what a [`QueryFilter`] excludes, and what
1006    /// [`world`](Self::world)'s own queries answer with.
1007    #[must_use]
1008    pub fn collider_of(&self, entity: Entity) -> Option<ColliderId> {
1009        self.record(entity)?
1010            .collider
1011            .as_ref()
1012            .map(|(collider, _)| *collider)
1013    }
1014
1015    /// The entity whose query collider `collider` is, or `None` if it is no
1016    /// entity's — a collider added straight to [`world_mut`](Self::world_mut),
1017    /// or an id that was removed or replaced since.
1018    ///
1019    /// The inverse of [`collider_of`](Self::collider_of), for turning a hit
1020    /// from [`world`](Self::world)'s own queries back into an entity.
1021    #[must_use]
1022    pub fn entity_of(&self, collider: ColliderId) -> Option<Entity> {
1023        let entity = self.entity_for(collider)?;
1024        // The reverse map is keyed by slot alone, so a stale id whose slot now
1025        // holds another entity's collider would name that entity: the
1026        // generation is checked against the entity's own collider.
1027        (self.collider_of(entity) == Some(collider)).then_some(entity)
1028    }
1029
1030    // ── Integration ────────────────────────────────────────────────────
1031
1032    /// Advance dynamics by `dt` seconds.
1033    ///
1034    /// **Without contacts** this is one substep: all force providers, then
1035    /// every body integrated — position, velocity, orientation and angular
1036    /// velocity — with [`SemiImplicitEuler`]. A caller wanting substeps calls
1037    /// this `n` times with `dt / n`.
1038    ///
1039    /// **With contacts** ([`with_contacts`](Self::with_contacts)) this is one
1040    /// tick: the force providers, then the contact broadphase and every
1041    /// manifold once, then [`ContactSettings::substeps`] solver substeps of
1042    /// `dt / substeps`, each integrating the bodies with the same
1043    /// [`SemiImplicitEuler`] split around the contact impulses. A force applied
1044    /// before the call is held for the whole tick. A body that touches nothing
1045    /// integrates exactly as the same number of contact-free substeps would,
1046    /// short of the speed and rotation caps and of the sweep that follows,
1047    /// which stops a fast body or a bullet where its path met something. An
1048    /// island that has been still
1049    /// long enough sleeps, and a sleeping body is not stepped at all. See
1050    /// [`crate::contact`].
1051    ///
1052    /// Either way, collider positions are synced to the new transforms, and
1053    /// bodies are visited in the awake set's own order, which is the order of
1054    /// the calls that registered them; see the [module docs](self).
1055    pub fn step(&mut self, dt: f64) {
1056        self.step_with_clock(dt, None);
1057    }
1058
1059    /// [`step`](Self::step), reading `clock` — seconds from any fixed origin —
1060    /// between the stages, so [`ContactCounters::stages`] reports what each
1061    /// took.
1062    ///
1063    /// The clock is the caller's because this crate reads none: a step's
1064    /// results must not depend on time, and `std::time::Instant` does not
1065    /// exist in a browser. A system without contacts has no stages and never
1066    /// reads it.
1067    pub fn step_timed(&mut self, dt: f64, clock: &mut dyn FnMut() -> f64) {
1068        self.step_with_clock(dt, Some(clock));
1069    }
1070
1071    fn step_with_clock(&mut self, dt: f64, clock: Option<&mut dyn FnMut() -> f64>) {
1072        if self.contacts.is_some() {
1073            self.step_contacts(dt, clock);
1074        } else {
1075            apply_forces(&mut self.awake, &self.force_providers, dt);
1076            let AwakeSet {
1077                transforms, bodies, ..
1078            } = &mut self.awake;
1079            for (body, transform) in bodies.iter_mut().zip(transforms.iter_mut()) {
1080                SemiImplicitEuler.step(body, transform, dt);
1081            }
1082            sync_colliders(&mut self.world, &self.records, &self.awake);
1083        }
1084    }
1085
1086    /// One tick of a system with contacts: see [`crate::contact`].
1087    ///
1088    /// The forces go on after the narrow phase rather than before it, so an
1089    /// island woken by a contact this tick feels them this tick; nothing
1090    /// before the solver reads a force.
1091    fn step_contacts(&mut self, dt: f64, mut clock: Option<&mut dyn FnMut() -> f64>) {
1092        let Some(pipeline) = self.contacts.as_mut() else {
1093            return;
1094        };
1095        let settings = pipeline.settings;
1096        let mut read = || clock.as_mut().map(|clock| clock());
1097        let start = read();
1098        if !settings.sleep && self.islands.sleeping_bodies() > 0 {
1099            self.islands.wake_all(&mut self.records, &mut self.awake);
1100        }
1101        self.islands.reconcile(&mut self.records, &self.awake);
1102        let reconciled = read();
1103
1104        let lent = Bodies {
1105            records: &self.records,
1106            statics: &self.statics,
1107            awake: &self.awake,
1108            islands: &self.islands,
1109        };
1110        pipeline.update_pairs(lent, dt);
1111        let paired = read();
1112        pipeline.collide(lent, dt);
1113        pipeline.joints.island_events(lent, &mut pipeline.events);
1114        let collided = read();
1115
1116        // Wake before linking, so every island a link merges is awake.
1117        let events = std::mem::take(&mut pipeline.events);
1118        for &id in &events.wake {
1119            self.islands
1120                .wake_body(&mut self.records, &mut self.awake, id);
1121        }
1122        for &(a, b) in &events.links {
1123            self.islands.link(&mut self.records, &mut self.awake, a, b);
1124        }
1125        for &id in &events.unlinks {
1126            if let Some(island) = self.records.get(id).and_then(|record| record.island) {
1127                self.islands.mark_removed(island);
1128            }
1129        }
1130        let linked = read();
1131
1132        apply_forces(&mut self.awake, &self.force_providers, dt);
1133        pipeline.remember_starts(&self.awake);
1134        pipeline.solve(
1135            &self.records,
1136            &self.statics,
1137            &mut self.awake,
1138            &self.islands,
1139            dt,
1140        );
1141        let solved = read();
1142        pipeline.sweep(
1143            &self.records,
1144            &self.statics,
1145            &mut self.awake,
1146            &self.islands,
1147            dt,
1148        );
1149        let swept = read();
1150
1151        // Colliders follow before anything sleeps, so a body put to sleep
1152        // this tick leaves its collider where it stopped.
1153        sync_colliders(&mut self.world, &self.records, &self.awake);
1154        pipeline.count_joints(Bodies {
1155            records: &self.records,
1156            statics: &self.statics,
1157            awake: &self.awake,
1158            islands: &self.islands,
1159        });
1160        let broken = std::mem::take(&mut pipeline.joints.broken);
1161        pipeline.counters.broken_joints = broken.len();
1162        for joint_break in &broken {
1163            self.take_out_joint(joint_break.joint);
1164        }
1165        let Some(pipeline) = self.contacts.as_mut() else {
1166            return;
1167        };
1168        pipeline.joints.broken = broken;
1169        let synced = read();
1170
1171        if settings.sleep {
1172            let records = &self.records;
1173            island::update_timers(
1174                &mut self.awake,
1175                settings.sleep_speed,
1176                settings.sleep_angular_speed,
1177                |id| {
1178                    records
1179                        .get(id)
1180                        .and_then(|record| record.collider.as_ref())
1181                        .map_or(0.0, |(_, collider)| collider.max_extent())
1182                },
1183                dt,
1184            );
1185            for &id in &events.stirred {
1186                if let Some(record) = self.records.get(id)
1187                    && record.set == BodySet::Awake
1188                {
1189                    self.awake.sleep_times[record.index] = 0.0;
1190                }
1191            }
1192            if let Some(island) =
1193                self.islands
1194                    .split_candidate(&self.records, &self.awake, settings.time_to_sleep)
1195            {
1196                let edges = pipeline.island_edges(&self.records, island);
1197                self.islands.split(&mut self.records, island, edges);
1198            }
1199            self.islands
1200                .sleep_ready(&mut self.records, &mut self.awake, settings.time_to_sleep);
1201        }
1202        let settled = read();
1203        pipeline.events = events;
1204
1205        let counters = &mut pipeline.counters;
1206        counters.bodies = self.awake.ids.len();
1207        counters.sleeping = self.islands.sleeping_bodies();
1208        counters.islands = self.islands.awake_islands();
1209        counters.sleeping_islands = self.islands.sleeping_islands();
1210        counters.stages = match (
1211            start, reconciled, paired, collided, linked, solved, swept, synced, settled,
1212        ) {
1213            (
1214                Some(start),
1215                Some(reconciled),
1216                Some(paired),
1217                Some(collided),
1218                Some(linked),
1219                Some(solved),
1220                Some(swept),
1221                Some(synced),
1222                Some(settled),
1223            ) => Some(StageTimes {
1224                broadphase: paired - reconciled,
1225                narrow_phase: collided - paired,
1226                solver: solved - linked,
1227                islands: (reconciled - start) + (linked - collided) + (settled - synced),
1228                continuous: swept - solved,
1229            }),
1230            _ => None,
1231        };
1232    }
1233
1234    // ── Queries ────────────────────────────────────────────────────────
1235
1236    /// Cast a ray, returning the closest hit entity and details.
1237    #[must_use]
1238    pub fn cast_ray(&mut self, ray: &Ray) -> Option<(Entity, ShapeHit)> {
1239        self.cast_ray_filtered(ray, QueryFilter::ALL)
1240    }
1241
1242    /// [`cast_ray`](Self::cast_ray) over only the colliders `filter` admits —
1243    /// see [`QueryFilter`] and [`set_collider_layers`](Self::set_collider_layers).
1244    #[must_use]
1245    pub fn cast_ray_filtered(
1246        &mut self,
1247        ray: &Ray,
1248        filter: QueryFilter,
1249    ) -> Option<(Entity, ShapeHit)> {
1250        // Lent to the view and put straight back, as
1251        // [`PhysicsSystem::overlap_sphere_into`] does and for the same reason.
1252        let mut scratch = std::mem::take(&mut self.scratch);
1253        let hit = self
1254            .overlap_queries()
1255            .cast_ray_filtered(ray, filter, &mut scratch);
1256        self.scratch = scratch;
1257        hit
1258    }
1259
1260    /// Sweep a sphere, returning the closest hit entity and details.
1261    ///
1262    /// Every collider in the world is a candidate. A caller sweeping a body
1263    /// along its own path wants [`sweep_body`](Self::sweep_body) instead, which
1264    /// builds the same segment and leaves that body out of the answer.
1265    #[must_use]
1266    pub fn sweep_sphere(&mut self, segment: &Segment, radius: f64) -> Option<(Entity, ShapeHit)> {
1267        self.sweep_sphere_filtered(segment, radius, QueryFilter::ALL)
1268    }
1269
1270    /// [`sweep_sphere`](Self::sweep_sphere) over only the colliders `filter`
1271    /// admits — see [`QueryFilter`].
1272    #[must_use]
1273    pub fn sweep_sphere_filtered(
1274        &mut self,
1275        segment: &Segment,
1276        radius: f64,
1277        filter: QueryFilter,
1278    ) -> Option<(Entity, ShapeHit)> {
1279        let mut scratch = std::mem::take(&mut self.scratch);
1280        let hit =
1281            self.overlap_queries()
1282                .sweep_sphere_filtered(segment, radius, filter, &mut scratch);
1283        self.scratch = scratch;
1284        hit
1285    }
1286
1287    /// Sweep the body at `entity` along the segment it covers in `dt`: from where
1288    /// it was (`position − velocity·dt`) to where it is (`position`), with the
1289    /// given `radius`. Returns the closest hit.
1290    ///
1291    /// This is the "never miss at any speed" half of CCD — a body moving faster
1292    /// than its own radius in one tick would tunnel through anything it crossed
1293    /// between steps, and the swept volume is what catches it.
1294    ///
1295    /// # The swept entity is left out of its own answer
1296    ///
1297    /// The segment ends where the body is, so the body's own collider sits on
1298    /// the end of it: swept against itself it is a hit at `t = 0`, closer than
1299    /// anything it was actually heading for. This excludes it — see
1300    /// [`PhysicsWorld::sweep_sphere_excluding`], which drops it in the narrow
1301    /// phase so the next-closest hit survives. An entity with a collider is
1302    /// therefore swept exactly like one without, and neither the caller nor
1303    /// this method has to lift a collider out of the world to ask.
1304    #[must_use]
1305    pub fn sweep_body(
1306        &mut self,
1307        entity: Entity,
1308        dt: f64,
1309        radius: f64,
1310    ) -> Option<(Entity, ShapeHit)> {
1311        self.sweep_body_filtered(entity, dt, radius, ALL_LAYERS)
1312    }
1313
1314    /// [`sweep_body`](Self::sweep_body) looking only at the colliders on a
1315    /// layer in `mask` — see [`set_collider_layers`](Self::set_collider_layers).
1316    ///
1317    /// A mask and not a whole [`QueryFilter`], because the exclusion is not the
1318    /// caller's to choose: it is always the swept body's own collider.
1319    #[must_use]
1320    pub fn sweep_body_filtered(
1321        &mut self,
1322        entity: Entity,
1323        dt: f64,
1324        radius: f64,
1325        mask: u32,
1326    ) -> Option<(Entity, ShapeHit)> {
1327        let body = self.body(entity).copied()?;
1328        let transform = self.transform(entity).copied()?;
1329        let segment = Segment {
1330            start: transform.position - body.velocity * dt,
1331            end: transform.position,
1332        };
1333        let filter = QueryFilter::excluding(self.collider_of(entity)).with_mask(mask);
1334        let (id, hit) = self.world.sweep_sphere_filtered(&segment, radius, filter)?;
1335        Some((self.entity_for(id)?, hit))
1336    }
1337
1338    /// Overlap query: every entity whose collider the sphere is inside, each
1339    /// with how deep, which way out and where ([`OverlapHit`]).
1340    ///
1341    /// # An overlap's hit is a push-out, not an impact
1342    ///
1343    /// This once answered `(Entity, ShapeHit)` with the hit filled in as
1344    /// `t: 0.0`, `normal: DVec3::Y` and `started_inside: true` whatever the
1345    /// geometry, and then bare entities, on the argument that an overlap has no
1346    /// impact time, point or single normal. The first half of that holds, and
1347    /// is why the hit is not a [`ShapeHit`]. The second does not: the shortest
1348    /// move that takes the sphere out of a shape is one direction and one
1349    /// depth, which is what Unity's `Physics.ComputePenetration` and PhysX's
1350    /// `PxGeometryQuery::computePenetration` answer, and the point it is
1351    /// pushed out from is one point. Of a compound, the deepest part answers.
1352    /// A collider the sphere only touches is not inside it and is not returned.
1353    ///
1354    /// A caller that wants only the entities maps the pairs, unless it is a
1355    /// crowd pass running one query per body per tick: that wants
1356    /// [`EntityOverlapQueries::overlap_sphere_entities_into`], which answers
1357    /// the same entities without building the hits.
1358    ///
1359    /// # The query is shape-aware, and `radius` is expanded by each collider
1360    ///
1361    /// The query sphere is tested against every collider's *shape*, so a sphere
1362    /// collider of radius `r_b` is returned iff its centre is within
1363    /// `radius + r_b` of `centre` (and a box or capsule by the extent of its own
1364    /// shape). A caller that wants "everything whose centre is within `radius`"
1365    /// has to subtract the largest collider radius itself. This is not a corner
1366    /// of the API — `apps/horde`'s separation query is only correct because it
1367    /// omits the neighbour's radius on purpose and lets this expansion supply
1368    /// it; the boundary is pinned by `world::tests`'
1369    /// `a_sphere_overlap_is_expanded_by_the_colliders_own_radius`.
1370    #[must_use]
1371    pub fn overlap_sphere(&mut self, centre: DVec3, radius: f64) -> Vec<(Entity, OverlapHit)> {
1372        let mut out = Vec::new();
1373        self.overlap_sphere_into(centre, radius, &mut out);
1374        out
1375    }
1376
1377    /// [`overlap_sphere`](Self::overlap_sphere) writing into a buffer the
1378    /// caller owns, for a game that queries once per body per tick.
1379    ///
1380    /// Same shape-aware semantics as [`overlap_sphere`](Self::overlap_sphere):
1381    /// a sphere collider of radius `r_b` is returned iff its centre is within
1382    /// `radius + r_b` of `centre`.
1383    ///
1384    /// `out` is cleared and then filled, so the buffer is hoisted out of the
1385    /// loop and reused. Nothing below this allocates either: the world's hits
1386    /// land in a scratch buffer of this system's, and the BVH's descent stack
1387    /// and candidate list are the world's own. A crowd of ten thousand
1388    /// therefore steers without a single allocation, where the owned form is
1389    /// three per agent per tick.
1390    pub fn overlap_sphere_into(
1391        &mut self,
1392        centre: DVec3,
1393        radius: f64,
1394        out: &mut Vec<(Entity, OverlapHit)>,
1395    ) {
1396        self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, out);
1397    }
1398
1399    /// [`overlap_sphere`](Self::overlap_sphere) naming only the entities whose
1400    /// collider `filter` admits — see [`QueryFilter`].
1401    #[must_use]
1402    pub fn overlap_sphere_filtered(
1403        &mut self,
1404        centre: DVec3,
1405        radius: f64,
1406        filter: QueryFilter,
1407    ) -> Vec<(Entity, OverlapHit)> {
1408        let mut out = Vec::new();
1409        self.overlap_sphere_filtered_into(centre, radius, filter, &mut out);
1410        out
1411    }
1412
1413    /// [`overlap_sphere_into`](Self::overlap_sphere_into) naming only the
1414    /// entities whose collider `filter` admits — see [`QueryFilter`].
1415    pub fn overlap_sphere_filtered_into(
1416        &mut self,
1417        centre: DVec3,
1418        radius: f64,
1419        filter: QueryFilter,
1420        out: &mut Vec<(Entity, OverlapHit)>,
1421    ) {
1422        // Lent to the view and put straight back — see
1423        // [`PhysicsWorld::overlap_sphere_into`], which does the same thing for
1424        // the same reason.
1425        let mut scratch = std::mem::take(&mut self.scratch);
1426        self.overlap_queries().overlap_sphere_filtered_into(
1427            centre,
1428            radius,
1429            filter,
1430            &mut scratch,
1431            out,
1432        );
1433        self.scratch = scratch;
1434    }
1435
1436    /// Builds the broadphase and hands back a shared view that can query it by
1437    /// entity.
1438    ///
1439    /// The system-level twin of [`PhysicsWorld::overlap_queries`], and the
1440    /// entry point a data-parallel pass over a crowd wants: it is what lets
1441    /// every chunk of a `crcbl_jobs` `par_for` run its own neighbourhood
1442    /// queries at the same time. See [`EntityOverlapQueries`].
1443    pub fn overlap_queries(&mut self) -> EntityOverlapQueries<'_> {
1444        // Split borrows: the view needs the reverse map shared and the world
1445        // exclusively, and they are different fields of this struct.
1446        let Self {
1447            world,
1448            collider_to_entity,
1449            ..
1450        } = self;
1451        EntityOverlapQueries {
1452            queries: world.overlap_queries(),
1453            collider_to_entity,
1454        }
1455    }
1456
1457    /// Overlap query: return all entities whose collider meets `aabb`, as
1458    /// [`PhysicsWorld::overlap_aabb`] answers it — a box, a compound or a mesh
1459    /// where its shape meets it, a sphere or a capsule wherever the world-axis
1460    /// box around it does.
1461    #[must_use]
1462    pub fn overlap_aabb(&mut self, aabb: &Aabb) -> Vec<Entity> {
1463        self.overlap_aabb_filtered(aabb, QueryFilter::ALL)
1464    }
1465
1466    /// [`overlap_aabb`](Self::overlap_aabb) naming only the entities whose
1467    /// collider `filter` admits — see [`QueryFilter`].
1468    #[must_use]
1469    pub fn overlap_aabb_filtered(&mut self, aabb: &Aabb, filter: QueryFilter) -> Vec<Entity> {
1470        let mut scratch = std::mem::take(&mut self.scratch);
1471        let mut out = Vec::new();
1472        self.overlap_queries()
1473            .overlap_aabb_filtered_into(aabb, filter, &mut scratch, &mut out);
1474        self.scratch = scratch;
1475        out
1476    }
1477
1478    /// Direct access to the underlying [`PhysicsWorld`] for advanced use.
1479    #[must_use]
1480    pub fn world(&self) -> &PhysicsWorld {
1481        &self.world
1482    }
1483
1484    /// Mutable access to the underlying [`PhysicsWorld`] for advanced use.
1485    pub fn world_mut(&mut self) -> &mut PhysicsWorld {
1486        &mut self.world
1487    }
1488
1489    // ── Internals ──────────────────────────────────────────────────────
1490
1491    /// The entity a collider id belongs to, or `None` if nothing is mapped to
1492    /// its slot.
1493    fn entity_for(&self, id: ColliderId) -> Option<Entity> {
1494        entity_for_in(&self.collider_to_entity, id)
1495    }
1496
1497    /// The record of `entity`, if it is registered.
1498    fn record(&self, entity: Entity) -> Option<&BodyRecord> {
1499        self.records.get(*self.entity_to_body.get(&entity)?)
1500    }
1501
1502    /// The id of `entity`'s record, registering it in the static set at
1503    /// `transform` first if it has none.
1504    fn record_for(&mut self, entity: Entity, transform: Transform) -> BodyId {
1505        if let Some(&id) = self.entity_to_body.get(&entity) {
1506            return id;
1507        }
1508        let id = self.records.insert(BodyRecord {
1509            entity,
1510            set: BodySet::Static,
1511            index: 0,
1512            collider: None,
1513            layers: ALL_LAYERS,
1514            material: SurfaceMaterial::DEFAULT,
1515            proxies: Vec::new(),
1516            island: None,
1517            substeps: 0,
1518            filter: CollisionFilter::DEFAULT,
1519        });
1520        let index = self.statics.push(id, transform);
1521        self.records.get_mut(id).expect("just inserted").index = index;
1522        self.entity_to_body.insert(entity, id);
1523        id
1524    }
1525
1526    /// The transform of the body `id` names, waking it first if it sleeps.
1527    fn transform_slot(&mut self, id: BodyId) -> &mut Transform {
1528        self.wake(id);
1529        let record = self.records.get(id).expect("a live record");
1530        match record.set {
1531            BodySet::Awake => &mut self.awake.transforms[record.index],
1532            BodySet::Static => &mut self.statics.transforms[record.index],
1533            BodySet::Sleeping => unreachable!("woken above"),
1534        }
1535    }
1536
1537    /// Wakes the island of the body `id` names, if it sleeps.
1538    fn wake(&mut self, id: BodyId) {
1539        self.islands
1540            .wake_body(&mut self.records, &mut self.awake, id);
1541    }
1542
1543    /// Wakes the island of the body `id` names and, while anything sleeps,
1544    /// every island touching it: what a change to a body that others may rest
1545    /// on — a teleport, a new material, a collider taken away — must do.
1546    ///
1547    /// Finding what touches a body is a walk over every contact, so it is
1548    /// skipped when nothing sleeps and there is nothing to wake.
1549    fn disturb(&mut self, id: BodyId) {
1550        self.wake(id);
1551        if self.islands.sleeping_bodies() == 0 {
1552            return;
1553        }
1554        let (Some(pipeline), Some(record)) = (self.contacts.as_ref(), self.records.get(id)) else {
1555            return;
1556        };
1557        if record.proxies.is_empty() {
1558            return;
1559        }
1560        let mut touching = Vec::new();
1561        pipeline.touching_bodies(&record.proxies, &mut touching);
1562        for other in touching {
1563            self.wake(other);
1564        }
1565    }
1566
1567    /// Point the record of a body a swap-remove `moved` into `index` at its
1568    /// new place. `None` is the removal that emptied the end of the set.
1569    fn reindex_to(&mut self, moved: Option<BodyId>, index: usize) {
1570        if let Some(record) = moved.and_then(|id| self.records.get_mut(id)) {
1571            record.index = index;
1572        }
1573    }
1574
1575    /// Reposition the collider of the body `id` names from its cached component
1576    /// and current transform. No-op if it has no collider.
1577    fn sync_collider(&mut self, id: BodyId) {
1578        let Some(record) = self.records.get(id) else {
1579            return;
1580        };
1581        let Some((collider, component)) = &record.collider else {
1582            return;
1583        };
1584        let transform = match record.set {
1585            BodySet::Awake => &self.awake.transforms[record.index],
1586            BodySet::Static => &self.statics.transforms[record.index],
1587            BodySet::Sleeping => self.islands.transform(record.island, record.index),
1588        };
1589        self.world.place_collider(*collider, component, transform);
1590    }
1591}
1592
1593/// Every force provider onto every awake body.
1594fn apply_forces(awake: &mut AwakeSet, providers: &[Box<dyn ForceProvider>], dt: f64) {
1595    let AwakeSet {
1596        transforms, bodies, ..
1597    } = awake;
1598    for (body, transform) in bodies.iter_mut().zip(transforms.iter()) {
1599        for provider in providers {
1600            provider.apply(body, transform, dt);
1601        }
1602    }
1603}
1604
1605/// Every awake body's collider moved to where its body is.
1606fn sync_colliders(world: &mut PhysicsWorld, records: &Pool<BodyRecord>, awake: &AwakeSet) {
1607    for (id, transform) in awake.ids.iter().zip(awake.transforms.iter()) {
1608        if let Some((collider, component)) = records.get(*id).and_then(|r| r.collider.as_ref()) {
1609            world.place_collider(*collider, component, transform);
1610        }
1611    }
1612}
1613
1614/// `value`'s bits with every zero and every `NaN` made one: `-0.0` hashes as
1615/// `+0.0` and any `NaN` as the canonical one, so two states that compare equal
1616/// hash equal — contact-solver decision 8.
1617pub(crate) fn canonical_bits(value: f64) -> u64 {
1618    if value == 0.0 {
1619        0
1620    } else if value.is_nan() {
1621        f64::NAN.to_bits()
1622    } else {
1623        value.to_bits()
1624    }
1625}
1626
1627impl Default for PhysicsSystem {
1628    fn default() -> Self {
1629        Self::new()
1630    }
1631}
1632
1633impl std::fmt::Debug for PhysicsSystem {
1634    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1635        f.debug_struct("PhysicsSystem")
1636            .field("collider_count", &self.collider_count)
1637            .field("body_count", &self.body_count())
1638            .field("force_provider_count", &self.force_providers.len())
1639            .finish()
1640    }
1641}
1642
1643// ---------------------------------------------------------------------------
1644// SystemTrait impl
1645// ---------------------------------------------------------------------------
1646
1647impl SystemTrait for PhysicsSystem {
1648    fn name(&self) -> &str {
1649        Self::NAME
1650    }
1651
1652    /// Nothing shared: a step works on the bodies, colliders and force
1653    /// providers this system owns.
1654    fn access(&self) -> Access {
1655        Access::none()
1656    }
1657
1658    fn tick(&mut self, dt: f64) {
1659        // One substep at the schedule's real tick period.  Assuming a rate
1660        // here instead would make simulated speed a function of the host's
1661        // tick rate.  Callers wanting sub-stepping call `step(dt / n)` n times
1662        // directly instead of relying on the schedule.
1663        self.step(dt);
1664    }
1665
1666    fn entity_count(&self) -> usize {
1667        self.collider_count
1668    }
1669
1670    fn sweep(&mut self, dead: &[Entity]) {
1671        for &entity in dead {
1672            self.remove_entity(entity);
1673        }
1674    }
1675
1676    /// Draws nothing: [`DebugCtx`] carries nothing to draw into, so the
1677    /// view is [`debug_lines`](Self::debug_lines), for a caller to draw.
1678    fn debug_draw(&mut self, _ctx: &DebugCtx) {}
1679
1680    /// Feed transform and rigid-body state into the determinism hash.
1681    ///
1682    /// Entities are visited in ascending `to_bits()` order rather than in the
1683    /// sets' order, which depends on the history of calls that built them, and
1684    /// every float goes in canonicalised — `-0.0` as `+0.0`, every `NaN` as one — so the hash
1685    /// is a function of the simulation state and nothing else.
1686    ///
1687    /// In a system with contacts each body's sleep goes in too — whether it
1688    /// sleeps, and if not how long it has been still — since two states that
1689    /// differ only there step differently.
1690    fn hash_state(&self, hasher: &mut dyn std::hash::Hasher) {
1691        let mut entities: Vec<(u64, &BodyRecord)> = self
1692            .records
1693            .iter()
1694            .map(|(_, record)| (record.entity.to_bits(), record))
1695            .collect();
1696        entities.sort_unstable_by_key(|(bits, _)| *bits);
1697
1698        for (bits, record) in entities {
1699            hasher.write(&bits.to_le_bytes());
1700            let (transform, body) = match record.set {
1701                BodySet::Awake => (
1702                    &self.awake.transforms[record.index],
1703                    Some(&self.awake.bodies[record.index]),
1704                ),
1705                BodySet::Sleeping => (
1706                    self.islands.transform(record.island, record.index),
1707                    Some(self.islands.body(record.island, record.index)),
1708                ),
1709                BodySet::Static => (&self.statics.transforms[record.index], None),
1710            };
1711
1712            hasher.write(&[1]);
1713            for value in [
1714                transform.position.x,
1715                transform.position.y,
1716                transform.position.z,
1717                transform.rotation.x,
1718                transform.rotation.y,
1719                transform.rotation.z,
1720                transform.rotation.w,
1721            ] {
1722                hasher.write(&canonical_bits(value).to_le_bytes());
1723            }
1724
1725            match body {
1726                Some(body) => {
1727                    hasher.write(&[1]);
1728                    for value in [
1729                        body.mass,
1730                        body.inverse_mass,
1731                        body.velocity.x,
1732                        body.velocity.y,
1733                        body.velocity.z,
1734                        body.force_accum.x,
1735                        body.force_accum.y,
1736                        body.force_accum.z,
1737                        body.angular_velocity.x,
1738                        body.angular_velocity.y,
1739                        body.angular_velocity.z,
1740                        body.torque_accum.x,
1741                        body.torque_accum.y,
1742                        body.torque_accum.z,
1743                    ]
1744                    .into_iter()
1745                    .chain(body.local_inertia.to_cols_array())
1746                    {
1747                        hasher.write(&canonical_bits(value).to_le_bytes());
1748                    }
1749                    // Only a bullet writes its flag, so a state with none
1750                    // hashes as it did before the flag existed.
1751                    if body.bullet {
1752                        hasher.write(&[3]);
1753                    }
1754                    // Only a body that asked for its own substeps writes
1755                    // them, likewise.
1756                    if record.substeps != 0 {
1757                        hasher.write(&[5]);
1758                        hasher.write(&record.substeps.to_le_bytes());
1759                    }
1760                    if self.contacts.is_some() {
1761                        match record.set {
1762                            BodySet::Awake => {
1763                                hasher.write(&[0]);
1764                                let still = self.awake.sleep_times[record.index];
1765                                hasher.write(&canonical_bits(still).to_le_bytes());
1766                            }
1767                            BodySet::Sleeping | BodySet::Static => hasher.write(&[1]),
1768                        }
1769                    }
1770                }
1771                None => hasher.write(&[0]),
1772            }
1773            // Only a body given a filter writes it, so a state with none
1774            // hashes as it did before filters.
1775            if record.filter != CollisionFilter::DEFAULT {
1776                hasher.write(&[7]);
1777                hasher.write(&record.filter.category.to_le_bytes());
1778                hasher.write(&record.filter.mask.to_le_bytes());
1779            }
1780        }
1781
1782        if let Some(pipeline) = &self.contacts {
1783            hasher.write(&[2]);
1784            pipeline.hash_state(&self.records, hasher);
1785        }
1786    }
1787
1788    fn contributes_to_hash(&self) -> bool {
1789        true
1790    }
1791
1792    fn replicate(&self, out: &mut Vec<u8>) -> bool {
1793        // Per-entity Transform in its wire form (`Transform::encode_wire`):
1794        // quantized, so the server's byte comparison sees a sub-quantum
1795        // change as no change at all. `hash_state` reads the unquantized
1796        // transforms, never these bytes. Entities are sorted by bits so the
1797        // wire encoding is deterministic across runs and platforms.
1798        let mut entries: Vec<(u64, &Transform)> = self
1799            .records
1800            .iter()
1801            .map(|(_, record)| {
1802                let transform = match record.set {
1803                    BodySet::Awake => &self.awake.transforms[record.index],
1804                    BodySet::Static => &self.statics.transforms[record.index],
1805                    BodySet::Sleeping => self.islands.transform(record.island, record.index),
1806                };
1807                (record.entity.to_bits(), transform)
1808            })
1809            .collect();
1810        entries.sort_unstable_by_key(|(bits, _)| *bits);
1811        let mut component = Vec::with_capacity(Transform::ENCODED_LEN);
1812        for (bits, transform) in &entries {
1813            component.clear();
1814            transform.encode_wire(&mut component);
1815            out.extend_from_slice(&bits.to_le_bytes());
1816            out.extend_from_slice(&(component.len() as u32).to_le_bytes());
1817            out.extend_from_slice(&component);
1818        }
1819        !entries.is_empty()
1820    }
1821
1822    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
1823        self
1824    }
1825}
1826
1827// ---------------------------------------------------------------------------
1828// Tests
1829// ---------------------------------------------------------------------------
1830
1831#[cfg(test)]
1832mod tests {
1833    use super::*;
1834    use crate::forces::GravityForce;
1835    use glam::DVec3;
1836
1837    fn test_entity(idx: u32) -> Entity {
1838        Entity::from_bits(((1u64) << 32) | idx as u64).expect("test entity")
1839    }
1840
1841    // ── Existing collider tests (preserved) ────────────────────────────
1842
1843    #[test]
1844    fn empty_system_has_no_colliders() {
1845        let phys = PhysicsSystem::new();
1846        assert_eq!(phys.collider_count(), 0);
1847    }
1848
1849    /// **The view names the entities that are actually within reach, and says
1850    /// the same thing to every thread asking at once.**
1851    ///
1852    /// Two claims, and the fixture serves both. The oracle is the entity
1853    /// positions themselves, not [`PhysicsSystem::overlap_sphere_into`] — that
1854    /// is the same code under a different borrow, so comparing them proves
1855    /// nothing about either. What the system layer adds over
1856    /// [`crate::world::OverlapQueries`] is the collider-slot-to-entity step, and
1857    /// a slot mapped to the wrong entity is what this catches.
1858    ///
1859    /// The concurrent half is the reason the API exists: several threads share
1860    /// one view and each brings its own [`crate::world::QueryScratch`], and
1861    /// every one of them must reach the answers the calling thread reached
1862    /// alone. It is a guard against a future regression rather than against
1863    /// today's code — the view holds only shared references, so there is
1864    /// nothing here for threads to race over, and putting the scratch back
1865    /// inside it is exactly the change that would make that false.
1866    #[test]
1867    fn the_view_names_the_right_entities_from_every_thread_at_once() {
1868        const RADIUS: f64 = 0.45;
1869        const REACH: f64 = 1.5;
1870
1871        let mut phys = PhysicsSystem::new();
1872        let mut placed: Vec<(Entity, DVec3)> = Vec::new();
1873        for idx in 0..40u32 {
1874            let entity = test_entity(idx);
1875            let position = DVec3::new(f64::from(idx % 7), f64::from(idx / 7), 0.0);
1876            let transform = Transform::from_position(position);
1877            phys.set_collider(
1878                entity,
1879                &ColliderComponent::Sphere {
1880                    offset: DVec3::ZERO,
1881                    radius: RADIUS,
1882                    is_trigger: false,
1883                },
1884                &transform,
1885            );
1886            phys.set_transform(entity, transform);
1887            placed.push((entity, position));
1888        }
1889
1890        let centres: Vec<DVec3> = placed.iter().map(|(_, p)| *p).collect();
1891        // Two spheres overlap when their centres are within the sum of their
1892        // radii, which is the whole of the test the query is meant to be doing.
1893        let oracle = |centre: DVec3| {
1894            let mut hits: Vec<Entity> = placed
1895                .iter()
1896                .filter(|(_, p)| p.distance(centre) <= REACH + RADIUS)
1897                .map(|(e, _)| *e)
1898                .collect();
1899            hits.sort_unstable_by_key(|e| e.to_bits());
1900            hits
1901        };
1902        let expected: Vec<Vec<Entity>> = centres.iter().map(|c| oracle(*c)).collect();
1903        let biggest = expected.iter().map(Vec::len).max().unwrap_or(0);
1904        assert!(
1905            biggest > 4,
1906            "the widest query in the fixture reaches {biggest} entities, which \
1907             is not a neighbourhood",
1908        );
1909
1910        let ask = |queries: &EntityOverlapQueries<'_>| {
1911            let mut scratch = crate::world::QueryScratch::new();
1912            let mut out = Vec::new();
1913            centres
1914                .iter()
1915                .map(|centre| {
1916                    queries.overlap_sphere_into(*centre, REACH, &mut scratch, &mut out);
1917                    let mut hits: Vec<Entity> = out.iter().map(|&(entity, _)| entity).collect();
1918                    hits.sort_unstable_by_key(|entity| entity.to_bits());
1919                    hits
1920                })
1921                .collect::<Vec<_>>()
1922        };
1923
1924        let queries = phys.overlap_queries();
1925        assert_eq!(ask(&queries), expected, "the calling thread's own answers");
1926
1927        std::thread::scope(|scope| {
1928            let handles: Vec<_> = (0..4)
1929                .map(|_| scope.spawn(|| ask(&queries)))
1930                .collect::<Vec<_>>();
1931            for handle in handles {
1932                assert_eq!(
1933                    handle.join().expect("a query thread panicked"),
1934                    expected,
1935                    "a thread sharing the view disagreed with the scan",
1936                );
1937            }
1938        });
1939    }
1940
1941    /// Every probe's answers from one borrow shape or the other, so a whole
1942    /// run compares in a single `assert_eq!`.
1943    #[derive(Debug, PartialEq)]
1944    struct EntityProbeAnswers {
1945        rays: Vec<Option<(Entity, ShapeHit)>>,
1946        sweeps: Vec<Option<(Entity, ShapeHit)>>,
1947        aabbs: Vec<Vec<Entity>>,
1948    }
1949
1950    /// **The view names the right entity for a cast, a sweep and a box query,
1951    /// and says the same thing to every thread asking at once.**
1952    ///
1953    /// The geometry is already pinned a layer down, by
1954    /// `crate::world::tests::the_shared_view_casts_sweeps_and_boxes_like_a_scan_would`,
1955    /// which holds the traversal to a brute-force scan. What this layer adds is
1956    /// the collider-slot-to-entity step, so the oracle here is the entity
1957    /// *positions*: every probe is aimed so that which entity it must name
1958    /// follows from where the entities were placed, with no shape arithmetic in
1959    /// the oracle at all. A slot mapped to the wrong entity is what that
1960    /// catches, and it is why the expected answers are all different entities.
1961    ///
1962    /// The concurrent half is the reason the shared form exists — see
1963    /// [`the_view_names_the_right_entities_from_every_thread_at_once`], which
1964    /// makes the same argument for the sphere overlap.
1965    #[test]
1966    fn the_view_casts_sweeps_and_boxes_for_the_right_entities_from_every_thread() {
1967        const RADIUS: f64 = 0.45;
1968        // Rows are one unit apart and the colliders are narrower than half of
1969        // that, so a probe aimed down the middle of a row reaches that row and
1970        // nothing else, and one aimed between two rows reaches neither.
1971        const ROWS: u32 = 5;
1972        const COLUMNS: u32 = 7;
1973        // Narrow enough that the swept volume between two rows still reaches
1974        // neither: `RADIUS + SWEEP_RADIUS` has to stay under half a row.
1975        const SWEEP_RADIUS: f64 = 0.04;
1976
1977        let mut phys = PhysicsSystem::new();
1978        let mut placed: Vec<(Entity, DVec3)> = Vec::new();
1979        for idx in 0..ROWS * COLUMNS {
1980            let entity = test_entity(idx);
1981            let position = DVec3::new(f64::from(idx % COLUMNS), f64::from(idx / COLUMNS), 0.0);
1982            let transform = Transform::from_position(position);
1983            phys.set_collider(
1984                entity,
1985                &ColliderComponent::Sphere {
1986                    offset: DVec3::ZERO,
1987                    radius: RADIUS,
1988                    is_trigger: false,
1989                },
1990                &transform,
1991            );
1992            phys.set_transform(entity, transform);
1993            placed.push((entity, position));
1994        }
1995
1996        // The entity nearest the -X end of a row, which is what a cast or a
1997        // sweep coming from there must name.
1998        let first_in_row = |row: f64| {
1999            placed
2000                .iter()
2001                .filter(|(_, p)| p.y == row)
2002                .min_by(|(_, a), (_, b)| a.x.total_cmp(&b.x))
2003                .map(|(entity, _)| *entity)
2004        };
2005
2006        let rays: Vec<Ray> = (0..ROWS)
2007            .map(|row| Ray::new(DVec3::new(-10.0, f64::from(row), 0.0), DVec3::X))
2008            // Between two rows, so it reaches neither.
2009            .chain(std::iter::once(Ray::new(
2010                DVec3::new(-10.0, 1.5, 0.0),
2011                DVec3::X,
2012            )))
2013            .collect();
2014        let expected_rays: Vec<Option<Entity>> = (0..ROWS)
2015            .map(|row| first_in_row(f64::from(row)))
2016            .chain(std::iter::once(None))
2017            .collect();
2018
2019        let sweeps: Vec<(Segment, f64)> = (0..ROWS)
2020            .map(|row| {
2021                (
2022                    Segment::new(
2023                        DVec3::new(-10.0, f64::from(row), 0.0),
2024                        DVec3::new(10.0, f64::from(row), 0.0),
2025                    ),
2026                    SWEEP_RADIUS,
2027                )
2028            })
2029            .chain(std::iter::once((
2030                Segment::new(DVec3::new(-10.0, 1.5, 0.0), DVec3::new(10.0, 1.5, 0.0)),
2031                SWEEP_RADIUS,
2032            )))
2033            .collect();
2034        let expected_sweeps = expected_rays.clone();
2035
2036        let aabbs = [
2037            Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(0.1)),
2038            Aabb::from_centre_half(DVec3::new(3.0, 2.0, 0.0), DVec3::splat(1.0)),
2039            Aabb::from_centre_half(DVec3::new(50.0, 50.0, 0.0), DVec3::splat(1.0)),
2040        ];
2041        // Two AABBs meet when they overlap on every axis, and a sphere's is its
2042        // centre grown by its radius — the whole of the test this query does.
2043        let expected_aabbs: Vec<Vec<Entity>> = aabbs
2044            .iter()
2045            .map(|aabb| {
2046                let mut hits: Vec<Entity> = placed
2047                    .iter()
2048                    .filter(|(_, p)| {
2049                        Aabb::from_centre_half(*p, DVec3::splat(RADIUS)).intersects(aabb)
2050                    })
2051                    .map(|(entity, _)| *entity)
2052                    .collect();
2053                hits.sort_unstable_by_key(|entity| entity.to_bits());
2054                hits
2055            })
2056            .collect();
2057
2058        // The oracle has to be able to tell a mix-up from a match: every row's
2059        // answer is a different entity, and the box probes are neither all
2060        // empty nor all the same.
2061        let mut named: Vec<Entity> = expected_rays.iter().flatten().copied().collect();
2062        assert_eq!(named.len(), ROWS as usize, "every row has a nearest entity");
2063        named.sort_unstable_by_key(|entity| entity.to_bits());
2064        named.dedup();
2065        assert_eq!(
2066            named.len(),
2067            ROWS as usize,
2068            "two rows expect the same entity, so a slot-to-entity mix-up could \\
2069             pass this",
2070        );
2071        let widest = expected_aabbs.iter().map(Vec::len).max().unwrap_or(0);
2072        assert!(
2073            widest > 4 && expected_aabbs.iter().any(Vec::is_empty),
2074            "the box probes reach at most {widest} entities and never nothing, \\
2075             so one of the two cases never runs",
2076        );
2077
2078        let exclusive = EntityProbeAnswers {
2079            rays: rays.iter().map(|ray| phys.cast_ray(ray)).collect(),
2080            sweeps: sweeps
2081                .iter()
2082                .map(|(segment, radius)| phys.sweep_sphere(segment, *radius))
2083                .collect(),
2084            aabbs: aabbs
2085                .iter()
2086                .map(|aabb| {
2087                    let mut hits = phys.overlap_aabb(aabb);
2088                    hits.sort_unstable_by_key(|entity| entity.to_bits());
2089                    hits
2090                })
2091                .collect(),
2092        };
2093
2094        assert_eq!(
2095            exclusive
2096                .rays
2097                .iter()
2098                .map(|hit| hit.map(|(entity, _)| entity))
2099                .collect::<Vec<_>>(),
2100            expected_rays,
2101            "the entities the casts named",
2102        );
2103        assert_eq!(
2104            exclusive
2105                .sweeps
2106                .iter()
2107                .map(|hit| hit.map(|(entity, _)| entity))
2108                .collect::<Vec<_>>(),
2109            expected_sweeps,
2110            "the entities the sweeps named",
2111        );
2112        assert_eq!(exclusive.aabbs, expected_aabbs, "the entities in the boxes");
2113
2114        // One scratch and one output buffer for the whole run, as a `par_for`
2115        // chunk holds them: a query that forgot to clear its output is visible
2116        // here and would not be if every probe got a fresh buffer.
2117        let ask = |queries: &EntityOverlapQueries<'_>| {
2118            let mut scratch = crate::world::QueryScratch::new();
2119            let mut found = Vec::new();
2120            EntityProbeAnswers {
2121                rays: rays
2122                    .iter()
2123                    .map(|ray| queries.cast_ray(ray, &mut scratch))
2124                    .collect(),
2125                sweeps: sweeps
2126                    .iter()
2127                    .map(|(segment, radius)| queries.sweep_sphere(segment, *radius, &mut scratch))
2128                    .collect(),
2129                aabbs: aabbs
2130                    .iter()
2131                    .map(|aabb| {
2132                        queries.overlap_aabb_into(aabb, &mut scratch, &mut found);
2133                        let mut hits = found.clone();
2134                        hits.sort_unstable_by_key(|entity| entity.to_bits());
2135                        hits
2136                    })
2137                    .collect(),
2138            }
2139        };
2140
2141        let queries = phys.overlap_queries();
2142        assert_eq!(ask(&queries), exclusive, "the calling thread's own answers");
2143
2144        std::thread::scope(|scope| {
2145            let handles: Vec<_> = (0..4).map(|_| scope.spawn(|| ask(&queries))).collect();
2146            for handle in handles {
2147                assert_eq!(
2148                    handle.join().expect("a query thread panicked"),
2149                    exclusive,
2150                    "a thread sharing the view disagreed with the placements",
2151                );
2152            }
2153        });
2154    }
2155
2156    /// Split a replicated blob into `(entity bits, component bytes)`.
2157    fn replicated_entries(out: &[u8]) -> Vec<(u64, Vec<u8>)> {
2158        let mut cursor = 0usize;
2159        let mut entries = Vec::new();
2160        while cursor < out.len() {
2161            let bits = u64::from_le_bytes(out[cursor..cursor + 8].try_into().unwrap());
2162            cursor += 8;
2163            let len = u32::from_le_bytes(out[cursor..cursor + 4].try_into().unwrap()) as usize;
2164            cursor += 4;
2165            entries.push((bits, out[cursor..cursor + len].to_vec()));
2166            cursor += len;
2167        }
2168        entries
2169    }
2170
2171    /// What `phys` replicates.
2172    fn replicated(phys: &PhysicsSystem) -> Vec<u8> {
2173        let mut out = Vec::new();
2174        SystemTrait::replicate(phys, &mut out);
2175        out
2176    }
2177
2178    #[test]
2179    fn replicate_encodes_sorted_transform_blobs() {
2180        let mut phys = PhysicsSystem::new();
2181        let e1 = test_entity(9);
2182        let e2 = test_entity(2);
2183        // Insert out of order — the encoding must still come out sorted.
2184        phys.set_transform(e1, Transform::from_position(DVec3::new(1.0, 2.0, 3.0)));
2185        phys.set_transform(
2186            e2,
2187            Transform::new(
2188                DVec3::new(-4.0, 0.5, 8.0),
2189                glam::DQuat::from_xyzw(0.0, 0.0, 0.0, 1.0),
2190            ),
2191        );
2192
2193        let mut out = Vec::new();
2194        assert!(SystemTrait::replicate(&phys, &mut out));
2195
2196        let entity_len = 8 + 4 + Transform::QUANTIZED_LEN;
2197        assert_eq!(
2198            out.len(),
2199            2 * entity_len,
2200            "both inside the range: quantized"
2201        );
2202
2203        let decoded: Vec<_> = replicated_entries(&out)
2204            .into_iter()
2205            .map(|(bits, data)| (bits, Transform::decode_wire(&data).unwrap()))
2206            .collect();
2207        assert_eq!(decoded[0].0, e2.to_bits(), "sorted by entity bits");
2208        assert_eq!(decoded[1].0, e1.to_bits());
2209        // Both positions are on the quantization grid, so they are exact.
2210        assert_eq!(decoded[0].1.position, DVec3::new(-4.0, 0.5, 8.0));
2211        assert_eq!(decoded[1].1.position, DVec3::new(1.0, 2.0, 3.0));
2212
2213        // An empty system writes nothing and reports as non-replicated.
2214        let empty = PhysicsSystem::new();
2215        let mut out = Vec::new();
2216        assert!(!SystemTrait::replicate(&empty, &mut out));
2217        assert!(out.is_empty());
2218    }
2219
2220    /// **A change smaller than the quantum replicates nothing; a larger one
2221    /// does.** The server compares these bytes against the client's baseline,
2222    /// so identical bytes are what "no update" means on the wire.
2223    #[test]
2224    fn a_sub_quantum_move_replicates_the_same_bytes_and_a_larger_one_does_not() {
2225        let q = Transform::WIRE_POSITION.quantum();
2226        let entity = test_entity(1);
2227        let at = |x: f64| {
2228            let mut phys = PhysicsSystem::new();
2229            phys.set_transform(
2230                entity,
2231                Transform::new(
2232                    DVec3::new(x, 1.0, -2.0),
2233                    crate::rotation_from_scaled_axis(DVec3::Y * 0.3),
2234                ),
2235            );
2236            phys
2237        };
2238        let still = replicated(&at(10.0));
2239        assert_eq!(replicated(&at(10.0 + q / 4.0)), still, "a quarter quantum");
2240        assert_eq!(replicated(&at(10.0 - q / 4.0)), still);
2241        assert_ne!(replicated(&at(10.0 + q)), still, "a whole quantum");
2242    }
2243
2244    /// **The determinism hash is over the unquantized state.** Two systems
2245    /// whose replicated bytes are identical, because they differ by less than a
2246    /// quantum, must still hash differently: the hash is how a desync is
2247    /// caught, and the wire's rounding must not hide one.
2248    #[test]
2249    fn the_determinism_hash_sees_what_quantization_rounds_away() {
2250        use std::collections::hash_map::DefaultHasher;
2251        use std::hash::Hasher;
2252
2253        let q = Transform::WIRE_POSITION.quantum();
2254        let entity = test_entity(1);
2255        let at = |x: f64| {
2256            let mut phys = PhysicsSystem::new();
2257            phys.set_transform(entity, Transform::from_position(DVec3::new(x, 0.0, 0.0)));
2258            phys
2259        };
2260        let (a, b) = (at(3.0), at(3.0 + q / 8.0));
2261        assert_eq!(
2262            replicated(&a),
2263            replicated(&b),
2264            "the wire cannot tell them apart"
2265        );
2266        let hash = |phys: &PhysicsSystem| {
2267            let mut hasher = DefaultHasher::new();
2268            SystemTrait::hash_state(phys, &mut hasher);
2269            hasher.finish()
2270        };
2271        assert_ne!(hash(&a), hash(&b), "the hash can");
2272    }
2273
2274    #[test]
2275    fn transform_encode_decode_roundtrips_and_lerp_midpoint() {
2276        let t = Transform::new(
2277            DVec3::new(1.25, -2.5, 3.75),
2278            crate::rotation_from_scaled_axis(DVec3::Y),
2279        );
2280        let mut buf = Vec::new();
2281        t.encode(&mut buf);
2282        assert_eq!(buf.len(), t.encoded_len());
2283        let decoded = Transform::decode(&buf).unwrap();
2284        assert_eq!(decoded.position, t.position);
2285        assert!((decoded.rotation.dot(t.rotation) - 1.0).abs() < 1e-12);
2286
2287        // Wrong-length payloads decode to None.
2288        assert!(Transform::decode(&buf[..buf.len() - 1]).is_none());
2289        assert!(Transform::decode(&[]).is_none());
2290
2291        let a = Transform::from_position(DVec3::new(0.0, 0.0, 0.0));
2292        let b = Transform::from_position(DVec3::new(10.0, -4.0, 2.0));
2293        let mid = a.lerp(&b, 0.5);
2294        assert_eq!(mid.position, DVec3::new(5.0, -2.0, 1.0));
2295        let at_a = a.lerp(&b, 0.0);
2296        let at_b = a.lerp(&b, 1.0);
2297        assert_eq!(at_a.position, a.position);
2298        assert_eq!(at_b.position, b.position);
2299    }
2300
2301    #[test]
2302    fn set_and_remove_collider() {
2303        let mut phys = PhysicsSystem::new();
2304        let e = test_entity(0);
2305        let transform = Transform::from_position(DVec3::new(1.0, 2.0, 3.0));
2306        let comp = ColliderComponent::Sphere {
2307            offset: DVec3::ZERO,
2308            radius: 1.0,
2309            is_trigger: false,
2310        };
2311        phys.set_collider(e, &comp, &transform);
2312        assert_eq!(phys.collider_count(), 1);
2313        phys.remove_collider(e);
2314        assert_eq!(phys.collider_count(), 0);
2315    }
2316
2317    #[test]
2318    fn ray_cast_hits_entity() {
2319        let mut phys = PhysicsSystem::new();
2320        let e = test_entity(0);
2321        let transform = Transform::from_position(DVec3::new(5.0, 0.0, 0.0));
2322        let comp = ColliderComponent::Sphere {
2323            offset: DVec3::ZERO,
2324            radius: 1.0,
2325            is_trigger: false,
2326        };
2327        phys.set_collider(e, &comp, &transform);
2328        let ray = Ray::new(DVec3::ZERO, DVec3::X);
2329        let result = phys.cast_ray(&ray);
2330        assert!(result.is_some());
2331        let (hit_entity, _) = result.unwrap();
2332        assert_eq!(hit_entity, e);
2333    }
2334
2335    #[test]
2336    fn ray_cast_misses_when_no_collider() {
2337        let mut phys = PhysicsSystem::new();
2338        let ray = Ray::new(DVec3::ZERO, DVec3::X);
2339        assert!(phys.cast_ray(&ray).is_none());
2340    }
2341
2342    #[test]
2343    fn overlap_aabb_finds_entity() {
2344        let mut phys = PhysicsSystem::new();
2345        let e = test_entity(0);
2346        let transform = Transform::from_position(DVec3::new(2.0, 0.0, 0.0));
2347        let comp = ColliderComponent::Sphere {
2348            offset: DVec3::ZERO,
2349            radius: 1.0,
2350            is_trigger: false,
2351        };
2352        phys.set_collider(e, &comp, &transform);
2353        let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(3.0));
2354        let hits = phys.overlap_aabb(&query);
2355        assert_eq!(hits.len(), 1);
2356        assert_eq!(hits[0], e);
2357    }
2358
2359    #[test]
2360    fn sweep_removes_dead_entities() {
2361        let mut phys = PhysicsSystem::new();
2362        let e = test_entity(0);
2363        let transform = Transform::IDENTITY;
2364        let comp = ColliderComponent::Sphere {
2365            offset: DVec3::ZERO,
2366            radius: 1.0,
2367            is_trigger: false,
2368        };
2369        phys.set_collider(e, &comp, &transform);
2370        assert_eq!(phys.collider_count(), 1);
2371        phys.sweep(&[e]);
2372        assert_eq!(phys.collider_count(), 0);
2373    }
2374
2375    #[test]
2376    fn the_entity_count_starts_at_zero_and_follows_the_colliders_that_are_set() {
2377        let mut phys = PhysicsSystem::new();
2378        assert_eq!(phys.entity_count(), 0);
2379        let e = test_entity(0);
2380        phys.set_collider(
2381            e,
2382            &ColliderComponent::Sphere {
2383                offset: DVec3::ZERO,
2384                radius: 1.0,
2385                is_trigger: false,
2386            },
2387            &Transform::IDENTITY,
2388        );
2389        assert_eq!(phys.entity_count(), 1);
2390    }
2391
2392    #[test]
2393    fn replacing_collider_keeps_count_stable() {
2394        let mut phys = PhysicsSystem::new();
2395        let e = test_entity(0);
2396        let transform = Transform::IDENTITY;
2397        let comp1 = ColliderComponent::Sphere {
2398            offset: DVec3::ZERO,
2399            radius: 1.0,
2400            is_trigger: false,
2401        };
2402        let comp2 = ColliderComponent::Box {
2403            offset: DVec3::ZERO,
2404            half_extents: DVec3::splat(2.0),
2405            is_trigger: true,
2406        };
2407        phys.set_collider(e, &comp1, &transform);
2408        phys.set_collider(e, &comp2, &transform);
2409        assert_eq!(phys.collider_count(), 1);
2410    }
2411
2412    #[test]
2413    fn sweep_sphere_hits_entity() {
2414        let mut phys = PhysicsSystem::new();
2415        let e = test_entity(0);
2416        let transform = Transform::from_position(DVec3::new(5.0, 0.0, 0.0));
2417        let comp = ColliderComponent::Sphere {
2418            offset: DVec3::ZERO,
2419            radius: 1.0,
2420            is_trigger: false,
2421        };
2422        phys.set_collider(e, &comp, &transform);
2423        let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
2424        let result = phys.sweep_sphere(&seg, 0.5);
2425        assert!(result.is_some());
2426        let (hit_entity, _) = result.unwrap();
2427        assert_eq!(hit_entity, e);
2428    }
2429
2430    /// **`sweep_body` reads the body's own motion, so it catches a crossing a
2431    /// stationary overlap at the body's position would miss.**
2432    ///
2433    /// The body is at the origin moving at `10 u/s`; one second of that motion
2434    /// is the segment from `(-10, 0, 0)` to `(0, 0, 0)`. A rock sits in the
2435    /// middle of it, five units from where the body is now — an overlap query
2436    /// centred there cannot see it, and the sweep exists precisely to. The
2437    /// entity is the assertion that breaks if `dt` is misapplied (the segment
2438    /// points the other way and misses the rock entirely); the normal pins the
2439    /// segment's *direction*, which is the half a start/end swap corrupts
2440    /// without losing the hit — both are silent under the raw geometry, which
2441    /// is what this method's tests exist to catch.
2442    #[test]
2443    fn sweep_body_catches_a_crossing_a_stationary_overlap_would_miss() {
2444        let mut phys = PhysicsSystem::new();
2445        let bullet = test_entity(0);
2446        let rock = test_entity(1);
2447
2448        // The swept entity: a kinematic body with no collider, moving along +x.
2449        let mut body = RigidBody::new_kinematic();
2450        body.velocity = DVec3::new(10.0, 0.0, 0.0);
2451        phys.set_body(bullet, body);
2452        phys.set_transform(bullet, Transform::from_position(DVec3::ZERO));
2453
2454        // The rock: halfway along the segment `sweep_body` reconstructs as
2455        // `position - velocity * dt`, and clear of `position` itself.
2456        phys.set_collider(
2457            rock,
2458            &ColliderComponent::Sphere {
2459                offset: DVec3::ZERO,
2460                radius: 1.0,
2461                is_trigger: false,
2462            },
2463            &Transform::from_position(DVec3::new(-5.0, 0.0, 0.0)),
2464        );
2465
2466        let (hit_entity, hit) = phys
2467            .sweep_body(bullet, 1.0, 0.5)
2468            .expect("the sweep crossed the rock");
2469        assert_eq!(hit_entity, rock, "the sweep hit the wrong entity");
2470        // Struck on the rock's leading side: a start/end swap turns this into
2471        // +x without changing which entity is hit.
2472        assert_eq!(hit.normal, DVec3::NEG_X, "the sweep ran the wrong way");
2473    }
2474
2475    /// **A stationary body sweeps nothing it does not already touch.**
2476    ///
2477    /// Zero velocity makes the segment zero-length, which is the degenerate
2478    /// overlap branch of the swept-sphere test rather than a ray — so the rock
2479    /// sits *beside* the body, close enough that the broadphase offers it (its
2480    /// AABB reaches into the radius-inflated query bounds) but far enough that
2481    /// the exact shape test rejects it. `None` is then the shape test's answer,
2482    /// not the broadphase's.
2483    #[test]
2484    fn a_stationary_body_sweeps_nothing_it_does_not_already_touch() {
2485        let mut phys = PhysicsSystem::new();
2486        let bullet = test_entity(0);
2487        phys.set_body(bullet, RigidBody::new_kinematic());
2488        phys.set_transform(bullet, Transform::from_position(DVec3::ZERO));
2489
2490        // Diagonally beside the body: inside the broadphase query (1.4 < 0.5 +
2491        // the rock's AABB reach) but outside the combined reach of 1.5.
2492        phys.set_collider(
2493            test_entity(1),
2494            &ColliderComponent::Sphere {
2495                offset: DVec3::ZERO,
2496                radius: 1.0,
2497                is_trigger: false,
2498            },
2499            &Transform::from_position(DVec3::new(1.4, 1.4, 0.0)),
2500        );
2501
2502        assert_eq!(phys.sweep_body(bullet, 1.0, 0.5), None);
2503    }
2504
2505    /// **The swept body stays registered exactly as it was.**
2506    ///
2507    /// The workaround this replaced lifted the collider out of the world for
2508    /// the duration of the query and put it back: a BVH removal and a BVH
2509    /// insertion every tick, a recycled storage slot, a bumped generation —
2510    /// and a window in which the body was not in the world at all, so an early
2511    /// return between the two calls lost its collider. The id surviving the
2512    /// sweep unchanged is what says none of that happens any more.
2513    #[test]
2514    fn sweep_body_leaves_the_swept_colliders_registration_alone() {
2515        let mut phys = PhysicsSystem::new();
2516        let mover = test_entity(0);
2517        let mut body = RigidBody::new_kinematic();
2518        body.velocity = DVec3::new(10.0, 0.0, 0.0);
2519        phys.set_body(mover, body);
2520        phys.set_collider(
2521            mover,
2522            &ColliderComponent::Sphere {
2523                offset: DVec3::ZERO,
2524                radius: 1.0,
2525                is_trigger: false,
2526            },
2527            &Transform::from_position(DVec3::ZERO),
2528        );
2529
2530        let collider_of = |phys: &PhysicsSystem| {
2531            phys.record(mover)
2532                .and_then(|record| record.collider.as_ref())
2533                .map(|(collider, _)| *collider)
2534                .expect("the mover has a collider")
2535        };
2536        let before = collider_of(&phys);
2537        for _ in 0..8 {
2538            let _ = phys.sweep_body(mover, 1.0, 0.5);
2539        }
2540        assert_eq!(
2541            collider_of(&phys),
2542            before,
2543            "the sweep re-registered the collider it swept"
2544        );
2545        assert_eq!(phys.collider_count(), 1);
2546    }
2547
2548    /// **A body with a collider never sweeps into itself.**
2549    ///
2550    /// The segment ends where the body is, so the body's own sphere is a hit
2551    /// near the end of it — at `t = 0.85` for the geometry below. Both halves
2552    /// break without the exclusion, and they break differently: alone in the
2553    /// world the mover reports hitting *itself*, and with `wall` just past its
2554    /// end position the self-hit is the nearer of the two and masks it. The
2555    /// second is why the exclusion has to happen inside the query rather than
2556    /// by discarding a self-naming result: the narrow phase keeps one winner,
2557    /// so throwing that one away throws the wall away with it.
2558    #[test]
2559    fn sweep_body_never_hits_the_body_it_sweeps() {
2560        let sphere = ColliderComponent::Sphere {
2561            offset: DVec3::ZERO,
2562            radius: 1.0,
2563            is_trigger: false,
2564        };
2565        let mut phys = PhysicsSystem::new();
2566        let mover = test_entity(0);
2567        let wall = test_entity(1);
2568
2569        let mut body = RigidBody::new_kinematic();
2570        body.velocity = DVec3::new(10.0, 0.0, 0.0);
2571        phys.set_body(mover, body);
2572        phys.set_collider(mover, &sphere, &Transform::from_position(DVec3::ZERO));
2573
2574        assert_eq!(
2575            phys.sweep_body(mover, 1.0, 0.5),
2576            None,
2577            "the only collider in the world is the mover's own"
2578        );
2579
2580        // Just past where the mover ended up: reached at t = 0.90, behind the
2581        // mover's own shape at t = 0.85.
2582        phys.set_collider(
2583            wall,
2584            &sphere,
2585            &Transform::from_position(DVec3::new(0.5, 0.0, 0.0)),
2586        );
2587        let (hit_entity, hit) = phys
2588            .sweep_body(mover, 1.0, 0.5)
2589            .expect("the wall is on the segment");
2590        assert_eq!(hit_entity, wall, "the mover masked the wall with itself");
2591        assert!((hit.t - 0.90).abs() < 1e-9, "expected ~0.90, got {}", hit.t);
2592    }
2593
2594    /// The `_into` form answers exactly what the owned one does, and reuses
2595    /// the caller's buffer rather than appending to it.
2596    ///
2597    /// The capacity check is the half that matters to the caller it was written
2598    /// for: a crowd sample runs one query per body per tick, and a buffer that
2599    /// grew on every call would be the allocation the `_into` form exists to
2600    /// remove, moved rather than deleted. What it cannot observe from here is
2601    /// the *inner* buffers — the system's collider-id scratch and the world's
2602    /// BVH stack and candidate list — which are fields rather than locals now;
2603    /// that part is structural.
2604    #[test]
2605    fn overlap_sphere_into_answers_the_owned_form_and_reuses_the_buffer() {
2606        let mut phys = PhysicsSystem::new();
2607        for (index, x) in [0.0, 1.0, 2.0, 40.0].into_iter().enumerate() {
2608            let e = test_entity(index as u32);
2609            let at = Transform::from_position(DVec3::new(x, 0.0, 0.0));
2610            phys.set_collider(
2611                e,
2612                &ColliderComponent::Sphere {
2613                    offset: DVec3::ZERO,
2614                    radius: 0.5,
2615                    is_trigger: false,
2616                },
2617                &at,
2618            );
2619        }
2620
2621        let owned = phys.overlap_sphere(DVec3::ZERO, 2.0);
2622        assert!(
2623            owned.len() > 1 && owned.len() < 4,
2624            "the fixture must include some colliders and exclude some: {}",
2625            owned.len(),
2626        );
2627
2628        let mut out = Vec::new();
2629        phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
2630        assert_eq!(out, owned, "the two forms disagree");
2631
2632        // A buffer arriving with something in it comes back with only the
2633        // answer in it.
2634        out.push((test_entity(99), owned[0].1));
2635        phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
2636        assert_eq!(
2637            out, owned,
2638            "the buffer was appended to rather than refilled"
2639        );
2640
2641        let capacity = out.capacity();
2642        for _ in 0..64 {
2643            phys.overlap_sphere_into(DVec3::ZERO, 2.0, &mut out);
2644        }
2645        assert_eq!(
2646            out.capacity(),
2647            capacity,
2648            "the buffer grew on a repeat query, so the loop still allocates",
2649        );
2650
2651        // The shared view's forms refill theirs too, and the entities-only one
2652        // names what the hit form does, in its order.
2653        let mut scratch = crate::world::QueryScratch::new();
2654        let view = phys.overlap_queries();
2655        out.push((test_entity(99), owned[0].1));
2656        view.overlap_sphere_filtered_into(
2657            DVec3::ZERO,
2658            2.0,
2659            QueryFilter::ALL,
2660            &mut scratch,
2661            &mut out,
2662        );
2663        assert_eq!(out, owned, "the view's buffer was appended to");
2664        let mut entities = vec![test_entity(99)];
2665        view.overlap_sphere_entities_into(DVec3::ZERO, 2.0, &mut scratch, &mut entities);
2666        let named: Vec<Entity> = owned.iter().map(|&(entity, _)| entity).collect();
2667        assert_eq!(entities, named, "the entities-only form disagrees");
2668    }
2669
2670    // ── Dynamics tests ──────────────────────────────────────────────────
2671
2672    /// A velocity written through `body_mut` is the one the integrator moves
2673    /// the body with, and it does **not** move the collider by itself.
2674    ///
2675    /// Both halves matter to the caller this was added for: a crowd sample
2676    /// steers kinematic agents, which no force can move (`inverse_mass` is
2677    /// zero, so `acceleration = force * inverse_mass` is zero), and it must
2678    /// still be true that repositioning a body goes through `set_transform` so
2679    /// the broadphase hears about it.
2680    #[test]
2681    fn a_velocity_written_through_body_mut_is_the_one_that_integrates() {
2682        let mut phys = PhysicsSystem::new();
2683        let e = test_entity(0);
2684        phys.set_body(e, RigidBody::new_kinematic());
2685        phys.set_transform(e, Transform::from_position(DVec3::ZERO));
2686        let comp = ColliderComponent::Sphere {
2687            offset: DVec3::ZERO,
2688            radius: 0.5,
2689            is_trigger: false,
2690        };
2691        phys.set_collider(e, &comp, &Transform::from_position(DVec3::ZERO));
2692
2693        // A force cannot steer this body, which is why `body_mut` exists.
2694        phys.apply_force(e, DVec3::new(1000.0, 0.0, 0.0));
2695        phys.step(1.0 / 60.0);
2696        assert_eq!(
2697            phys.transform(e).expect("a transform").position,
2698            DVec3::ZERO,
2699            "a force moved a kinematic body",
2700        );
2701
2702        phys.body_mut(e).expect("a body").velocity = DVec3::new(3.0, 0.0, 0.0);
2703        let dt = 1.0 / 60.0;
2704        phys.step(dt);
2705        assert!(
2706            (phys.transform(e).expect("a transform").position.x - 3.0 * dt).abs() < 1e-12,
2707            "the written velocity did not reach the integrator: {:?}",
2708            phys.transform(e).expect("a transform").position,
2709        );
2710        assert_eq!(
2711            phys.body(e).expect("a body").velocity,
2712            DVec3::new(3.0, 0.0, 0.0),
2713            "the write did not survive the step",
2714        );
2715    }
2716
2717    /// Steering a body is not teleporting one: the write alone leaves the
2718    /// collider where it was, and the **step** is what moves it and tells the
2719    /// broadphase.
2720    ///
2721    /// Both halves are asserted against the same query, because either one
2722    /// alone is satisfied by a system that does nothing.
2723    #[test]
2724    fn a_steered_body_reaches_the_broadphase_on_the_step_and_not_before() {
2725        let mut phys = PhysicsSystem::new();
2726        let e = test_entity(0);
2727        phys.set_body(e, RigidBody::new_kinematic());
2728        let at = Transform::from_position(DVec3::new(10.0, 0.0, 0.0));
2729        phys.set_transform(e, at);
2730        let comp = ColliderComponent::Sphere {
2731            offset: DVec3::ZERO,
2732            radius: 0.5,
2733            is_trigger: false,
2734        };
2735        phys.set_collider(e, &comp, &at);
2736
2737        // Fast enough that one tick carries it clear of the query below.
2738        phys.body_mut(e).expect("a body").velocity = DVec3::new(0.0, 600.0, 0.0);
2739        assert_eq!(
2740            phys.overlap_sphere(DVec3::new(10.0, 0.0, 0.0), 1.0).len(),
2741            1,
2742            "writing a velocity moved the collider before anything stepped",
2743        );
2744
2745        phys.step(1.0 / 60.0);
2746        assert!(
2747            phys.overlap_sphere(DVec3::new(10.0, 0.0, 0.0), 1.0)
2748                .is_empty(),
2749            "the step moved the body and the broadphase did not hear about it",
2750        );
2751        assert_eq!(
2752            phys.overlap_sphere(phys.transform(e).expect("a transform").position, 1.0)
2753                .len(),
2754            1,
2755            "the collider is not where the body now is",
2756        );
2757    }
2758
2759    #[test]
2760    fn body_falls_under_gravity() {
2761        let mut phys = PhysicsSystem::new();
2762        phys.add_force_provider(Box::new(GravityForce::EARTH));
2763        let e = test_entity(0);
2764        phys.set_body(e, RigidBody::new_dynamic(1.0));
2765        phys.set_transform(e, Transform::from_position(DVec3::new(0.0, 100.0, 0.0)));
2766
2767        // Step for ~1 second at 60 Hz.
2768        let dt = 1.0 / 60.0;
2769        for _ in 0..60 {
2770            phys.step(dt);
2771        }
2772
2773        let t = phys.transform(e).unwrap();
2774        // After 1s: pos.y ≈ 100 - 0.5 * 9.81 * 1² = 100 - 4.905 ≈ 95.095
2775        assert!(
2776            t.position.y < 96.0 && t.position.y > 94.0,
2777            "expected pos.y ~95.1, got {}",
2778            t.position.y
2779        );
2780
2781        let b = phys.body(e).unwrap();
2782        // vy ≈ -9.81
2783        assert!(
2784            b.velocity.y < -9.0 && b.velocity.y > -10.5,
2785            "expected vy ~-9.81, got {}",
2786            b.velocity.y
2787        );
2788    }
2789
2790    #[test]
2791    fn kinematic_body_stays_put() {
2792        let mut phys = PhysicsSystem::new();
2793        phys.add_force_provider(Box::new(GravityForce::EARTH));
2794        let e = test_entity(0);
2795        phys.set_body(e, RigidBody::new_kinematic());
2796        phys.set_transform(e, Transform::from_position(DVec3::new(5.0, 5.0, 5.0)));
2797
2798        phys.step(1.0 / 60.0);
2799        let t = phys.transform(e).unwrap();
2800        assert_eq!(t.position, DVec3::new(5.0, 5.0, 5.0));
2801    }
2802
2803    #[test]
2804    fn collider_moves_with_body_after_integration() {
2805        let mut phys = PhysicsSystem::new();
2806        let e = test_entity(0);
2807        let body = {
2808            let mut b = RigidBody::new_dynamic(1.0);
2809            b.velocity = DVec3::new(10.0, 0.0, 0.0);
2810            b
2811        };
2812        let transform = Transform::from_position(DVec3::new(0.0, 0.0, 0.0));
2813        let comp = ColliderComponent::Sphere {
2814            offset: DVec3::ZERO,
2815            radius: 1.0,
2816            is_trigger: false,
2817        };
2818        phys.set_body(e, body);
2819        phys.set_collider(e, &comp, &transform);
2820
2821        // Step: pos moves by vel * dt.
2822        phys.step(0.5);
2823        // pos = (5, 0, 0)
2824        let t = phys.transform(e).unwrap();
2825        assert!((t.position.x - 5.0).abs() < 1e-12);
2826
2827        // Collider should have moved to the new position.
2828        let ray = Ray::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::X);
2829        let result = phys.cast_ray(&ray);
2830        assert!(result.is_some());
2831        let (hit_entity, hit) = result.unwrap();
2832        assert_eq!(hit_entity, e);
2833        // Sphere at (5,0,0) radius 1: hit at t = (5 - 1) = 4 from origin at x=-5
2834        // Actually: ray origin is -5, sphere centre is 5, radius 1 → hit at t ≈ 9
2835        // Direction is (1,0,0) so t is distance from -5 to 4 = 9.
2836        assert!((hit.t - 9.0).abs() < 0.01, "t = {}", hit.t);
2837    }
2838
2839    #[test]
2840    fn remove_entity_cleans_up_all_data() {
2841        let mut phys = PhysicsSystem::new();
2842        let e = test_entity(0);
2843        phys.set_body(e, RigidBody::new_dynamic(1.0));
2844        phys.set_collider(
2845            e,
2846            &ColliderComponent::Sphere {
2847                offset: DVec3::ZERO,
2848                radius: 1.0,
2849                is_trigger: false,
2850            },
2851            &Transform::IDENTITY,
2852        );
2853        assert_eq!(phys.body_count(), 1);
2854        assert_eq!(phys.collider_count(), 1);
2855
2856        phys.remove_entity(e);
2857        assert_eq!(phys.body_count(), 0);
2858        assert_eq!(phys.collider_count(), 0);
2859        assert!(phys.body(e).is_none());
2860        assert!(phys.transform(e).is_none());
2861    }
2862
2863    #[test]
2864    fn multiple_bodies_integrate_independently() {
2865        let mut phys = PhysicsSystem::new();
2866        phys.add_force_provider(Box::new(GravityForce::EARTH));
2867
2868        let e1 = test_entity(0);
2869        let e2 = test_entity(1);
2870
2871        phys.set_body(e1, RigidBody::new_dynamic(1.0));
2872        phys.set_transform(e1, Transform::from_position(DVec3::new(0.0, 0.0, 0.0)));
2873
2874        // e2: kinematic, should not move.
2875        phys.set_body(e2, RigidBody::new_kinematic());
2876        phys.set_transform(e2, Transform::from_position(DVec3::new(10.0, 10.0, 0.0)));
2877
2878        phys.step(1.0 / 60.0);
2879
2880        let t1 = phys.transform(e1).unwrap();
2881        let t2 = phys.transform(e2).unwrap();
2882        assert!(t1.position.y < 0.0, "dynamic body should fall");
2883        assert_eq!(
2884            t2.position,
2885            DVec3::new(10.0, 10.0, 0.0),
2886            "kinematic should not move"
2887        );
2888    }
2889
2890    /// A step over an empty world applies nothing and creates nothing.
2891    ///
2892    /// "Did not panic" was the whole of this before, and a `step` that invented
2893    /// a body out of an empty map, or ran its providers over a default body,
2894    /// would not have panicked either. The provider counts its own calls
2895    /// because that is the only way to see the difference: a force applied to a
2896    /// body nothing else can reach leaves no trace in the counts or the hash.
2897    #[test]
2898    fn a_step_with_no_bodies_applies_no_force_and_creates_nothing() {
2899        use std::collections::hash_map::DefaultHasher;
2900        use std::hash::Hasher as _;
2901        use std::sync::Arc;
2902        use std::sync::atomic::{AtomicUsize, Ordering};
2903
2904        #[derive(Debug)]
2905        struct CountingGravity(Arc<AtomicUsize>);
2906
2907        impl ForceProvider for CountingGravity {
2908            fn apply(&self, body: &mut RigidBody, transform: &Transform, dt: f64) {
2909                self.0.fetch_add(1, Ordering::SeqCst);
2910                GravityForce::EARTH.apply(body, transform, dt);
2911            }
2912        }
2913
2914        let applications = Arc::new(AtomicUsize::new(0));
2915
2916        let mut phys = PhysicsSystem::new();
2917        phys.add_force_provider(Box::new(CountingGravity(Arc::clone(&applications))));
2918
2919        let mut before = DefaultHasher::new();
2920        SystemTrait::hash_state(&phys, &mut before);
2921
2922        phys.step(1.0 / 60.0);
2923
2924        assert_eq!(
2925            applications.load(Ordering::SeqCst),
2926            0,
2927            "there is no body for a force provider to be applied to"
2928        );
2929        assert_eq!(phys.body_count(), 0);
2930        assert_eq!(phys.collider_count(), 0);
2931
2932        let mut after = DefaultHasher::new();
2933        SystemTrait::hash_state(&phys, &mut after);
2934        assert_eq!(after.finish(), before.finish(), "the step wrote state");
2935    }
2936
2937    // ── Schedule integration ────────────────────────────────────────────
2938
2939    #[test]
2940    fn tick_uses_the_schedule_dt_rather_than_an_assumed_rate() {
2941        // Same simulated second, two tick rates.  A hardcoded step would make
2942        // the 30 Hz run cover half the ground of the 60 Hz one.
2943        let simulate = |hz: u32| {
2944            let mut phys = PhysicsSystem::new();
2945            let e = test_entity(0);
2946            let mut body = RigidBody::new_dynamic(1.0);
2947            body.velocity = DVec3::new(10.0, 0.0, 0.0);
2948            phys.set_body(e, body);
2949            phys.set_transform(e, Transform::IDENTITY);
2950
2951            let dt = 1.0 / f64::from(hz);
2952            for _ in 0..hz {
2953                SystemTrait::tick(&mut phys, dt);
2954            }
2955            phys.transform(e).unwrap().position.x
2956        };
2957
2958        let at_60 = simulate(60);
2959        let at_30 = simulate(30);
2960        assert!((at_60 - 10.0).abs() < 1e-9, "x = {at_60}");
2961        assert!((at_30 - 10.0).abs() < 1e-9, "x = {at_30}");
2962    }
2963
2964    #[test]
2965    fn step_visits_bodies_in_canonical_order() {
2966        // Insertion order must not reach the arithmetic: the `bodies` map is
2967        // randomly seeded, so anything that depended on it would differ per
2968        // process.  Two systems built in opposite orders must agree bit for
2969        // bit.
2970        let build = |reverse: bool| {
2971            let mut phys = PhysicsSystem::new();
2972            phys.add_force_provider(Box::new(GravityForce::EARTH));
2973            let mut indices: Vec<u32> = (0..16).collect();
2974            if reverse {
2975                indices.reverse();
2976            }
2977            for i in indices {
2978                let e = test_entity(i);
2979                let mut body = RigidBody::new_dynamic(1.0 + f64::from(i) * 0.25);
2980                body.velocity = DVec3::new(f64::from(i) * 0.1, 0.0, 0.0);
2981                phys.set_body(e, body);
2982                phys.set_transform(e, Transform::from_position(DVec3::splat(f64::from(i))));
2983            }
2984            for _ in 0..120 {
2985                phys.step(1.0 / 120.0);
2986            }
2987            phys
2988        };
2989
2990        let forward = build(false);
2991        let backward = build(true);
2992        for i in 0..16 {
2993            let e = test_entity(i);
2994            assert_eq!(
2995                forward.transform(e).unwrap().position,
2996                backward.transform(e).unwrap().position,
2997                "entity {i} diverged"
2998            );
2999        }
3000    }
3001
3002    #[test]
3003    fn hash_state_covers_physics_state_in_canonical_order() {
3004        use std::collections::hash_map::DefaultHasher;
3005        use std::hash::Hasher as _;
3006
3007        fn hash(phys: &PhysicsSystem) -> u64 {
3008            let mut h = DefaultHasher::new();
3009            SystemTrait::hash_state(phys, &mut h);
3010            h.finish()
3011        }
3012
3013        let build = |reverse: bool, y: f64| {
3014            let mut phys = PhysicsSystem::new();
3015            let mut indices: Vec<u32> = (0..8).collect();
3016            if reverse {
3017                indices.reverse();
3018            }
3019            for i in indices {
3020                let e = test_entity(i);
3021                phys.set_body(e, RigidBody::new_dynamic(1.0 + f64::from(i)));
3022                phys.set_transform(
3023                    e,
3024                    Transform::from_position(DVec3::new(f64::from(i), y, 0.0)),
3025                );
3026            }
3027            phys
3028        };
3029
3030        // The system must announce that it contributes, or the server's
3031        // determinism harness silently skips all of physics.
3032        assert!(SystemTrait::contributes_to_hash(&build(false, 0.0)));
3033
3034        // Insertion order is not state; position is.
3035        assert_eq!(hash(&build(false, 0.0)), hash(&build(true, 0.0)));
3036        assert_ne!(hash(&build(false, 0.0)), hash(&build(false, 1.0)));
3037
3038        // A velocity change alone must move the hash.
3039        let mut moving = build(false, 0.0);
3040        let e = test_entity(3);
3041        let mut body = *moving.body(e).unwrap();
3042        body.velocity = DVec3::new(0.0, -1.0, 0.0);
3043        moving.set_body(e, body);
3044        assert_ne!(hash(&build(false, 0.0)), hash(&moving));
3045    }
3046
3047    // ── Dense storage ───────────────────────────────────────────────────
3048
3049    /// **Removing bodies from the middle of a set leaves every other one's
3050    /// body, transform and collider where its entity finds them.**
3051    ///
3052    /// A swap-remove moves the set's last body into the hole, so a record whose
3053    /// index was not rewritten would name its neighbour's state. Each entity
3054    /// here has a mass, a position and a collider that are its own, so a stale
3055    /// index shows up as the wrong one of each. Both sets are exercised: the
3056    /// statics are colliders with no body.
3057    #[test]
3058    fn removing_from_the_middle_of_a_set_leaves_every_other_body_its_own_state() {
3059        let mut phys = PhysicsSystem::new();
3060        let at = |i: u32| DVec3::new(f64::from(i) * 10.0, 0.0, 0.0);
3061        let sphere = ColliderComponent::Sphere {
3062            offset: DVec3::ZERO,
3063            radius: 1.0,
3064            is_trigger: false,
3065        };
3066        for i in 0..12u32 {
3067            let e = test_entity(i);
3068            phys.set_collider(e, &sphere, &Transform::from_position(at(i)));
3069            if i % 3 != 0 {
3070                let mut body = RigidBody::new_dynamic(1.0 + f64::from(i));
3071                body.velocity = DVec3::Y;
3072                phys.set_body(e, body);
3073            }
3074        }
3075        for i in [1u32, 3, 7, 0, 11] {
3076            phys.remove_entity(test_entity(i));
3077        }
3078        phys.step(1.0);
3079
3080        for i in 0..12u32 {
3081            let e = test_entity(i);
3082            let removed = [1u32, 3, 7, 0, 11].contains(&i);
3083            if removed {
3084                assert!(phys.transform(e).is_none(), "{i} survived its removal");
3085                continue;
3086            }
3087            let has_body = i % 3 != 0;
3088            let want = at(i) + if has_body { DVec3::Y } else { DVec3::ZERO };
3089            assert_eq!(
3090                phys.transform(e).expect("a transform").position,
3091                want,
3092                "entity {i} has another's transform"
3093            );
3094            assert_eq!(
3095                phys.body(e).map(|body| body.mass),
3096                has_body.then(|| 1.0 + f64::from(i)),
3097                "entity {i} has another's body"
3098            );
3099            let hit = phys
3100                .cast_ray(&Ray::new(want - DVec3::Z * 5.0, DVec3::Z))
3101                .map(|(entity, _)| entity);
3102            assert_eq!(hit, Some(e), "entity {i}'s collider is not where it is");
3103        }
3104        assert_eq!(phys.body_count(), 5);
3105        assert_eq!(phys.collider_count(), 7);
3106    }
3107
3108    /// **Giving a static entity a body moves it into the awake set with its
3109    /// transform, and leaves the static it swapped with intact.**
3110    #[test]
3111    fn a_body_moves_a_static_entity_into_the_awake_set_with_its_transform() {
3112        let mut phys = PhysicsSystem::new();
3113        let (wall, prop, crate_) = (test_entity(0), test_entity(1), test_entity(2));
3114        phys.set_transform(wall, Transform::from_position(DVec3::X));
3115        phys.set_transform(crate_, Transform::from_position(DVec3::Y));
3116        phys.set_transform(prop, Transform::from_position(DVec3::Z));
3117
3118        let mut body = RigidBody::new_kinematic();
3119        body.velocity = DVec3::X;
3120        phys.set_body(wall, body);
3121        phys.step(1.0);
3122
3123        assert_eq!(
3124            phys.transform(wall).expect("a transform").position,
3125            DVec3::X * 2.0
3126        );
3127        assert_eq!(
3128            phys.transform(crate_).expect("a transform").position,
3129            DVec3::Y
3130        );
3131        assert_eq!(
3132            phys.transform(prop).expect("a transform").position,
3133            DVec3::Z
3134        );
3135        assert!(phys.body(crate_).is_none() && phys.body(prop).is_none());
3136        assert_eq!(phys.body_count(), 1);
3137    }
3138
3139    #[test]
3140    fn a_material_is_carried_on_its_entity_and_defaults_until_set() {
3141        let mut phys = PhysicsSystem::new();
3142        let (ice, floor) = (test_entity(0), test_entity(1));
3143        let ghost = test_entity(2);
3144        phys.set_body(ice, RigidBody::new_dynamic(1.0));
3145        phys.set_transform(floor, Transform::IDENTITY);
3146
3147        assert_eq!(phys.material(ice), Some(SurfaceMaterial::DEFAULT));
3148        let slick = SurfaceMaterial::new(0.02, 0.1);
3149        assert!(phys.set_material(ice, slick));
3150        assert!(phys.set_material(floor, SurfaceMaterial::new(0.9, 0.0)));
3151        assert_eq!(phys.material(ice), Some(slick));
3152        assert_eq!(phys.material(floor).map(|m| m.friction), Some(0.9));
3153
3154        assert!(!phys.set_material(ghost, slick), "an unregistered entity");
3155        assert_eq!(phys.material(ghost), None);
3156        phys.remove_entity(ice);
3157        assert_eq!(phys.material(ice), None, "the material outlived its entity");
3158    }
3159
3160    /// Decision 8's canonical hash: a state that compares equal hashes equal,
3161    /// so a velocity of `-0.0` is the same state as `+0.0`.
3162    #[test]
3163    fn the_hash_does_not_tell_a_negative_zero_from_a_positive_one() {
3164        use std::collections::hash_map::DefaultHasher;
3165        use std::hash::Hasher as _;
3166
3167        let hash = |vx: f64| {
3168            let mut phys = PhysicsSystem::new();
3169            let mut body = RigidBody::new_dynamic(1.0);
3170            body.velocity = DVec3::new(vx, 1.0, 0.0);
3171            phys.set_body(test_entity(0), body);
3172            let mut h = DefaultHasher::new();
3173            SystemTrait::hash_state(&phys, &mut h);
3174            h.finish()
3175        };
3176        assert_eq!(hash(0.0), hash(-0.0));
3177        assert_ne!(
3178            hash(0.0),
3179            hash(f64::MIN_POSITIVE),
3180            "the hash cannot see velocity"
3181        );
3182    }
3183}
3184
3185#[cfg(test)]
3186#[path = "system/query_layer_tests.rs"]
3187mod query_layer_tests;