crcbl_phys/world.rs
1//! Physics world: collider storage, BVH management, and query dispatch.
2//!
3//! [`PhysicsWorld`] is the main entry point for physics queries during
4//! simulation. It stores collider shapes indexed by a generic `ColliderId`,
5//! maintains a lazily-rebuilt BVH over their AABBs, and dispatches rays and
6//! sweeps to the shape-level intersection functions.
7
8use glam::{DQuat, DVec3};
9
10use crate::broadphase::{Bvh, BvhHit, Ray, Segment};
11use crate::collider::{Aabb, BoxCollider, Capsule, LyingCapsule, Sphere};
12use crate::components::Transform;
13use crate::compound_shape::CompoundShape;
14use crate::contact::manifold::gap;
15use crate::contact::shape::ContactShape;
16use crate::mesh::{MeshScratch, PlacedMesh, TriangleMesh};
17use crate::query::{self, OverlapHit, Penetration, ShapeHit, TurnedCapsule};
18
19mod arc_sweep;
20mod candidate_sweeps;
21mod capsule_sweep;
22pub(crate) use capsule_sweep::CapsuleSweepShape;
23mod entry;
24mod placement;
25
26use entry::{ColliderEntry, PlacedCompound, Primitive};
27
28/// Opaque identifier for a registered collider.
29///
30/// Created by [`PhysicsWorld::add_sphere`], [`PhysicsWorld::add_box`],
31/// [`PhysicsWorld::add_capsule`], [`PhysicsWorld::add_mesh`] or
32/// [`PhysicsWorld::add_compound`]. Use it to remove or update the collider.
33///
34/// This is a *generational* id — a storage slot plus the generation that slot
35/// was issued with — for the same reason [`crcbl_ecs::Entity`] is: removing a
36/// collider recycles its slot, and a bare index kept across the removal would
37/// silently start addressing whatever collider landed there next. A stale id
38/// resolves to nothing instead.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct ColliderId {
41 index: u32,
42 generation: u32,
43}
44
45impl ColliderId {
46 /// The storage slot this id names.
47 ///
48 /// A small integer to subscript a caller's own per-collider array with,
49 /// which is what a hot loop wants where a `HashMap<ColliderId, _>` would
50 /// otherwise stand: turning a query result back into "which of my bodies
51 /// is this" costs an array index rather than a hash.
52 ///
53 /// What the number does and does not promise:
54 ///
55 /// - **Bounded** by the number of slots the world has ever allocated. That
56 /// equals [`PhysicsWorld::len`] only while nothing has been removed —
57 /// afterwards the slot count stays where it was and `len` drops below it,
58 /// so an array sized from `len` is too short.
59 /// - **Stable** for as long as the collider lives. Nothing compacts the
60 /// slot array, so a collider keeps its slot however many others are added
61 /// or removed around it.
62 /// - **Not dense** once anything has been removed: the freed slot is a hole
63 /// until a later `add` recycles it.
64 /// - **Not an identity.** A recycled slot names a different collider, and
65 /// only the generation the id also carries tells the two apart. Comparing
66 /// slots is not comparing colliders; compare the ids themselves.
67 #[inline]
68 #[must_use]
69 pub const fn index(self) -> u32 {
70 self.index
71 }
72
73 /// Build an id from its parts. Crate-internal: only [`PhysicsWorld`] knows
74 /// which generation a slot is currently on.
75 #[inline]
76 const fn new(index: u32, generation: u32) -> Self {
77 Self { index, generation }
78 }
79}
80
81// ---------------------------------------------------------------------------
82// Collider shape storage
83// ---------------------------------------------------------------------------
84
85/// `bvh_slot_to_elem` entry for a collider slot with no element in the tree.
86const NO_ELEMENT: u32 = u32::MAX;
87
88/// The layer bits a collider starts with: every one, so a query with any
89/// non-zero mask sees it and a world that never touches layers behaves as if
90/// they did not exist.
91pub const ALL_LAYERS: u32 = u32::MAX;
92
93/// Repartition a refit-aged tree once its normalized traversal cost grows this
94/// far past the last build or structural-change baseline.
95const BROADPHASE_REBUILD_COST_RATIO: f64 = 1.2;
96
97/// Full-tree equivalents of refits between quality scans.
98const BROADPHASE_QUALITY_CHECK_REFIT_PASSES: usize = 4;
99
100/// A collider stored in the [`PhysicsWorld`], with an optional trigger flag.
101#[derive(Debug, Clone)]
102struct ColliderSlot {
103 entry: ColliderEntry,
104 /// When true, this collider is a trigger (generates overlap events rather
105 /// than collision response).
106 is_trigger: bool,
107 /// The query layers this collider is on; see [`PhysicsWorld::set_layers`].
108 layers: u32,
109}
110
111/// Which colliders a query may report: one collider left out, and a mask of
112/// the layers it looks at.
113///
114/// A collider passes when it is not [`exclude`](Self::exclude) and its
115/// [layers](PhysicsWorld::set_layers) match [`mask`](Self::mask) the way
116/// [`layer_match`](Self::layer_match) says: by sharing at least one bit with
117/// it (the default), or by lying wholly [`within`](Self::within) it. The solid
118/// queries — rays, sweeps and capsule
119/// penetrations — also skip triggers, exactly as their unfiltered forms do;
120/// the overlap queries report triggers, as theirs do. A filter never makes a
121/// query see something its unfiltered form would not.
122///
123/// The [`Default`] excludes nothing and looks at every layer, which is what
124/// every unfiltered query passes: `cast_ray(ray)` is
125/// `cast_ray_filtered(ray, QueryFilter::default())`.
126///
127/// ```
128/// use crcbl_phys::{BoxCollider, PhysicsWorld, QueryFilter, Ray};
129/// use glam::DVec3;
130///
131/// const ITEMS: u32 = 1 << 1;
132///
133/// let mut world = PhysicsWorld::new();
134/// let item = world.add_box(BoxCollider::new(DVec3::new(2.0, 0.0, 0.0), DVec3::splat(0.5)));
135/// world.set_layers(item, ITEMS);
136/// let ray = Ray::new(DVec3::ZERO, DVec3::X);
137///
138/// // A movement query looks past items; an interaction ray looks only at them.
139/// assert!(world.cast_ray_filtered(&ray, QueryFilter::masked(!ITEMS)).is_none());
140/// assert_eq!(
141/// world.cast_ray_filtered(&ray, QueryFilter::masked(ITEMS)).map(|(id, _)| id),
142/// Some(item),
143/// );
144/// ```
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct QueryFilter {
147 /// A collider to leave out of the answer, or `None`. A stale or invalid id
148 /// excludes nothing, which is the same answer as `None`.
149 pub exclude: Option<ColliderId>,
150 /// The layers the query looks at. A collider on none of them is skipped,
151 /// so a mask of `0` sees nothing.
152 pub mask: u32,
153 /// How a collider's layers must match [`mask`](Self::mask) to be looked
154 /// at.
155 pub layer_match: LayerMatch,
156}
157
158/// How a [`QueryFilter`] holds a collider's layers to its mask.
159///
160/// Every collider starts on [`ALL_LAYERS`], so under
161/// [`Shares`](Self::Shares) a mask of one query-only layer still reports every
162/// ordinary collider beside the ones put on it. [`Within`](Self::Within) is the
163/// query for those alone — a walker barrier, a concealment volume — without a
164/// second, inverted query to subtract.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
166pub enum LayerMatch {
167 /// A collider sharing at least one layer with the mask: `layers & mask !=
168 /// 0`.
169 #[default]
170 Shares,
171 /// A collider on at least one layer, every one of them in the mask:
172 /// `layers & mask != 0 && layers & !mask == 0`. A collider still on
173 /// [`ALL_LAYERS`] is within no mask short of every layer.
174 Within,
175}
176
177impl LayerMatch {
178 /// Whether a collider on `layers` matches `mask` this way.
179 const fn admits(self, layers: u32, mask: u32) -> bool {
180 match self {
181 Self::Shares => layers & mask != 0,
182 Self::Within => layers & mask != 0 && layers & !mask == 0,
183 }
184 }
185}
186
187impl QueryFilter {
188 /// Excludes nothing and looks at every layer: the [`Default`].
189 pub const ALL: Self = Self {
190 exclude: None,
191 mask: ALL_LAYERS,
192 layer_match: LayerMatch::Shares,
193 };
194
195 /// Every layer, with `exclude` left out — what the `_excluding` queries
196 /// pass.
197 #[must_use]
198 pub const fn excluding(exclude: Option<ColliderId>) -> Self {
199 Self {
200 exclude,
201 mask: ALL_LAYERS,
202 layer_match: LayerMatch::Shares,
203 }
204 }
205
206 /// Only the layers in `mask`, excluding nothing.
207 #[must_use]
208 pub const fn masked(mask: u32) -> Self {
209 Self {
210 exclude: None,
211 mask,
212 layer_match: LayerMatch::Shares,
213 }
214 }
215
216 /// Only the colliders whose layers all lie in `mask`, excluding nothing:
217 /// [`LayerMatch::Within`].
218 #[must_use]
219 pub const fn within(mask: u32) -> Self {
220 Self {
221 exclude: None,
222 mask,
223 layer_match: LayerMatch::Within,
224 }
225 }
226
227 /// This filter with its mask replaced by `mask`.
228 #[must_use]
229 pub const fn with_mask(self, mask: u32) -> Self {
230 Self { mask, ..self }
231 }
232
233 /// This filter with its exclusion replaced by `exclude`.
234 #[must_use]
235 pub const fn with_exclude(self, exclude: Option<ColliderId>) -> Self {
236 Self { exclude, ..self }
237 }
238
239 /// This filter with its layer test replaced by `layer_match`.
240 #[must_use]
241 pub const fn with_layer_match(self, layer_match: LayerMatch) -> Self {
242 Self {
243 layer_match,
244 ..self
245 }
246 }
247}
248
249impl Default for QueryFilter {
250 fn default() -> Self {
251 Self::ALL
252 }
253}
254
255/// A [`QueryFilter`] resolved against one world for one query: the excluded
256/// id turned into its storage slot, and whether triggers count.
257///
258/// Every candidate loop asks [`admits`](Self::admits) and nothing else, so
259/// what a trigger, an excluded collider and a layer mask mean is one rule
260/// shared by every query family, not a copy per loop.
261#[derive(Debug, Clone, Copy)]
262struct ResolvedFilter {
263 /// The storage slot of the excluded collider, if it is live.
264 skip: Option<usize>,
265 mask: u32,
266 layer_match: LayerMatch,
267 /// Whether triggers are skipped — true for the solid queries.
268 solid: bool,
269}
270
271impl ResolvedFilter {
272 /// For a ray, sweep or penetration query: triggers are skipped.
273 fn solid(colliders: &[Option<ColliderSlot>], generations: &[u32], filter: QueryFilter) -> Self {
274 Self::resolve(colliders, generations, filter, true)
275 }
276
277 /// For an overlap query: triggers are reported.
278 fn overlap(
279 colliders: &[Option<ColliderSlot>],
280 generations: &[u32],
281 filter: QueryFilter,
282 ) -> Self {
283 Self::resolve(colliders, generations, filter, false)
284 }
285
286 fn resolve(
287 colliders: &[Option<ColliderSlot>],
288 generations: &[u32],
289 filter: QueryFilter,
290 solid: bool,
291 ) -> Self {
292 Self {
293 skip: filter
294 .exclude
295 .and_then(|id| slot_of_in(colliders, generations, id)),
296 mask: filter.mask,
297 layer_match: filter.layer_match,
298 solid,
299 }
300 }
301
302 /// The tree's elements whose bounds meet `bounds`, into
303 /// `scratch.candidates`, leaving out subtrees on none of the mask's
304 /// layers.
305 ///
306 /// Both layer tests ask `layers & mask != 0` before anything else, so a
307 /// collider in a pruned subtree is one [`admits`](Self::admits) would
308 /// refuse, and the survivors come in the order the unpruned walk gives
309 /// them: every query's answer is what it was without the pruning. The
310 /// exclusion, the trigger flag and [`LayerMatch::Within`]'s second half
311 /// are not masks over the tree and stay in `admits`.
312 fn candidates(&self, bvh: &Bvh, bounds: &Aabb, scratch: &mut QueryScratch) {
313 bvh.traverse_aabb_masked_into(
314 bounds,
315 self.mask,
316 &mut scratch.stack,
317 &mut scratch.candidates,
318 );
319 }
320
321 /// Whether the collider at storage slot `idx` may be reported.
322 fn admits(&self, idx: usize, slot: &ColliderSlot) -> bool {
323 Some(idx) != self.skip
324 && self.layer_match.admits(slot.layers, self.mask)
325 && !(self.solid && slot.is_trigger)
326 }
327}
328
329// ---------------------------------------------------------------------------
330// PhysicsWorld
331// ---------------------------------------------------------------------------
332
333/// A reading of the broadphase, from [`PhysicsWorld::broadphase_stats`].
334///
335/// Two kinds of number, read two different ways.
336///
337/// **The shape, as it is right now:** [`elements`](Self::elements),
338/// [`nodes`](Self::nodes), [`depth`](Self::depth) and
339/// [`surface_area_cost`](Self::surface_area_cost). These are what let a
340/// structural policy (a teleport rule, a rebuild cadence) be argued from
341/// measurement — depth is the query-cost bound, node count the footprint
342/// including recycled slots, and surface-area cost exposes overlap inside a
343/// tree whose depth stayed balanced.
344///
345/// **The totals, counting up from the moment the world was created and never
346/// reset:** [`refits`](Self::refits),
347/// [`updates_without_refit`](Self::updates_without_refit) and
348/// [`rebuilds`](Self::rebuilds). There is no reset call, deliberately: take a
349/// reading either side of a phase and subtract, and the phase's own numbers
350/// come out exactly, with no second observer able to zero the counters halfway
351/// through somebody else's measurement.
352///
353/// Taking the reading is itself an event the totals see.
354/// [`PhysicsWorld::broadphase_stats`] forces the lazy rebuild, so a reading
355/// taken while the tree is dirty reports a `rebuilds` that includes the one it
356/// just caused — which is the honest number, since that rebuild happened.
357#[derive(Debug, Clone, Copy, PartialEq)]
358pub struct BroadphaseStats {
359 /// Live colliders (leaves) in the tree.
360 pub elements: usize,
361 /// Allocated node slots, including those a `remove` recycled.
362 pub nodes: usize,
363 /// Longest root-to-leaf path, counted in nodes ([`Bvh::depth`]'s units).
364 pub depth: usize,
365 /// Sum of every live internal node's half-surface area.
366 ///
367 /// [`Bvh::surface_area_cost`] is the definition and the reason this catches
368 /// refit degradation that [`depth`](Self::depth) cannot. Compare readings
369 /// over the same collider set and world scale; the absolute value carries
370 /// units squared and is not a portable threshold by itself.
371 pub surface_area_cost: f64,
372 /// Collider updates ([`PhysicsWorld::set_sphere`] and its siblings) that a
373 /// built tree absorbed in place, refitting one root-to-leaf path.
374 ///
375 /// How far the collider moved does not enter into it. [`Bvh::update_aabb`]
376 /// never refuses a new box for being far from the old one — it grows the
377 /// ancestors it walks back through — so a body that teleports across the
378 /// world is counted here too, and pays for the trip in a looser tree rather
379 /// than in a rebuild.
380 pub refits: u64,
381 /// Collider updates that did not refit, leaving the BVH absent so that the
382 /// next query rebuilds it.
383 ///
384 /// An update refits whenever the id resolves *and* the tree both exists and
385 /// still holds an element for that slot, so what lands here is an update
386 /// made with no tree to refit: before the first query, or after something
387 /// else already dropped the tree.
388 ///
389 /// Counted per update, not per rebuild — several of these before the next
390 /// query cost one rebuild between them. With [`refits`](Self::refits) it
391 /// accounts for every `set_*` call that resolved to a live collider; a call
392 /// on a stale id is counted by neither.
393 pub updates_without_refit: u64,
394 /// Full [`Bvh::build`]s performed, whether asked for by
395 /// [`PhysicsWorld::rebuild`] or forced by a query finding the tree absent.
396 ///
397 /// The number that says which of the two a phase's timing actually
398 /// measured, and the reason the other two totals are here at all.
399 pub rebuilds: u64,
400}
401
402/// The running totals [`BroadphaseStats`] hands out.
403///
404/// Separate from the stats struct because these are the world's own state,
405/// while `BroadphaseStats` is a reading of it taken alongside the tree's shape.
406#[derive(Debug, Clone, Copy, Default)]
407struct BroadphaseCounters {
408 refits: u64,
409 updates_without_refit: u64,
410 rebuilds: u64,
411}
412
413/// A spatial world that stores colliders and supports ray/sweep queries.
414///
415/// Colliders are added with `add_sphere`, `add_box`, `add_capsule` or
416/// `add_mesh` and removed with `remove`. The internal BVH is rebuilt lazily — call
417/// [`PhysicsWorld::rebuild`] after batch mutations, or it auto-rebuilds on
418/// the next query.
419///
420/// # Queries only: the contact solver never reads this world
421///
422/// A collider added here directly answers rays, sweeps and overlaps and
423/// nothing else. The contact solver in a
424/// [`PhysicsSystem`](crate::PhysicsSystem) built
425/// [`with_contacts`](crate::PhysicsSystem::with_contacts) pairs bodies through
426/// its own broadphase, which holds only the colliders bodies own as a
427/// [`ColliderComponent`](crate::ColliderComponent): a body falls straight
428/// through a floor registered with `add_box` or `add_mesh` through
429/// [`PhysicsSystem::world_mut`](crate::PhysicsSystem::world_mut). Ground that
430/// bodies must stand on is a static body carrying the collider, such as a
431/// [`ColliderComponent::Mesh`](crate::ColliderComponent::Mesh) for terrain.
432pub struct PhysicsWorld {
433 /// Dense storage of collider entries.
434 colliders: Vec<Option<ColliderSlot>>,
435 /// Generation counter per slot, parallel to `colliders`. Bumped when a
436 /// slot is freed, so ids issued before the removal stop resolving.
437 generations: Vec<u32>,
438 /// Free slots for reuse (indices into `colliders`).
439 free_slots: Vec<u32>,
440 /// Live collider count, so `len` does not scan the slot array.
441 live_count: usize,
442 /// Lazily-rebuilt BVH. `None` when dirty.
443 bvh: Option<Bvh>,
444 /// Scale-independent surface-area cost at the last build or structural
445 /// change. `None` asks the next query batch to establish a new baseline.
446 bvh_quality_baseline: Option<f64>,
447 /// Successful leaf refits since the last quality scan.
448 refits_since_quality_check: usize,
449 /// Refit and rebuild totals, handed out by
450 /// [`PhysicsWorld::broadphase_stats`]. Never reset.
451 counters: BroadphaseCounters,
452 /// Maps collider slot index → BVH element position (`u32::MAX` for slots
453 /// with no element). Populated during [`PhysicsWorld::rebuild`]. Used by
454 /// update methods for O(log n) refit.
455 bvh_slot_to_elem: Vec<u32>,
456 /// The buffers an overlap query works in, kept between calls.
457 ///
458 /// None of them outlives the call, so allocating them per call is a cost a
459 /// caller running one query per body per tick pays for nothing. They live
460 /// here rather than being passed in because `&mut self` query methods
461 /// already take the exclusive borrow that makes one shared set sound —
462 /// [`OverlapQueries`] is the shape for callers who cannot, and it asks for
463 /// a [`QueryScratch`] of their own instead.
464 scratch: QueryScratch,
465}
466
467/// The buffers one overlap query works in, owned by whoever runs the query.
468///
469/// [`OverlapQueries::overlap_sphere_into`] takes `&self`, so it cannot reach
470/// the world's own buffers — several threads running queries at once would be
471/// writing the same ones. One of these per thread is what replaces them, and it
472/// is reused across calls exactly as the world's are: the contents are cleared
473/// on entry and mean nothing between calls, so a scratch buffer never changes
474/// an answer, only what a query has to allocate to reach it.
475#[derive(Debug, Default)]
476pub struct QueryScratch {
477 /// The BVH descent stack.
478 stack: Vec<u32>,
479 /// The elements the descent turned up, before the exact shape test.
480 candidates: Vec<u32>,
481 /// The leaves a ray descent turned up. Separate from `candidates` because
482 /// a ray leaf carries the AABB entry distance alongside its element id.
483 ray_hits: Vec<BvhHit>,
484 /// The collider ids the exact test kept, for a caller mapping them onto
485 /// something of its own — [`crate::system::EntityOverlapQueries`] maps them
486 /// to entities, which is why this is reachable from that module and from
487 /// nowhere outside the crate.
488 pub(crate) ids: Vec<ColliderId>,
489 /// The sphere overlaps' hits, kept for the same caller and the same
490 /// reason as `ids`.
491 pub(crate) hits: Vec<(ColliderId, OverlapHit)>,
492 /// The buffers a mesh's own tree is descended in, while the world's
493 /// candidates are still being walked.
494 mesh: MeshScratch,
495}
496
497impl QueryScratch {
498 /// Empty buffers, which the first query grows.
499 #[must_use]
500 pub fn new() -> Self {
501 Self::default()
502 }
503}
504
505/// Read-only overlap queries against a world whose broadphase is already built.
506///
507/// **The type is the proof, not a comment.** A query needs the BVH to be
508/// current, and building it needs `&mut PhysicsWorld` — so
509/// [`PhysicsWorld::overlap_queries`] takes that exclusive borrow, builds the
510/// tree, and hands back a shared borrow of the world in its place. A caller
511/// cannot reach these queries without the tree being current and cannot mutate
512/// the world while one is outstanding, which is what makes the query itself
513/// `&self` and therefore `Sync`.
514///
515/// That is the whole point of it: a data-parallel pass over a crowd hands the
516/// same view to every chunk and gives each chunk a [`QueryScratch`] of its own.
517/// A caller that is not doing that wants
518/// [`PhysicsWorld::overlap_sphere_into`], which keeps the scratch itself.
519#[derive(Clone, Copy, Debug)]
520pub struct OverlapQueries<'a> {
521 colliders: &'a [Option<ColliderSlot>],
522 generations: &'a [u32],
523 bvh: &'a Bvh,
524}
525
526impl OverlapQueries<'_> {
527 /// [`PhysicsWorld::overlap_sphere_into`] under a shared borrow, working in
528 /// `scratch` instead of the world's own buffers.
529 ///
530 /// `out` is cleared and then filled. The results are identical to the
531 /// `&mut self` form's — same tree, same traversal order, same exact tests —
532 /// because the two are one implementation and not two that agree;
533 /// `crcbl_phys::world::tests::the_shared_view_finds_exactly_what_a_scan_would`
534 /// is what checks that implementation against a scan.
535 pub fn overlap_sphere_into(
536 &self,
537 centre: DVec3,
538 radius: f64,
539 scratch: &mut QueryScratch,
540 out: &mut Vec<(ColliderId, OverlapHit)>,
541 ) {
542 self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, scratch, out);
543 }
544
545 /// [`overlap_sphere_into`](Self::overlap_sphere_into) reporting only the
546 /// colliders `filter` admits. Triggers are still reported.
547 pub fn overlap_sphere_filtered_into(
548 &self,
549 centre: DVec3,
550 radius: f64,
551 filter: QueryFilter,
552 scratch: &mut QueryScratch,
553 out: &mut Vec<(ColliderId, OverlapHit)>,
554 ) {
555 out.clear();
556 overlap_sphere_core(
557 self.bvh,
558 self.colliders,
559 self.generations,
560 &Sphere::new(centre, radius),
561 filter,
562 scratch,
563 |id, hit| out.push((id, hit)),
564 );
565 }
566
567 /// [`overlap_sphere_into`](Self::overlap_sphere_into) naming the colliders
568 /// and dropping their hits: the same colliders in the same order, because
569 /// it is the same traversal and the same measurement, written into ids.
570 ///
571 /// **The fast path for a caller that never reads a hit**, and it exists
572 /// because one measured it: on 2026-10-05 `crcbl bench --scenario phys`,
573 /// which stands in for `apps/horde`'s steering pass, ran its query phase
574 /// about a fifth slower answering hits at a crowd of twenty-eight
575 /// neighbours a query, and this form gave back most of that — the record
576 /// is in `docs/backlog.md`.
577 /// The depth is still worked out, because a positive depth is what decides
578 /// a hit; the normal, the point and the bigger buffer are what it saves.
579 pub fn overlap_sphere_ids_into(
580 &self,
581 centre: DVec3,
582 radius: f64,
583 scratch: &mut QueryScratch,
584 out: &mut Vec<ColliderId>,
585 ) {
586 out.clear();
587 overlap_sphere_core(
588 self.bvh,
589 self.colliders,
590 self.generations,
591 &Sphere::new(centre, radius),
592 QueryFilter::ALL,
593 scratch,
594 |id, _| out.push(id),
595 );
596 }
597
598 /// [`PhysicsWorld::overlap_aabb`] under a shared borrow, working in
599 /// `scratch` and writing into a buffer the caller owns.
600 ///
601 /// `out` is cleared and then filled, with the same ids in the same tree
602 /// order the `&mut self` form produces, because the two are one
603 /// implementation and not two that agree.
604 pub fn overlap_aabb_into(
605 &self,
606 aabb: &Aabb,
607 scratch: &mut QueryScratch,
608 out: &mut Vec<ColliderId>,
609 ) {
610 self.overlap_aabb_filtered_into(aabb, QueryFilter::ALL, scratch, out);
611 }
612
613 /// [`overlap_aabb_into`](Self::overlap_aabb_into) reporting only the
614 /// colliders `filter` admits. Triggers are still reported.
615 pub fn overlap_aabb_filtered_into(
616 &self,
617 aabb: &Aabb,
618 filter: QueryFilter,
619 scratch: &mut QueryScratch,
620 out: &mut Vec<ColliderId>,
621 ) {
622 overlap_aabb_core(
623 self.bvh,
624 self.colliders,
625 self.generations,
626 aabb,
627 filter,
628 scratch,
629 out,
630 );
631 }
632
633 /// [`PhysicsWorld::cast_ray`] under a shared borrow, working in `scratch`
634 /// instead of the world's own buffers.
635 ///
636 /// Triggers are skipped and the closest exact hit wins, exactly as in the
637 /// `&mut self` form, because the two are one implementation.
638 #[must_use]
639 pub fn cast_ray(
640 &self,
641 ray: &Ray,
642 scratch: &mut QueryScratch,
643 ) -> Option<(ColliderId, ShapeHit)> {
644 self.cast_ray_excluding(ray, None, scratch)
645 }
646
647 /// [`PhysicsWorld::cast_ray_excluding`] under a shared borrow, working in
648 /// `scratch` instead of the world's own buffers.
649 ///
650 /// This leaves one live collider out of the narrow phase while preserving
651 /// the closest hit behind it. The shared and `&mut self` forms call the
652 /// same implementation.
653 #[must_use]
654 pub fn cast_ray_excluding(
655 &self,
656 ray: &Ray,
657 exclude: Option<ColliderId>,
658 scratch: &mut QueryScratch,
659 ) -> Option<(ColliderId, ShapeHit)> {
660 self.cast_ray_filtered(ray, QueryFilter::excluding(exclude), scratch)
661 }
662
663 /// [`PhysicsWorld::cast_ray_filtered`] under a shared borrow, working in
664 /// `scratch` instead of the world's own buffers.
665 #[must_use]
666 pub fn cast_ray_filtered(
667 &self,
668 ray: &Ray,
669 filter: QueryFilter,
670 scratch: &mut QueryScratch,
671 ) -> Option<(ColliderId, ShapeHit)> {
672 cast_ray_core(
673 self.bvh,
674 self.colliders,
675 self.generations,
676 ray,
677 filter,
678 scratch,
679 )
680 }
681
682 /// [`PhysicsWorld::sweep_sphere`] under a shared borrow, working in
683 /// `scratch` instead of the world's own buffers.
684 #[must_use]
685 pub fn sweep_sphere(
686 &self,
687 segment: &Segment,
688 radius: f64,
689 scratch: &mut QueryScratch,
690 ) -> Option<(ColliderId, ShapeHit)> {
691 self.sweep_sphere_excluding(segment, radius, None, scratch)
692 }
693
694 /// [`PhysicsWorld::sweep_sphere_excluding`] under a shared borrow, working
695 /// in `scratch` instead of the world's own buffers.
696 ///
697 /// This is the form a body sweeping its own path needs — see the `&mut
698 /// self` method for why the exclusion happens in the narrow phase and not
699 /// after the fact. The two forms are one implementation.
700 #[must_use]
701 pub fn sweep_sphere_excluding(
702 &self,
703 segment: &Segment,
704 radius: f64,
705 exclude: Option<ColliderId>,
706 scratch: &mut QueryScratch,
707 ) -> Option<(ColliderId, ShapeHit)> {
708 self.sweep_sphere_filtered(segment, radius, QueryFilter::excluding(exclude), scratch)
709 }
710
711 /// [`PhysicsWorld::sweep_sphere_filtered`] under a shared borrow, working
712 /// in `scratch` instead of the world's own buffers.
713 #[must_use]
714 pub fn sweep_sphere_filtered(
715 &self,
716 segment: &Segment,
717 radius: f64,
718 filter: QueryFilter,
719 scratch: &mut QueryScratch,
720 ) -> Option<(ColliderId, ShapeHit)> {
721 let mut closest = None;
722 sweep_sphere_hits(*self, segment, radius, filter, scratch, |id, hit| {
723 keep_closest(&mut closest, id, hit);
724 });
725 closest
726 }
727
728 /// [`PhysicsWorld::sweep_capsule`] under a shared borrow, working in
729 /// `scratch` instead of the world's own buffers.
730 #[must_use]
731 pub fn sweep_capsule(
732 &self,
733 segment: &Segment,
734 radius: f64,
735 half_height: f64,
736 scratch: &mut QueryScratch,
737 ) -> Option<(ColliderId, ShapeHit)> {
738 self.sweep_capsule_excluding(segment, radius, half_height, None, scratch)
739 }
740
741 /// [`PhysicsWorld::sweep_capsule_excluding`] under a shared borrow, working
742 /// in `scratch` instead of the world's own buffers.
743 ///
744 /// This is the form a character controller needs, and it excludes in the
745 /// narrow phase for the reason the sphere form gives. The two forms are one
746 /// implementation.
747 #[must_use]
748 pub fn sweep_capsule_excluding(
749 &self,
750 segment: &Segment,
751 radius: f64,
752 half_height: f64,
753 exclude: Option<ColliderId>,
754 scratch: &mut QueryScratch,
755 ) -> Option<(ColliderId, ShapeHit)> {
756 self.sweep_capsule_filtered(
757 segment,
758 radius,
759 half_height,
760 QueryFilter::excluding(exclude),
761 scratch,
762 )
763 }
764
765 /// [`PhysicsWorld::sweep_capsule_filtered`] under a shared borrow, working
766 /// in `scratch` instead of the world's own buffers.
767 #[must_use]
768 pub fn sweep_capsule_filtered(
769 &self,
770 segment: &Segment,
771 radius: f64,
772 half_height: f64,
773 filter: QueryFilter,
774 scratch: &mut QueryScratch,
775 ) -> Option<(ColliderId, ShapeHit)> {
776 let capsule = Capsule::new(segment.start, radius, half_height);
777 self.sweep_upright_where(&capsule, segment.end, filter, scratch, |_| true)
778 }
779
780 /// [`PhysicsWorld::capsule_penetrations_into`] under a shared borrow,
781 /// working in `scratch` instead of the world's own buffers.
782 pub fn capsule_penetrations_into(
783 &self,
784 capsule: &Capsule,
785 exclude: Option<ColliderId>,
786 scratch: &mut QueryScratch,
787 out: &mut Vec<(ColliderId, Penetration)>,
788 ) {
789 self.capsule_penetrations_filtered_into(
790 capsule,
791 QueryFilter::excluding(exclude),
792 scratch,
793 out,
794 );
795 }
796
797 /// [`PhysicsWorld::capsule_penetrations_filtered_into`] under a shared
798 /// borrow, working in `scratch` instead of the world's own buffers.
799 pub fn capsule_penetrations_filtered_into(
800 &self,
801 capsule: &Capsule,
802 filter: QueryFilter,
803 scratch: &mut QueryScratch,
804 out: &mut Vec<(ColliderId, Penetration)>,
805 ) {
806 capsule_penetrations_core(
807 self.bvh,
808 self.colliders,
809 self.generations,
810 capsule,
811 filter,
812 scratch,
813 out,
814 );
815 }
816
817 /// The push-out normal of every surface an upright `capsule` is inside,
818 /// appended to `out`: one per sphere, box or capsule primitive, and one per
819 /// **triangle** of a mesh, where
820 /// [`capsule_penetrations_filtered_into`](Self::capsule_penetrations_filtered_into)
821 /// keeps a collider's deepest. What a character wedged between two faces
822 /// of one mesh stands on is both of them. Triggers and the filter's
823 /// exclusions are skipped as there.
824 pub(crate) fn capsule_contact_normals_into(
825 &self,
826 capsule: &Capsule,
827 filter: QueryFilter,
828 scratch: &mut QueryScratch,
829 out: &mut Vec<DVec3>,
830 ) {
831 let filter = ResolvedFilter::solid(self.colliders, self.generations, filter);
832 filter.candidates(self.bvh, &capsule.aabb(), scratch);
833 for &element in scratch.candidates.iter() {
834 let idx = element as usize;
835 let Some(Some(slot)) = self.colliders.get(idx) else {
836 continue;
837 };
838 if !filter.admits(idx, slot) {
839 continue;
840 }
841 for (_, shape) in slot.entry.primitives() {
842 let penetration = match shape {
843 Primitive::Sphere(s) => query::capsule_penetration_vs_sphere(capsule, s),
844 Primitive::Box(b) => query::capsule_penetration_vs_box(capsule, b),
845 Primitive::Capsule(c) => {
846 query::capsule_penetration_vs_turned_capsule(capsule, c)
847 }
848 Primitive::Mesh(m) => {
849 m.capsule_contact_normals(capsule, &mut scratch.mesh, out);
850 None
851 }
852 };
853 out.extend(penetration.map(|penetration| penetration.normal));
854 }
855 }
856 }
857
858 /// [`PhysicsWorld::lying_capsule_blocker`] under a shared borrow, working
859 /// in `scratch` instead of the world's own buffers.
860 #[must_use]
861 pub fn lying_capsule_blocker(
862 &self,
863 capsule: &LyingCapsule,
864 filter: QueryFilter,
865 scratch: &mut QueryScratch,
866 ) -> Option<ColliderId> {
867 lying_capsule_blocker_core(
868 self.bvh,
869 self.colliders,
870 self.generations,
871 capsule,
872 filter,
873 scratch,
874 )
875 }
876
877 /// What a [`LyingCapsule`] moved by `motion`, without turning, meets first
878 /// among the solid colliders `filter` admits, and how far along the motion
879 /// it gets: the sweep [`crate::CharacterController::move_lying`] slides
880 /// with. Uses the shared oriented-capsule sweep.
881 pub(crate) fn sweep_lying_capsule(
882 &self,
883 capsule: &LyingCapsule,
884 motion: DVec3,
885 filter: QueryFilter,
886 scratch: &mut QueryScratch,
887 ) -> Option<(ColliderId, SweptContact)> {
888 self.sweep_capsule_shape(
889 CapsuleSweepShape::Lying(*capsule),
890 motion,
891 filter,
892 scratch,
893 |_| true,
894 )
895 .map(|(id, hit)| (id, hit.contact))
896 }
897}
898
899/// The one implementation of "which colliders overlap this sphere, and how".
900///
901/// Both the `&mut self` form and [`OverlapQueries`] come through here, so there
902/// is no second copy of the traversal for the two to disagree in — which
903/// matters more than usual, because a caller mixing the two in one pass is
904/// exactly what a `par_for` adoption looks like mid-migration. Each hit is
905/// handed to `keep`, in order, so the ids-only form
906/// ([`OverlapQueries::overlap_sphere_ids_into`]) is this one too, keeping less.
907///
908/// # Shape-aware: `radius` is expanded by each collider's own shape
909///
910/// The query sphere is measured against every collider's *shape* (see
911/// `query::sphere_overlap_vs_*`), not against its centre. A sphere collider of
912/// radius `r_b` is therefore returned iff its centre is within
913/// `radius + r_b` of `centre`, which is what makes `apps/horde`'s
914/// `separation_query_radius` correct without adding the neighbour's radius to
915/// the query. `tests::a_sphere_overlap_is_expanded_by_the_colliders_own_radius`
916/// pins the boundary.
917///
918/// # One hit per collider, the deepest
919///
920/// A hit is a positive depth: a collider the sphere only touches is not
921/// returned (see [`OverlapHit`]). A compound is one entry, its deepest part's
922/// hit; of two parts equally deep, the lower — the rule
923/// [`capsule_penetrations_core`] keeps. Triggers are reported, and the order
924/// is the tree's traversal order, which is a pure function of the world.
925///
926/// The query is one [`Sphere`] argument rather than a centre and a radius, as
927/// the capsule sweep's is one [`Capsule`].
928fn overlap_sphere_core(
929 bvh: &Bvh,
930 colliders: &[Option<ColliderSlot>],
931 generations: &[u32],
932 query_sphere: &Sphere,
933 filter: QueryFilter,
934 scratch: &mut QueryScratch,
935 mut keep: impl FnMut(ColliderId, OverlapHit),
936) {
937 let filter = ResolvedFilter::overlap(colliders, generations, filter);
938 let query_aabb = Aabb::from_centre_half(query_sphere.centre, DVec3::splat(query_sphere.radius));
939
940 filter.candidates(bvh, &query_aabb, scratch);
941
942 for &element in scratch.candidates.iter() {
943 let idx = element as usize;
944 let Some(Some(slot)) = colliders.get(idx) else {
945 continue;
946 };
947 if !filter.admits(idx, slot) {
948 continue;
949 }
950 let mut deepest: Option<OverlapHit> = None;
951 for (part, shape) in slot.entry.primitives() {
952 let hit = match shape {
953 Primitive::Sphere(s) => query::sphere_overlap_vs_sphere(query_sphere, s),
954 Primitive::Box(b) => query::sphere_overlap_vs_box(query_sphere, b),
955 Primitive::Capsule(c) => query::sphere_overlap_vs_turned_capsule(query_sphere, c),
956 Primitive::Mesh(m) => m.sphere_overlap(query_sphere, &mut scratch.mesh),
957 };
958 if let Some(hit) = hit
959 && deepest.is_none_or(|deepest| hit.depth > deepest.depth)
960 {
961 deepest = Some(OverlapHit { part, ..hit });
962 }
963 }
964 if let Some(hit) = deepest {
965 keep(id_for_slot_in(generations, element), hit);
966 }
967 }
968}
969
970/// The one implementation of "which colliders meet this AABB".
971///
972/// A box, turned or not, is refined against the box itself
973/// ([`query::aabb_overlaps_box`]), and so is each part of a compound, whose
974/// leaf is the bounds of all its parts. A mesh's leaf is the bounds of a
975/// whole level, which would meet every query, so a mesh is refined against
976/// its triangles, exactly. A sphere and a capsule are broadphase-only: their
977/// leaves are their bounds, and a query meeting a corner of those bounds
978/// reports them though it misses the round surface. Both
979/// [`PhysicsWorld::overlap_aabb`] and [`OverlapQueries::overlap_aabb_into`]
980/// come through here.
981fn overlap_aabb_core(
982 bvh: &Bvh,
983 colliders: &[Option<ColliderSlot>],
984 generations: &[u32],
985 aabb: &Aabb,
986 filter: QueryFilter,
987 scratch: &mut QueryScratch,
988 out: &mut Vec<ColliderId>,
989) {
990 let filter = ResolvedFilter::overlap(colliders, generations, filter);
991 filter.candidates(bvh, aabb, scratch);
992 out.clear();
993 for &slot in &scratch.candidates {
994 let admitted = colliders
995 .get(slot as usize)
996 .and_then(|s| s.as_ref())
997 .filter(|data| filter.admits(slot as usize, data))
998 .is_some_and(|data| {
999 data.entry.primitives().any(|(_, shape)| match shape {
1000 Primitive::Mesh(m) => m.overlaps_aabb(aabb, &mut scratch.mesh),
1001 Primitive::Box(b) => query::aabb_overlaps_box(aabb, b),
1002 Primitive::Sphere(_) | Primitive::Capsule(_) => true,
1003 })
1004 });
1005 if admitted {
1006 out.push(id_for_slot_in(generations, slot));
1007 }
1008 }
1009}
1010
1011/// The one implementation of "what does this ray hit first".
1012///
1013/// Both [`PhysicsWorld::cast_ray_filtered`] and
1014/// [`OverlapQueries::cast_ray_filtered`] come through here — and so do the
1015/// `cast_ray` and `cast_ray_excluding` forms, which are this with a narrower
1016/// filter. Triggers are non-solid and are skipped by `closest_hit_core`.
1017fn cast_ray_core(
1018 bvh: &Bvh,
1019 colliders: &[Option<ColliderSlot>],
1020 generations: &[u32],
1021 ray: &Ray,
1022 filter: QueryFilter,
1023 scratch: &mut QueryScratch,
1024) -> Option<(ColliderId, ShapeHit)> {
1025 // Out of the scratch and back into it, because the descent borrows the
1026 // stack at the same time and the two are fields of one struct.
1027 let filter = ResolvedFilter::solid(colliders, generations, filter);
1028 let mut hits = core::mem::take(&mut scratch.ray_hits);
1029 bvh.traverse_ray_masked_into(ray, filter.mask, &mut scratch.stack, &mut hits);
1030 let best = closest_hit_core(
1031 colliders,
1032 generations,
1033 ray,
1034 &hits,
1035 filter,
1036 &mut scratch.mesh,
1037 );
1038 scratch.ray_hits = hits;
1039 best
1040}
1041
1042/// The one implementation of "what does this swept sphere hit": every
1043/// admitted collider it meets, handed to `visit` with its exact hit.
1044///
1045/// Both [`PhysicsWorld::sweep_sphere_filtered`] and
1046/// [`OverlapQueries::sweep_sphere_filtered`] come through here, keeping the
1047/// closest — and so do the `sweep_sphere` and `sweep_sphere_excluding` forms,
1048/// which are this with a narrower filter, and
1049/// [`PhysicsWorld::sweep_sphere_all`], which keeps them all.
1050///
1051/// The broadphase query is the swept *volume* and not the centre line; see
1052/// [`PhysicsWorld::sweep_sphere`] for what that costs and what it fixes.
1053fn sweep_sphere_hits(
1054 view: OverlapQueries<'_>,
1055 segment: &Segment,
1056 radius: f64,
1057 filter: QueryFilter,
1058 scratch: &mut QueryScratch,
1059 visit: impl FnMut(ColliderId, ShapeHit),
1060) {
1061 let filter = ResolvedFilter::solid(view.colliders, view.generations, filter);
1062 let bounds = swept_bounds(segment, DVec3::splat(radius));
1063 filter.candidates(view.bvh, &bounds, scratch);
1064 swept_hits_core(
1065 view.colliders,
1066 view.generations,
1067 &scratch.candidates,
1068 filter,
1069 |_, _, shape| match shape {
1070 Primitive::Sphere(s) => query::swept_sphere_vs_sphere(segment, radius, s),
1071 Primitive::Box(b) => query::swept_sphere_vs_box(segment, radius, b),
1072 Primitive::Capsule(c) => query::swept_sphere_vs_turned_capsule(segment, radius, c),
1073 Primitive::Mesh(m) => m.sweep(segment, radius, DVec3::ZERO, &mut scratch.mesh),
1074 },
1075 visit,
1076 );
1077}
1078
1079/// The one implementation of "what does this swept Y-aligned capsule hit":
1080/// `capsule` sits at the start of the sweep and its centre travels to `end`,
1081/// and every admitted collider it meets is handed to `visit` with its exact
1082/// hit.
1083///
1084/// Both [`PhysicsWorld::sweep_capsule_filtered`] and
1085/// [`OverlapQueries::sweep_capsule_filtered`] come through here, keeping the
1086/// closest — and so do the `sweep_capsule` and `sweep_capsule_excluding`
1087/// forms, which are this with a narrower filter, and
1088/// [`PhysicsWorld::sweep_capsule_all`], which keeps them all. They take a
1089/// [`Segment`] and a radius the way the sphere sweeps do; the shape is one
1090/// argument here so that the swept capsule's two dimensions travel together.
1091///
1092/// The broadphase query is the swept *volume*, for the reason
1093/// [`PhysicsWorld::sweep_sphere`] gives: the capsule is `radius` wide and
1094/// `half_height + radius` tall, so the candidates are everything within that of
1095/// the path its centre takes.
1096fn sweep_capsule_hits(
1097 view: OverlapQueries<'_>,
1098 capsule: &Capsule,
1099 end: DVec3,
1100 filter: QueryFilter,
1101 scratch: &mut QueryScratch,
1102 accept: impl Fn(&ShapeHit) -> bool,
1103 visit: impl FnMut(ColliderId, ShapeHit),
1104) {
1105 let Capsule {
1106 radius,
1107 half_height,
1108 ..
1109 } = *capsule;
1110 let segment = &Segment::new(capsule.centre, end);
1111 let filter = ResolvedFilter::solid(view.colliders, view.generations, filter);
1112 let bounds = swept_bounds(segment, DVec3::new(radius, radius + half_height, radius));
1113 filter.candidates(view.bvh, &bounds, scratch);
1114 swept_hits_core(
1115 view.colliders,
1116 view.generations,
1117 &scratch.candidates,
1118 filter,
1119 |_, _, shape| {
1120 let hit = match shape {
1121 Primitive::Sphere(s) => {
1122 query::swept_capsule_vs_sphere(segment, radius, half_height, s)
1123 }
1124 Primitive::Box(b) => query::swept_capsule_vs_box(segment, radius, half_height, b),
1125 Primitive::Capsule(c) => {
1126 query::swept_capsule_vs_turned_capsule(segment, radius, half_height, c)
1127 }
1128 Primitive::Mesh(m) => m.sweep_where(
1129 segment,
1130 radius,
1131 DVec3::Y * half_height,
1132 &mut scratch.mesh,
1133 &accept,
1134 ),
1135 }?;
1136 accept(&hit).then_some(hit)
1137 },
1138 visit,
1139 );
1140}
1141
1142/// The one implementation of "what is this capsule inside, and how far out does
1143/// each one need it pushed".
1144///
1145/// Both [`PhysicsWorld::capsule_penetrations_filtered_into`] and
1146/// [`OverlapQueries::capsule_penetrations_filtered_into`] come through here,
1147/// and so do the two unfiltered forms.
1148///
1149/// Triggers are non-solid and are skipped, and so is the filter's exclusion —
1150/// a character whose own capsule is registered in the world is inside itself
1151/// by the whole of its own radius, which is the deepest contact it would ever
1152/// find. A compound is one entry, its deepest part's push-out; of two parts
1153/// equally deep, the lower.
1154fn capsule_penetrations_core(
1155 bvh: &Bvh,
1156 colliders: &[Option<ColliderSlot>],
1157 generations: &[u32],
1158 capsule: &Capsule,
1159 filter: QueryFilter,
1160 scratch: &mut QueryScratch,
1161 out: &mut Vec<(ColliderId, Penetration)>,
1162) {
1163 out.clear();
1164 let filter = ResolvedFilter::solid(colliders, generations, filter);
1165 filter.candidates(bvh, &capsule.aabb(), scratch);
1166
1167 for &element in scratch.candidates.iter() {
1168 let idx = element as usize;
1169 let Some(Some(slot)) = colliders.get(idx) else {
1170 continue;
1171 };
1172 if !filter.admits(idx, slot) {
1173 continue;
1174 }
1175 let mut deepest: Option<Penetration> = None;
1176 for (_, shape) in slot.entry.primitives() {
1177 let penetration = match shape {
1178 Primitive::Sphere(s) => query::capsule_penetration_vs_sphere(capsule, s),
1179 Primitive::Box(b) => query::capsule_penetration_vs_box(capsule, b),
1180 Primitive::Capsule(c) => query::capsule_penetration_vs_turned_capsule(capsule, c),
1181 Primitive::Mesh(m) => m.capsule_penetration(capsule, &mut scratch.mesh),
1182 };
1183 if let Some(penetration) = penetration
1184 && deepest.is_none_or(|deepest| penetration.depth > deepest.depth)
1185 {
1186 deepest = Some(penetration);
1187 }
1188 }
1189 if let Some(penetration) = deepest {
1190 out.push((id_for_slot_in(generations, element), penetration));
1191 }
1192 }
1193}
1194
1195/// The one implementation of "is this lying capsule inside anything solid".
1196///
1197/// Both [`PhysicsWorld::lying_capsule_blocker`] and
1198/// [`OverlapQueries::lying_capsule_blocker`] come through here.
1199///
1200/// The parametric shapes are measured by the contact pipeline's own [`gap`],
1201/// which already takes a capsule at any angle: the lying capsule is its core
1202/// segment from head to feet, and the query world's shapes are placed as that
1203/// pipeline places them — a box turned as its collider is, a capsule along
1204/// `+Y`. A mesh
1205/// is measured by its own capsule push-out, turned to lie along the core.
1206/// Either way it is a *penetration* that blocks, as in
1207/// [`capsule_penetrations_core`]: a shape the capsule only touches does not.
1208fn lying_capsule_blocker_core(
1209 bvh: &Bvh,
1210 colliders: &[Option<ColliderSlot>],
1211 generations: &[u32],
1212 capsule: &LyingCapsule,
1213 filter: QueryFilter,
1214 scratch: &mut QueryScratch,
1215) -> Option<ColliderId> {
1216 let filter = ResolvedFilter::solid(colliders, generations, filter);
1217 filter.candidates(bvh, &capsule.aabb(), scratch);
1218
1219 let (head, feet) = (capsule.head, capsule.feet());
1220 let lying = ContactShape::Capsule {
1221 a: head,
1222 b: feet,
1223 radius: capsule.radius,
1224 };
1225 let inside = |target: ContactShape| gap(&lying, &target).0 < 0.0;
1226
1227 for &element in scratch.candidates.iter() {
1228 let idx = element as usize;
1229 let Some(Some(slot)) = colliders.get(idx) else {
1230 continue;
1231 };
1232 if !filter.admits(idx, slot) {
1233 continue;
1234 }
1235 let blocked = slot.entry.primitives().any(|(_, shape)| match shape {
1236 Primitive::Sphere(s) => inside(ContactShape::Sphere {
1237 centre: s.centre,
1238 radius: s.radius,
1239 }),
1240 Primitive::Box(b) => inside(query::contact_box(b)),
1241 Primitive::Capsule(c) => inside(c.contact_shape()),
1242 Primitive::Mesh(m) => m
1243 .turned_capsule_penetration(
1244 (head + feet) * 0.5,
1245 (head - feet) * 0.5,
1246 capsule.radius,
1247 &mut scratch.mesh,
1248 )
1249 .is_some(),
1250 });
1251 if blocked {
1252 return Some(id_for_slot_in(generations, element));
1253 }
1254 }
1255 None
1256}
1257
1258/// Where a sweep that reports no contact point met a collider:
1259/// [`OverlapQueries::sweep_lying_capsule`]'s answer.
1260#[derive(Debug, Clone, Copy, PartialEq)]
1261pub(crate) struct SweptContact {
1262 /// The share of the motion covered before the contact, in `[0, 1]`.
1263 pub(crate) t: f64,
1264 /// Unit normal pointing away from the surface met, toward the swept shape.
1265 pub(crate) normal: DVec3,
1266 /// Whether the swept shape began already touching or inside the collider,
1267 /// as [`ShapeHit::started_inside`] means it; `t` is then zero.
1268 pub(crate) started_inside: bool,
1269 /// The part of the collider met, as [`ShapeHit::part`] means it.
1270 pub(crate) part: usize,
1271}
1272
1273impl From<ShapeHit> for SweptContact {
1274 fn from(hit: ShapeHit) -> Self {
1275 Self {
1276 t: hit.t,
1277 normal: hit.normal,
1278 started_inside: hit.started_inside,
1279 part: hit.part,
1280 }
1281 }
1282}
1283
1284/// The broadphase bounds of a sweep: the box the segment covers, grown by the
1285/// swept shape's half-extents so the traversal offers the narrow phase every
1286/// collider the *volume* touches and not only the ones its centre line runs
1287/// through.
1288fn swept_bounds(segment: &Segment, half_extents: DVec3) -> Aabb {
1289 Aabb::new(
1290 segment.start.min(segment.end) - half_extents,
1291 segment.start.max(segment.end) + half_extents,
1292 )
1293}
1294
1295/// Given BVH hits (AABB-level), find the closest exact hit using shape-level
1296/// intersection, over the colliders `filter` admits — which skips triggers.
1297fn closest_hit_core(
1298 colliders: &[Option<ColliderSlot>],
1299 generations: &[u32],
1300 ray: &Ray,
1301 bvh_hits: &[BvhHit],
1302 filter: ResolvedFilter,
1303 mesh: &mut MeshScratch,
1304) -> Option<(ColliderId, ShapeHit)> {
1305 let mut best: Option<(f64, ColliderId, ShapeHit)> = None;
1306 for bvh_hit in bvh_hits {
1307 let idx = bvh_hit.element_id as usize;
1308 let Some(Some(slot)) = colliders.get(idx) else {
1309 continue;
1310 };
1311 if !filter.admits(idx, slot) {
1312 continue;
1313 }
1314 for (part, shape) in slot.entry.primitives() {
1315 let hit = match shape {
1316 Primitive::Sphere(s) => query::ray_vs_sphere(ray, s),
1317 Primitive::Box(b) => query::ray_vs_box(ray, b),
1318 Primitive::Capsule(c) => query::ray_vs_turned_capsule(ray, c),
1319 Primitive::Mesh(m) => m.cast_ray(ray, mesh),
1320 };
1321 if let Some(hit) = hit
1322 && hit.t < best.as_ref().map_or(f64::INFINITY, |&(t, _, _)| t)
1323 {
1324 let id = id_for_slot_in(generations, bvh_hit.element_id);
1325 best = Some((hit.t, id, ShapeHit { part, ..hit }));
1326 }
1327 }
1328 }
1329 best.map(|(_, id, hit)| (id, hit))
1330}
1331
1332/// Given broadphase candidates, hand `visit` every exact swept hit, with
1333/// `narrow` supplying the shape-level TOI for whichever shape is being swept,
1334/// over the colliders `filter` admits — which skips triggers.
1335///
1336/// The sphere, capsule and lying capsule sweeps share this rather than each
1337/// carrying a copy: what a trigger, a dead slot, an excluded collider and a
1338/// layer mask mean is one rule, and a second copy of it is where they would
1339/// drift. The closest sweeps keep one of the hits it hands over
1340/// ([`keep_closest`]) and the candidate sweeps keep them all, so the two
1341/// agree on which hits there are.
1342///
1343/// A hit whose `t` is not below infinity — a `NaN` from degenerate input —
1344/// ranks against nothing, and is no hit.
1345fn swept_hits_core<H: SweptHit>(
1346 colliders: &[Option<ColliderSlot>],
1347 generations: &[u32],
1348 candidates: &[u32],
1349 filter: ResolvedFilter,
1350 mut narrow: impl FnMut(ColliderId, usize, Primitive<'_>) -> Option<H>,
1351 mut visit: impl FnMut(ColliderId, H),
1352) {
1353 for &element in candidates {
1354 let idx = element as usize;
1355 let Some(Some(slot)) = colliders.get(idx) else {
1356 continue;
1357 };
1358 if !filter.admits(idx, slot) {
1359 continue;
1360 }
1361 for (part, shape) in slot.entry.primitives() {
1362 if let Some(hit) = narrow(id_for_slot_in(generations, element), part, shape)
1363 && hit.t() < f64::INFINITY
1364 {
1365 visit(id_for_slot_in(generations, element), hit.with_part(part));
1366 }
1367 }
1368 }
1369}
1370
1371/// [`swept_hits_core`] keeping only the hit that comes first by
1372/// [`sweep_order`]: the lying capsule sweep's closest hit.
1373fn closest_swept_core<H: SweptHit>(
1374 colliders: &[Option<ColliderSlot>],
1375 generations: &[u32],
1376 candidates: &[u32],
1377 filter: ResolvedFilter,
1378 mut narrow: impl FnMut(Primitive<'_>) -> Option<H>,
1379) -> Option<(ColliderId, H)> {
1380 let mut closest = None;
1381 swept_hits_core(
1382 colliders,
1383 generations,
1384 candidates,
1385 filter,
1386 |_, _, shape| narrow(shape),
1387 |id, hit| {
1388 keep_closest(&mut closest, id, hit);
1389 },
1390 );
1391 closest
1392}
1393
1394/// Replace `closest` with `(id, hit)` if that comes first by [`sweep_order`].
1395fn keep_closest<H: SweptHit>(closest: &mut Option<(ColliderId, H)>, id: ColliderId, hit: H) {
1396 if closest.as_ref().is_none_or(|&(best, best_hit)| {
1397 sweep_order(
1398 (id, hit.part_index(), hit.t()),
1399 (best, best_hit.part_index(), best_hit.t()),
1400 )
1401 .is_lt()
1402 }) {
1403 *closest = Some((id, hit));
1404 }
1405}
1406
1407/// The order a sweep's hits come in: nearer `t` first, of two at the same
1408/// `t` the one in the lower storage slot, and of two parts of one compound
1409/// at the same `t` the lower part.
1410///
1411/// The tie needs a rule because the alternative is the order the broadphase
1412/// happened to offer the candidates in, which follows the tree's shape and so
1413/// the world's history of adds, refits and rebuilds. A slot index is stable
1414/// for the collider's whole life. The closest sweeps and the candidate sweeps
1415/// both rank by this, which is what makes the candidate list's first entry
1416/// the closest sweep's answer.
1417fn sweep_order(a: (ColliderId, usize, f64), b: (ColliderId, usize, f64)) -> std::cmp::Ordering {
1418 if a.2 < b.2 {
1419 std::cmp::Ordering::Less
1420 } else if b.2 < a.2 {
1421 std::cmp::Ordering::Greater
1422 } else {
1423 (a.0.index, a.1).cmp(&(b.0.index, b.1))
1424 }
1425}
1426
1427/// What [`closest_swept_core`] ranks a sweep's hits by: how far along the
1428/// sweep each one is, and which part of its collider it met.
1429trait SweptHit: Copy {
1430 fn t(&self) -> f64;
1431 fn part_index(&self) -> usize;
1432 /// This hit, on part `part` of its collider.
1433 #[must_use]
1434 fn with_part(self, part: usize) -> Self;
1435}
1436
1437impl SweptHit for ShapeHit {
1438 fn t(&self) -> f64 {
1439 self.t
1440 }
1441
1442 fn part_index(&self) -> usize {
1443 self.part
1444 }
1445
1446 fn with_part(self, part: usize) -> Self {
1447 Self { part, ..self }
1448 }
1449}
1450
1451impl SweptHit for SweptContact {
1452 fn t(&self) -> f64 {
1453 self.t
1454 }
1455
1456 fn part_index(&self) -> usize {
1457 self.part
1458 }
1459
1460 fn with_part(self, part: usize) -> Self {
1461 Self { part, ..self }
1462 }
1463}
1464
1465/// Resolve an id to a live storage slot, or `None` if the id is stale
1466/// (generation mismatch) or names an empty slot.
1467///
1468/// The free form of [`PhysicsWorld::slot_of`], which is what
1469/// `ResolvedFilter` needs: a shared view has the two arrays but not the world.
1470fn slot_of_in(
1471 colliders: &[Option<ColliderSlot>],
1472 generations: &[u32],
1473 id: ColliderId,
1474) -> Option<usize> {
1475 let slot = id.index as usize;
1476 if generations.get(slot).copied() != Some(id.generation) {
1477 return None;
1478 }
1479 colliders.get(slot).and_then(|s| s.as_ref()).map(|_| slot)
1480}
1481
1482/// The id currently naming `slot`. Only call with a slot the BVH just
1483/// reported, i.e. one that is live.
1484fn id_for_slot_in(generations: &[u32], slot: u32) -> ColliderId {
1485 ColliderId::new(slot, generations[slot as usize])
1486}
1487
1488impl PhysicsWorld {
1489 /// Create an empty physics world.
1490 #[must_use]
1491 pub fn new() -> Self {
1492 Self {
1493 colliders: Vec::new(),
1494 generations: Vec::new(),
1495 free_slots: Vec::new(),
1496 live_count: 0,
1497 bvh: None,
1498 bvh_quality_baseline: None,
1499 refits_since_quality_check: 0,
1500 counters: BroadphaseCounters::default(),
1501 bvh_slot_to_elem: Vec::new(),
1502 scratch: QueryScratch::new(),
1503 }
1504 }
1505
1506 /// Register a sphere collider. Returns a [`ColliderId`] that can be used
1507 /// to remove or update the collider later.
1508 ///
1509 /// # Adding does not cost a rebuild
1510 ///
1511 /// Once the BVH exists, a new collider is *inserted* into it
1512 /// ([`Bvh::insert`]) rather than the tree being dropped and rebuilt on the
1513 /// next query. A game that spawns and kills colliders every tick — a
1514 /// bullet per shot, two rocks per split — would otherwise pay `O(n log n)`
1515 /// per frame for a tree it had already built, and pay it again for the
1516 /// removal.
1517 ///
1518 /// Before the first query there is no tree, and adds simply accumulate: a
1519 /// world populated in one batch still gets one bulk [`Bvh::build`], which
1520 /// produces a better tree than the same elements inserted one at a time.
1521 pub fn add_sphere(&mut self, sphere: Sphere) -> ColliderId {
1522 self.add(ColliderEntry::Sphere(sphere))
1523 }
1524
1525 /// Register a box collider, turned or not: every query answers for the
1526 /// turned box itself ([`crate::query::ray_vs_box`] and its siblings), and
1527 /// the broadphase holds the world-axis box around it.
1528 pub fn add_box(&mut self, box_collider: BoxCollider) -> ColliderId {
1529 self.add(ColliderEntry::Box(box_collider))
1530 }
1531
1532 /// Register a capsule collider, standing up the world's `Y`.
1533 pub fn add_capsule(&mut self, capsule: Capsule) -> ColliderId {
1534 self.add(ColliderEntry::Capsule(TurnedCapsule::upright(capsule)))
1535 }
1536
1537 /// Register `capsule` turned by `rotation` about its centre, its core
1538 /// along `rotation * Y`, as the contact pipeline places a body's capsule.
1539 /// A turn that leaves the core along `Y` answers as
1540 /// [`add_capsule`](Self::add_capsule) does, to the bit.
1541 pub(crate) fn add_turned_capsule(&mut self, capsule: Capsule, rotation: DQuat) -> ColliderId {
1542 self.add(ColliderEntry::Capsule(TurnedCapsule::new(
1543 capsule, rotation,
1544 )))
1545 }
1546
1547 /// Register a triangle mesh, its vertices in the frame of `transform`.
1548 ///
1549 /// It is one entry in this world's tree, and every query that reaches its
1550 /// bounds descends the mesh's own tree and tests the triangles exactly:
1551 /// see [`TriangleMesh`]'s module docs. To a query a triangle has two
1552 /// sides, and a hit's normal faces the side the query came from.
1553 ///
1554 /// Queries see the mesh and the contact solver does not, so bodies fall
1555 /// through it: a mesh they must collide with is a static body's
1556 /// [`ColliderComponent::Mesh`](crate::ColliderComponent::Mesh). See
1557 /// [queries only](Self#queries-only-the-contact-solver-never-reads-this-world).
1558 pub fn add_mesh(&mut self, mesh: TriangleMesh, transform: Transform) -> ColliderId {
1559 self.add(ColliderEntry::Mesh(PlacedMesh::new(mesh, transform)))
1560 }
1561
1562 /// Register a [`CompoundShape`] `offset` from a body at `transform`: its
1563 /// parts placed as [`crate::ColliderComponent::Compound`] places them,
1564 /// turned with the body.
1565 ///
1566 /// It is one collider — one id, one trigger flag, one set of layers — and
1567 /// every query answers for its parts themselves, not for the world-axis
1568 /// box around them that the broadphase holds: a ray down the gap between
1569 /// two parts passes through. A hit names the part it met in
1570 /// [`ShapeHit::part`], an index into [`CompoundShape::parts`].
1571 pub fn add_compound(
1572 &mut self,
1573 shape: &CompoundShape,
1574 offset: DVec3,
1575 transform: &Transform,
1576 ) -> ColliderId {
1577 self.add(ColliderEntry::Compound(PlacedCompound::place(
1578 Vec::new(),
1579 shape,
1580 offset,
1581 transform,
1582 )))
1583 }
1584
1585 /// Update an existing sphere collider. Returns `true` if the id was valid.
1586 ///
1587 /// If the BVH is built, this refits the tree in O(log n). Otherwise the
1588 /// BVH is simply marked dirty for the next query.
1589 pub fn set_sphere(&mut self, id: ColliderId, sphere: Sphere) -> bool {
1590 self.set(id, ColliderEntry::Sphere(sphere))
1591 }
1592
1593 /// Update an existing box collider.
1594 pub fn set_box(&mut self, id: ColliderId, box_collider: BoxCollider) -> bool {
1595 self.set(id, ColliderEntry::Box(box_collider))
1596 }
1597
1598 /// Update an existing capsule collider, standing up the world's `Y`.
1599 pub fn set_capsule(&mut self, id: ColliderId, capsule: Capsule) -> bool {
1600 self.set(id, ColliderEntry::Capsule(TurnedCapsule::upright(capsule)))
1601 }
1602
1603 /// Update an existing collider to be `capsule` turned by `rotation`, as
1604 /// [`add_turned_capsule`](Self::add_turned_capsule) places it.
1605 pub(crate) fn set_turned_capsule(
1606 &mut self,
1607 id: ColliderId,
1608 capsule: Capsule,
1609 rotation: DQuat,
1610 ) -> bool {
1611 self.set(
1612 id,
1613 ColliderEntry::Capsule(TurnedCapsule::new(capsule, rotation)),
1614 )
1615 }
1616
1617 /// Update an existing collider to be `mesh` at `transform`.
1618 pub fn set_mesh(&mut self, id: ColliderId, mesh: TriangleMesh, transform: Transform) -> bool {
1619 self.set(id, ColliderEntry::Mesh(PlacedMesh::new(mesh, transform)))
1620 }
1621
1622 /// Update an existing collider to be `shape` `offset` from a body at
1623 /// `transform`, as [`add_compound`](Self::add_compound) places it.
1624 /// Returns `true` if the id was valid.
1625 ///
1626 /// A collider that was already a compound lends its parts' buffer to the
1627 /// new placement, so a moving compound placed every tick reuses one
1628 /// buffer rather than allocating a new one each time.
1629 pub fn set_compound(
1630 &mut self,
1631 id: ColliderId,
1632 shape: &CompoundShape,
1633 offset: DVec3,
1634 transform: &Transform,
1635 ) -> bool {
1636 let Some(slot) = self.slot_of(id) else {
1637 return false;
1638 };
1639 let buffer = match self.colliders[slot].as_mut().map(|s| &mut s.entry) {
1640 Some(ColliderEntry::Compound(placed)) => placed.take_parts(),
1641 _ => Vec::new(),
1642 };
1643 self.set(
1644 id,
1645 ColliderEntry::Compound(PlacedCompound::place(buffer, shape, offset, transform)),
1646 )
1647 }
1648
1649 /// Mark a collider as a trigger.
1650 ///
1651 /// A trigger is *non-solid*: [`PhysicsWorld::cast_ray`],
1652 /// [`PhysicsWorld::sweep_sphere`] and [`PhysicsWorld::sweep_capsule`] pass
1653 /// straight through it, while
1654 /// [`PhysicsWorld::overlap_sphere`] and [`PhysicsWorld::overlap_aabb`]
1655 /// still report it — that is what makes it an overlap-only volume.
1656 ///
1657 /// Returns `false` if the id is invalid.
1658 pub fn set_trigger(&mut self, id: ColliderId, is_trigger: bool) -> bool {
1659 let Some(slot) = self.slot_of(id) else {
1660 return false;
1661 };
1662 if let Some(slot_data) = self.colliders[slot].as_mut() {
1663 slot_data.is_trigger = is_trigger;
1664 }
1665 true
1666 }
1667
1668 /// Whether a collider is a trigger.
1669 pub fn is_trigger(&self, id: ColliderId) -> bool {
1670 self.slot_of(id)
1671 .is_some_and(|slot| self.colliders[slot].as_ref().is_some_and(|s| s.is_trigger))
1672 }
1673
1674 /// Put a collider on the query layers in `bits`, replacing whatever it was
1675 /// on. Returns `false` if the id is invalid.
1676 ///
1677 /// A layer is a bit, and a [`QueryFilter`]'s mask is the set of layers a
1678 /// query looks at: a collider is reported only when `bits & mask != 0`,
1679 /// or under [`LayerMatch::Within`] only when every bit is in the mask too.
1680 /// Every collider starts on [`ALL_LAYERS`], so a world that never calls
1681 /// this answers every query exactly as before. Layers survive
1682 /// [`set_sphere`](Self::set_sphere) and its siblings, as the trigger flag
1683 /// does; removing the collider drops them, and a new collider landing in
1684 /// the recycled slot starts on [`ALL_LAYERS`] again.
1685 ///
1686 /// Layers filter **queries** only — the ones on this world and the
1687 /// character controller's. They do not touch the contact solver, which
1688 /// never reads this world.
1689 ///
1690 /// A built tree takes the new bits in place ([`Bvh::set_layers`]): every
1691 /// node holds the union of its subtree's layers so a query can skip
1692 /// subtrees on none of its mask's, and a union left holding the old bits
1693 /// would hide this collider from a query for its new ones.
1694 pub fn set_layers(&mut self, id: ColliderId, bits: u32) -> bool {
1695 let Some(slot) = self.slot_of(id) else {
1696 return false;
1697 };
1698 if let Some(slot_data) = self.colliders[slot].as_mut() {
1699 slot_data.layers = bits;
1700 }
1701 if let Some(bvh) = self.bvh.as_mut() {
1702 let updated = match self.bvh_slot_to_elem.get(slot).copied() {
1703 Some(elem) if elem != NO_ELEMENT => bvh.set_layers(elem as usize, bits),
1704 _ => false,
1705 };
1706 // A live collider with no element in a built tree: the tree no
1707 // longer describes the collider set, as in `remove`.
1708 if !updated {
1709 self.invalidate_bvh();
1710 }
1711 }
1712 true
1713 }
1714
1715 /// The query layers a collider is on, or `None` if the id is invalid.
1716 #[must_use]
1717 pub fn layers(&self, id: ColliderId) -> Option<u32> {
1718 let slot = self.slot_of(id)?;
1719 self.colliders[slot].as_ref().map(|s| s.layers)
1720 }
1721
1722 /// Remove a collider by its id. Returns `true` if the id was valid.
1723 ///
1724 /// The slot is recycled, but its generation is bumped first, so `id` (and
1725 /// any copy of it) stops resolving even once a new collider lands there.
1726 ///
1727 /// If a BVH is built, the element is taken out of it incrementally rather
1728 /// than the tree being thrown away — see [`PhysicsWorld::add_sphere`] for
1729 /// why that matters.
1730 pub fn remove(&mut self, id: ColliderId) -> bool {
1731 let Some(slot) = self.slot_of(id) else {
1732 return false;
1733 };
1734 self.colliders[slot] = None;
1735 self.generations[slot] = self.generations[slot].wrapping_add(1);
1736 self.free_slots.push(slot as u32);
1737 self.live_count -= 1;
1738
1739 if let Some(bvh) = self.bvh.as_mut() {
1740 match self.bvh_slot_to_elem.get(slot).copied() {
1741 Some(elem) if elem != NO_ELEMENT && bvh.remove(elem as usize) => {
1742 self.bvh_slot_to_elem[slot] = NO_ELEMENT;
1743 self.bvh_quality_baseline = None;
1744 self.refits_since_quality_check = 0;
1745 }
1746 // A live collider with no element in a built tree should not
1747 // happen; if it ever does, the tree no longer describes the
1748 // collider set and querying it would report a ghost.
1749 _ => self.invalidate_bvh(),
1750 }
1751 }
1752 true
1753 }
1754
1755 /// Rebuild the BVH from the current set of colliders.
1756 ///
1757 /// Called automatically on the first query after an invalidation and when
1758 /// refits make the existing partition sufficiently loose. Explicitly
1759 /// calling this is only needed when you want to control the timing.
1760 pub fn rebuild(&mut self) {
1761 let elements: Vec<_> = self
1762 .colliders
1763 .iter()
1764 .enumerate()
1765 .filter_map(|(idx, slot)| {
1766 slot.as_ref()
1767 .map(|s| (s.entry.aabb(), idx as u32, s.layers))
1768 })
1769 .collect();
1770 // Build slot→elem reverse mapping. `elem_idx` is the element's
1771 // position in the array handed to `Bvh::build` — its *build order* —
1772 // which is exactly what `Bvh::update_aabb` is indexed by.
1773 self.bvh_slot_to_elem = vec![NO_ELEMENT; self.colliders.len()];
1774 for (elem_idx, (_, slot, _)) in elements.iter().enumerate() {
1775 self.bvh_slot_to_elem[*slot as usize] = elem_idx as u32;
1776 }
1777 let bvh = Bvh::build_layered(elements);
1778 self.bvh_quality_baseline = Some(bvh.normalized_surface_area_cost());
1779 self.refits_since_quality_check = 0;
1780 self.bvh = Some(bvh);
1781 self.counters.rebuilds += 1;
1782 }
1783
1784 /// Number of colliders currently registered.
1785 #[must_use]
1786 pub fn len(&self) -> usize {
1787 self.live_count
1788 }
1789
1790 /// Whether the world has no colliders.
1791 #[must_use]
1792 pub fn is_empty(&self) -> bool {
1793 self.live_count == 0
1794 }
1795
1796 // ── Queries ────────────────────────────────────────────────────────
1797
1798 /// Every collider whose shape the query sphere is inside, each with how
1799 /// deep, which way out and where ([`OverlapHit`]).
1800 ///
1801 /// Uses the BVH for broadphase culling, then measures the exact overlap
1802 /// against each shape — sphere, box, capsule, mesh, and each part of a
1803 /// compound, whose deepest part answers for it. A collider the sphere only
1804 /// touches is not inside it and is not returned. Triggers are included —
1805 /// overlap is the query they exist for. A caller that wants only the ids
1806 /// maps the pairs.
1807 #[must_use]
1808 pub fn overlap_sphere(&mut self, centre: DVec3, radius: f64) -> Vec<(ColliderId, OverlapHit)> {
1809 let mut out = Vec::new();
1810 self.overlap_sphere_into(centre, radius, &mut out);
1811 out
1812 }
1813
1814 /// [`overlap_sphere`](Self::overlap_sphere) writing into a buffer the
1815 /// caller owns.
1816 ///
1817 /// `out` is cleared and then filled. The intermediate buffers — the BVH
1818 /// descent stack and its candidate list — are the world's own and are
1819 /// reused between calls, so a caller that hoists one `out` out of its loop
1820 /// runs the whole pass without allocating.
1821 pub fn overlap_sphere_into(
1822 &mut self,
1823 centre: DVec3,
1824 radius: f64,
1825 out: &mut Vec<(ColliderId, OverlapHit)>,
1826 ) {
1827 self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, out);
1828 }
1829
1830 /// [`overlap_sphere`](Self::overlap_sphere) reporting only the colliders
1831 /// `filter` admits. Triggers are still reported.
1832 #[must_use]
1833 pub fn overlap_sphere_filtered(
1834 &mut self,
1835 centre: DVec3,
1836 radius: f64,
1837 filter: QueryFilter,
1838 ) -> Vec<(ColliderId, OverlapHit)> {
1839 let mut out = Vec::new();
1840 self.overlap_sphere_filtered_into(centre, radius, filter, &mut out);
1841 out
1842 }
1843
1844 /// [`overlap_sphere_into`](Self::overlap_sphere_into) reporting only the
1845 /// colliders `filter` admits. Triggers are still reported.
1846 pub fn overlap_sphere_filtered_into(
1847 &mut self,
1848 centre: DVec3,
1849 radius: f64,
1850 filter: QueryFilter,
1851 out: &mut Vec<(ColliderId, OverlapHit)>,
1852 ) {
1853 // Lent to the view and put straight back, which is what lets one
1854 // implementation serve both borrow shapes: the view cannot reach a
1855 // field of the world it is only sharing.
1856 let mut scratch = core::mem::take(&mut self.scratch);
1857 self.overlap_queries().overlap_sphere_filtered_into(
1858 centre,
1859 radius,
1860 filter,
1861 &mut scratch,
1862 out,
1863 );
1864 self.scratch = scratch;
1865 }
1866
1867 /// Builds the broadphase and hands back a shared view that can query it.
1868 ///
1869 /// The exchange this makes is the point: it costs the caller's exclusive
1870 /// borrow *once*, and buys a [`Sync`] query it can run from several threads
1871 /// at a time — see [`OverlapQueries`] for why the type is what enforces
1872 /// that rather than a rule in a comment.
1873 pub fn overlap_queries(&mut self) -> OverlapQueries<'_> {
1874 self.overlap_queries_with_scratch().0
1875 }
1876
1877 /// [`overlap_queries`](Self::overlap_queries) together with the world's
1878 /// own query buffers, for a caller in this crate that runs a whole
1879 /// sequence of queries against one view — a character move — under the
1880 /// exclusive borrow it already holds, and so needs no buffers of its own.
1881 pub(crate) fn overlap_queries_with_scratch(
1882 &mut self,
1883 ) -> (OverlapQueries<'_>, &mut QueryScratch) {
1884 self.ensure_bvh();
1885 let view = OverlapQueries {
1886 colliders: &self.colliders,
1887 generations: &self.generations,
1888 bvh: self.bvh.as_ref().expect("ensure_bvh built it"),
1889 };
1890 (view, &mut self.scratch)
1891 }
1892
1893 /// Return all collider ids that meet the query AABB.
1894 ///
1895 /// A box, turned or not, is reported only where it meets the query itself
1896 /// ([`crate::aabb_overlaps_box`]), a compound only where one of its parts
1897 /// does, and a mesh only where one of its triangles does. A sphere or a
1898 /// capsule is reported wherever the world-axis box around it meets the
1899 /// query, round surface or not; use [`PhysicsWorld::overlap_sphere`] for an
1900 /// exact round query. Triggers are included.
1901 #[must_use]
1902 pub fn overlap_aabb(&mut self, aabb: &Aabb) -> Vec<ColliderId> {
1903 self.overlap_aabb_filtered(aabb, QueryFilter::ALL)
1904 }
1905
1906 /// [`overlap_aabb`](Self::overlap_aabb) reporting only the colliders
1907 /// `filter` admits. Triggers are still reported.
1908 #[must_use]
1909 pub fn overlap_aabb_filtered(&mut self, aabb: &Aabb, filter: QueryFilter) -> Vec<ColliderId> {
1910 let mut scratch = core::mem::take(&mut self.scratch);
1911 let mut out = Vec::new();
1912 self.overlap_queries()
1913 .overlap_aabb_filtered_into(aabb, filter, &mut scratch, &mut out);
1914 self.scratch = scratch;
1915 out
1916 }
1917
1918 /// Cast a ray against all colliders, returning the closest hit (if any).
1919 ///
1920 /// Results are tested against the exact shape geometry (not just the AABB).
1921 /// The returned `ColliderId` is the handle you got from `add_*`.
1922 ///
1923 /// Triggers are non-solid and are skipped — use
1924 /// [`PhysicsWorld::overlap_sphere`] to detect them.
1925 #[must_use]
1926 pub fn cast_ray(&mut self, ray: &Ray) -> Option<(ColliderId, ShapeHit)> {
1927 self.cast_ray_excluding(ray, None)
1928 }
1929
1930 /// [`cast_ray`](Self::cast_ray) with one collider left out of the answer.
1931 ///
1932 /// A character whose collision capsule is registered in the world can
1933 /// cast from inside itself. Excluding that capsule in the narrow phase
1934 /// keeps the wall behind it, which discarding a self-hit afterwards loses.
1935 ///
1936 /// A stale or invalid `exclude` excludes nothing, which is the same answer
1937 /// as `None`. Triggers remain non-solid and are skipped.
1938 ///
1939 /// **It matches every layer**: the filter is only
1940 /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
1941 /// mask queries through [`cast_ray_filtered`](Self::cast_ray_filtered) with the same
1942 /// filter, or a query-only layer it ignores elsewhere blocks it here.
1943 #[must_use]
1944 pub fn cast_ray_excluding(
1945 &mut self,
1946 ray: &Ray,
1947 exclude: Option<ColliderId>,
1948 ) -> Option<(ColliderId, ShapeHit)> {
1949 self.cast_ray_filtered(ray, QueryFilter::excluding(exclude))
1950 }
1951
1952 /// [`cast_ray`](Self::cast_ray) over only the colliders `filter` admits:
1953 /// its exclusion is left out and so is every collider on none of its
1954 /// mask's layers, in the narrow phase, so the closest hit behind them
1955 /// survives. Triggers remain non-solid and are skipped.
1956 #[must_use]
1957 pub fn cast_ray_filtered(
1958 &mut self,
1959 ray: &Ray,
1960 filter: QueryFilter,
1961 ) -> Option<(ColliderId, ShapeHit)> {
1962 let mut scratch = core::mem::take(&mut self.scratch);
1963 let hit = self
1964 .overlap_queries()
1965 .cast_ray_filtered(ray, filter, &mut scratch);
1966 self.scratch = scratch;
1967 hit
1968 }
1969
1970 /// Sweep a sphere along a segment, returning the closest hit (if any).
1971 ///
1972 /// Uses the shape-level swept-sphere TOI functions for exact results.
1973 /// Triggers are non-solid and are skipped. Of two colliders met at exactly
1974 /// the same `t`, the one with the lower [`ColliderId::index`] is the
1975 /// answer. [`sweep_sphere_all`](Self::sweep_sphere_all) reports every hit,
1976 /// in the same order.
1977 ///
1978 /// # The broadphase query is the swept *volume*, not the centre line
1979 ///
1980 /// A sphere is `radius` wide, so the colliders it can touch are the ones
1981 /// within `radius` of the path its centre takes. Traversing the BVH with the
1982 /// centre line as a ray — which this did — offers the narrow phase only the
1983 /// colliders that line runs through, and every shape the sphere merely
1984 /// grazes is dropped before the exact test that would have caught it. The
1985 /// visible form of that: a ball rolling along a wall never touches it, and a
1986 /// ball approaching one is reported as hitting only once its centre is level
1987 /// with the surface, half a diameter inside.
1988 ///
1989 /// Traversing the segment's bounds inflated by `radius` offers a superset
1990 /// instead. The extra candidates cost one exact test each and are rejected
1991 /// by the same narrow phase as before.
1992 #[must_use]
1993 pub fn sweep_sphere(
1994 &mut self,
1995 segment: &Segment,
1996 radius: f64,
1997 ) -> Option<(ColliderId, ShapeHit)> {
1998 self.sweep_sphere_excluding(segment, radius, None)
1999 }
2000
2001 /// [`sweep_sphere`](Self::sweep_sphere) with one collider left out of the
2002 /// answer.
2003 ///
2004 /// This is the query a *body* sweeping its own path needs: the segment ends
2005 /// where the body is, so the body's own shape is sitting on the far end of
2006 /// it and is reported as the closest hit at `t = 0`. Excluding it here — and
2007 /// not by discarding the result afterwards — is what keeps the *next*
2008 /// closest hit: the narrow phase picks a single winner, so a caller that
2009 /// throws away a self-hit throws away the wall behind it too.
2010 ///
2011 /// A stale or invalid `exclude` excludes nothing, which is the same answer
2012 /// as `None`.
2013 ///
2014 /// # One id, and a mask — not a callback
2015 ///
2016 /// The field's general form is a filter the query calls back into — PhysX's
2017 /// `PxQueryFilterData`/`PxQueryFilterCallback`, Jolt's `BodyFilter`,
2018 /// Bullet's `ClosestRayResultCallback` and its mask. Every one of them also
2019 /// ships the degenerate case as its own thing, because it is the case that
2020 /// actually comes up: Jolt has `IgnoreSingleBodyFilter`, and Bullet's
2021 /// character controller carries a `ClosestNotMeConvexResultCallback`. That
2022 /// degenerate case was the whole of what this crate's consumers asked for,
2023 /// so for a while it was the whole of what this took.
2024 ///
2025 /// Then a consumer needed the mask as well. EW keeps its level, its
2026 /// characters and its dropped items in one world, and an item must not
2027 /// block a player's or an AI's sweep while an interaction ray still hits
2028 /// it — "skip everything of this kind", which no single excluded id can
2029 /// say. So [`QueryFilter`] exists, and carries exactly the two things asked
2030 /// for: the excluded id, and a layer mask tested against each collider's
2031 /// [layers](Self::set_layers) — Bullet's group/mask and PhysX's
2032 /// `PxFilterData` words, cut down to one word. It is still plain data and
2033 /// not a callback: tested in the narrow phase with no indirection, `Copy`
2034 /// into a shared [`OverlapQueries`] view, and the same answer on every
2035 /// thread. This method is [`sweep_sphere_filtered`](Self::sweep_sphere_filtered)
2036 /// with [`QueryFilter::excluding`].
2037 ///
2038 /// **It matches every layer**: the filter is only
2039 /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
2040 /// mask queries through [`sweep_sphere_filtered`](Self::sweep_sphere_filtered) with the same
2041 /// filter, or a query-only layer it ignores elsewhere blocks it here.
2042 #[must_use]
2043 pub fn sweep_sphere_excluding(
2044 &mut self,
2045 segment: &Segment,
2046 radius: f64,
2047 exclude: Option<ColliderId>,
2048 ) -> Option<(ColliderId, ShapeHit)> {
2049 self.sweep_sphere_filtered(segment, radius, QueryFilter::excluding(exclude))
2050 }
2051
2052 /// [`sweep_sphere`](Self::sweep_sphere) over only the colliders `filter`
2053 /// admits, left out in the narrow phase so the closest hit behind them
2054 /// survives. Triggers remain non-solid and are skipped.
2055 #[must_use]
2056 pub fn sweep_sphere_filtered(
2057 &mut self,
2058 segment: &Segment,
2059 radius: f64,
2060 filter: QueryFilter,
2061 ) -> Option<(ColliderId, ShapeHit)> {
2062 let mut scratch = core::mem::take(&mut self.scratch);
2063 let hit =
2064 self.overlap_queries()
2065 .sweep_sphere_filtered(segment, radius, filter, &mut scratch);
2066 self.scratch = scratch;
2067 hit
2068 }
2069
2070 /// Sweep a Y-aligned capsule along a segment, returning the closest hit (if
2071 /// any). `segment` is the path of the capsule's **centre**; `radius` and
2072 /// `half_height` describe the same capsule [`Capsule`] does.
2073 ///
2074 /// This is [`sweep_sphere`](Self::sweep_sphere)'s sibling and shares its
2075 /// semantics: exact shape-level TOI, triggers skipped, ties to the lower
2076 /// collider index, and a broadphase query over the swept volume rather
2077 /// than the centre line. [`sweep_capsule_all`](Self::sweep_capsule_all)
2078 /// reports every hit, in the same order.
2079 ///
2080 /// # Why a character wants this and not the sphere sweep
2081 ///
2082 /// A sphere is the wrong probe for anything that stands up. Given a
2083 /// character's width it is too short, so it rides over a step or a railing
2084 /// the character's chest should have struck; given the character's height it
2085 /// is too wide, so it collides with walls the character is clear of and
2086 /// cannot fit through its own doorway. Neither is tunable away — the two
2087 /// errors are the same sphere. The capsule is the shape every engine's
2088 /// character controller uses for exactly that reason.
2089 #[must_use]
2090 pub fn sweep_capsule(
2091 &mut self,
2092 segment: &Segment,
2093 radius: f64,
2094 half_height: f64,
2095 ) -> Option<(ColliderId, ShapeHit)> {
2096 self.sweep_capsule_excluding(segment, radius, half_height, None)
2097 }
2098
2099 /// [`sweep_capsule`](Self::sweep_capsule) with one collider left out of the
2100 /// answer.
2101 ///
2102 /// The same query, and the same reason, as
2103 /// [`sweep_sphere_excluding`](Self::sweep_sphere_excluding): a character
2104 /// whose own capsule is registered in the world is sitting on the start of
2105 /// every segment it sweeps, so it is reported as the closest hit at
2106 /// `t = 0`. Dropping it in the narrow phase is what keeps the *next*
2107 /// closest hit — the wall behind it — which a caller discarding a self-hit
2108 /// afterwards has already thrown away.
2109 ///
2110 /// A stale or invalid `exclude` excludes nothing, which is the same answer
2111 /// as `None`.
2112 ///
2113 /// **It matches every layer**: the filter is only
2114 /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
2115 /// mask queries through [`sweep_capsule_filtered`](Self::sweep_capsule_filtered) with the same
2116 /// filter, or a query-only layer it ignores elsewhere blocks it here.
2117 #[must_use]
2118 pub fn sweep_capsule_excluding(
2119 &mut self,
2120 segment: &Segment,
2121 radius: f64,
2122 half_height: f64,
2123 exclude: Option<ColliderId>,
2124 ) -> Option<(ColliderId, ShapeHit)> {
2125 self.sweep_capsule_filtered(
2126 segment,
2127 radius,
2128 half_height,
2129 QueryFilter::excluding(exclude),
2130 )
2131 }
2132
2133 /// [`sweep_capsule`](Self::sweep_capsule) over only the colliders `filter`
2134 /// admits, left out in the narrow phase so the closest hit behind them
2135 /// survives. Triggers remain non-solid and are skipped. This is the sweep
2136 /// [`CharacterController`](crate::CharacterController) runs, with its
2137 /// self collider and its query mask.
2138 #[must_use]
2139 pub fn sweep_capsule_filtered(
2140 &mut self,
2141 segment: &Segment,
2142 radius: f64,
2143 half_height: f64,
2144 filter: QueryFilter,
2145 ) -> Option<(ColliderId, ShapeHit)> {
2146 let mut scratch = core::mem::take(&mut self.scratch);
2147 let hit = self.overlap_queries().sweep_capsule_filtered(
2148 segment,
2149 radius,
2150 half_height,
2151 filter,
2152 &mut scratch,
2153 );
2154 self.scratch = scratch;
2155 hit
2156 }
2157
2158 /// Every solid collider a Y-aligned capsule is *inside*, with the push-out
2159 /// each one needs, written into `out` (which is cleared first).
2160 ///
2161 /// # A sweep cannot answer this, which is why it is its own query
2162 ///
2163 /// [`sweep_capsule`](Self::sweep_capsule) reports a capsule that starts
2164 /// overlapping as a contact at `t = 0` and stops there: there is no earlier
2165 /// time to report, and the *depth* is a measurement the time of impact does
2166 /// not contain. A character that spawned inside the level, or that a moving
2167 /// platform closed on, has to know how far out to go — see [`Penetration`].
2168 ///
2169 /// Triggers are non-solid and are skipped, and so is `exclude`. Nothing
2170 /// here allocates beyond growing `out`: the broadphase's descent stack and
2171 /// candidate list are the world's own, so a character resolving its
2172 /// overlaps every tick costs no allocation.
2173 ///
2174 /// **It matches every layer**: the filter is only
2175 /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
2176 /// mask queries through [`capsule_penetrations_filtered_into`](Self::capsule_penetrations_filtered_into) with the same
2177 /// filter, or a query-only layer it ignores elsewhere blocks it here.
2178 pub fn capsule_penetrations_into(
2179 &mut self,
2180 capsule: &Capsule,
2181 exclude: Option<ColliderId>,
2182 out: &mut Vec<(ColliderId, Penetration)>,
2183 ) {
2184 self.capsule_penetrations_filtered_into(capsule, QueryFilter::excluding(exclude), out);
2185 }
2186
2187 /// [`capsule_penetrations_into`](Self::capsule_penetrations_into) over
2188 /// only the colliders `filter` admits. Triggers are still skipped.
2189 pub fn capsule_penetrations_filtered_into(
2190 &mut self,
2191 capsule: &Capsule,
2192 filter: QueryFilter,
2193 out: &mut Vec<(ColliderId, Penetration)>,
2194 ) {
2195 let mut scratch = core::mem::take(&mut self.scratch);
2196 self.overlap_queries().capsule_penetrations_filtered_into(
2197 capsule,
2198 filter,
2199 &mut scratch,
2200 out,
2201 );
2202 self.scratch = scratch;
2203 }
2204
2205 /// A solid collider a [`LyingCapsule`] would be *inside*, or `None` if it
2206 /// is clear of every one `filter` admits: whether a prone body fits at
2207 /// that pose.
2208 ///
2209 /// Nothing moves — this is the question to ask before letting a body lie
2210 /// down, or before turning one that already is. A shape the capsule only
2211 /// touches does not block it, as it is no
2212 /// [penetration](Self::capsule_penetrations_into): a body lying with its
2213 /// underside a [`radius`](LyingCapsule::radius) above the floor fits.
2214 ///
2215 /// Triggers are non-solid and are skipped, as the penetration query skips
2216 /// them, and so is the filter's exclusion — which is where a character's
2217 /// own collider goes. When several colliders block the pose, which one is
2218 /// named is the first the broadphase offers: the same one for the same
2219 /// world, and no nearer or deeper than the others.
2220 #[must_use]
2221 pub fn lying_capsule_blocker(
2222 &mut self,
2223 capsule: &LyingCapsule,
2224 filter: QueryFilter,
2225 ) -> Option<ColliderId> {
2226 let mut scratch = core::mem::take(&mut self.scratch);
2227 let blocker = self
2228 .overlap_queries()
2229 .lying_capsule_blocker(capsule, filter, &mut scratch);
2230 self.scratch = scratch;
2231 blocker
2232 }
2233
2234 /// [`OverlapQueries::sweep_lying_capsule`] in the world's own buffers.
2235 ///
2236 /// Only the world's tests ask it this way: the controller's slide runs
2237 /// against a view it holds for the whole move.
2238 #[cfg(test)]
2239 pub(crate) fn sweep_lying_capsule(
2240 &mut self,
2241 capsule: &LyingCapsule,
2242 motion: DVec3,
2243 filter: QueryFilter,
2244 ) -> Option<(ColliderId, SweptContact)> {
2245 let (view, scratch) = self.overlap_queries_with_scratch();
2246 view.sweep_lying_capsule(capsule, motion, filter, scratch)
2247 }
2248
2249 /// Get the AABB of a collider by id.
2250 #[must_use]
2251 pub fn aabb_of(&self, id: ColliderId) -> Option<Aabb> {
2252 let slot = self.slot_of(id)?;
2253 self.colliders[slot].as_ref().map(|s| s.entry.aabb())
2254 }
2255
2256 /// The broadphase's shape and its refit/rebuild totals, as a reading a
2257 /// game can measure a policy against.
2258 ///
2259 /// **For diagnostics, not for the frame path.** It forces the lazy rebuild
2260 /// if the tree is dirty, and the two shape diagnostics walk the whole tree
2261 /// — `O(n)` — so this is what a teleport rule's cost/benefit is argued
2262 /// from, the way `docs/backlog.md`'s "A consumer cannot see the cost it is
2263 /// being asked to avoid" asked for, and nothing a hot loop should call.
2264 ///
2265 /// The forced rebuild is counted: call this on a dirty tree and the
2266 /// [`rebuilds`](BroadphaseStats::rebuilds) it returns includes that one.
2267 /// A caller subtracting two readings to measure a phase therefore sees the
2268 /// phase it asked about *plus* whatever the first reading itself forced,
2269 /// which is why the first reading is best taken with the tree already
2270 /// built.
2271 #[must_use]
2272 pub fn broadphase_stats(&mut self) -> BroadphaseStats {
2273 self.ensure_bvh();
2274 let bvh = self.bvh.as_ref().expect("ensure_bvh built it");
2275 BroadphaseStats {
2276 elements: bvh.len(),
2277 nodes: bvh.node_count(),
2278 depth: bvh.depth(),
2279 surface_area_cost: bvh.surface_area_cost(),
2280 refits: self.counters.refits,
2281 updates_without_refit: self.counters.updates_without_refit,
2282 rebuilds: self.counters.rebuilds,
2283 }
2284 }
2285
2286 // ── Internal helpers ───────────────────────────────────────────────
2287
2288 /// Resolve an id to a live storage slot, or `None` if the id is stale
2289 /// (generation mismatch) or names an empty slot.
2290 fn slot_of(&self, id: ColliderId) -> Option<usize> {
2291 slot_of_in(&self.colliders, &self.generations, id)
2292 }
2293
2294 /// The id currently naming `slot`. Only call with a slot the BVH just
2295 /// reported, i.e. one that is live.
2296 fn id_for_slot(&self, slot: u32) -> ColliderId {
2297 id_for_slot_in(&self.generations, slot)
2298 }
2299
2300 fn add(&mut self, entry: ColliderEntry) -> ColliderId {
2301 let aabb = entry.aabb();
2302 let slot_data = ColliderSlot {
2303 entry,
2304 is_trigger: false,
2305 layers: ALL_LAYERS,
2306 };
2307 let index = if let Some(slot) = self.free_slots.pop() {
2308 self.colliders[slot as usize] = Some(slot_data);
2309 slot
2310 } else {
2311 let idx = self.colliders.len() as u32;
2312 self.colliders.push(Some(slot_data));
2313 self.generations.push(0);
2314 idx
2315 };
2316 self.live_count += 1;
2317
2318 // A tree that exists absorbs the new collider; one that does not stays
2319 // absent, so a batch of adds before the first query still costs one
2320 // bulk build rather than n insertions.
2321 if let Some(bvh) = self.bvh.as_mut() {
2322 let elem = bvh.insert_layered(aabb, index, ALL_LAYERS);
2323 if self.bvh_slot_to_elem.len() <= index as usize {
2324 self.bvh_slot_to_elem.resize(index as usize + 1, NO_ELEMENT);
2325 }
2326 self.bvh_slot_to_elem[index as usize] = elem as u32;
2327 self.bvh_quality_baseline = None;
2328 self.refits_since_quality_check = 0;
2329 }
2330 self.id_for_slot(index)
2331 }
2332
2333 /// Drop the BVH so the next query rebuilds it from the collider set.
2334 fn invalidate_bvh(&mut self) {
2335 self.bvh = None;
2336 self.bvh_quality_baseline = None;
2337 self.refits_since_quality_check = 0;
2338 self.bvh_slot_to_elem.clear();
2339 }
2340
2341 /// Update an existing collider entry, refitting the BVH if built.
2342 fn set(&mut self, id: ColliderId, entry: ColliderEntry) -> bool {
2343 let Some(slot) = self.slot_of(id) else {
2344 return false;
2345 };
2346 let new_aabb = entry.aabb();
2347 if let Some(slot_data) = self.colliders[slot].as_mut() {
2348 // Only the shape changes: the trigger flag and the layers stay.
2349 slot_data.entry = entry;
2350 }
2351
2352 // Try incremental refit. A refit that reports failure leaves the tree
2353 // holding the old bounds, so the BVH must be dropped rather than
2354 // queried against stale geometry.
2355 let refit = match self.bvh {
2356 Some(ref mut bvh) => match self.bvh_slot_to_elem.get(slot).copied() {
2357 Some(elem) if elem != NO_ELEMENT => bvh.update_aabb(elem as usize, new_aabb),
2358 _ => false,
2359 },
2360 None => false,
2361 };
2362 if refit {
2363 self.counters.refits += 1;
2364 self.refits_since_quality_check = self.refits_since_quality_check.saturating_add(1);
2365 } else {
2366 self.counters.updates_without_refit += 1;
2367 self.invalidate_bvh();
2368 }
2369 true
2370 }
2371
2372 fn ensure_bvh(&mut self) {
2373 if self.bvh.is_none() {
2374 self.rebuild();
2375 return;
2376 }
2377
2378 let bvh = self.bvh.as_ref().expect("the absent tree returned above");
2379 if self.bvh_quality_baseline.is_none() {
2380 self.bvh_quality_baseline = Some(bvh.normalized_surface_area_cost());
2381 self.refits_since_quality_check = 0;
2382 return;
2383 }
2384 let refits_per_check = self
2385 .live_count
2386 .saturating_mul(BROADPHASE_QUALITY_CHECK_REFIT_PASSES)
2387 .max(1);
2388 if self.refits_since_quality_check < refits_per_check {
2389 return;
2390 }
2391
2392 let current_cost = bvh.normalized_surface_area_cost();
2393 self.refits_since_quality_check = 0;
2394 let baseline = self
2395 .bvh_quality_baseline
2396 .expect("the absent baseline returned above");
2397 if current_cost > baseline * BROADPHASE_REBUILD_COST_RATIO {
2398 self.rebuild();
2399 }
2400 }
2401}
2402
2403impl Default for PhysicsWorld {
2404 fn default() -> Self {
2405 Self::new()
2406 }
2407}
2408
2409impl std::fmt::Debug for PhysicsWorld {
2410 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2411 f.debug_struct("PhysicsWorld")
2412 .field("collider_count", &self.len())
2413 .field("bvh_cached", &self.bvh.is_some())
2414 .finish()
2415 }
2416}
2417
2418// ---------------------------------------------------------------------------
2419// Tests
2420// ---------------------------------------------------------------------------
2421
2422#[cfg(test)]
2423mod tests {
2424 use super::*;
2425
2426 /// The colliders an overlap answered, in its order, without their hits.
2427 pub(super) fn ids_of(hits: &[(ColliderId, OverlapHit)]) -> Vec<ColliderId> {
2428 hits.iter().map(|&(id, _)| id).collect()
2429 }
2430
2431 #[test]
2432 fn empty_world_is_empty() {
2433 let world = PhysicsWorld::new();
2434 assert!(world.is_empty());
2435 assert_eq!(world.len(), 0);
2436 }
2437
2438 /// **The stats a teleport rule would measure with.** `broadphase_stats`
2439 /// forces the lazy rebuild and reports the tree's shape: one entry per
2440 /// live collider, at least one node per leaf, and a depth that exists for
2441 /// a non-empty tree. The exact node count and depth are the AVL balance's
2442 /// business — what is pinned is that the observable exists and agrees with
2443 /// the world's own count.
2444 #[test]
2445 fn broadphase_stats_report_the_trees_shape() {
2446 let mut world = PhysicsWorld::new();
2447 assert_eq!(
2448 world.broadphase_stats(),
2449 BroadphaseStats {
2450 elements: 0,
2451 nodes: 0,
2452 depth: 0,
2453 surface_area_cost: 0.0,
2454 refits: 0,
2455 updates_without_refit: 0,
2456 rebuilds: 1,
2457 },
2458 "an empty world has an empty tree, built by the reading itself"
2459 );
2460
2461 for x in 0..16 {
2462 world.add_sphere(Sphere::new(DVec3::new(f64::from(x), 0.0, 0.0), 0.4));
2463 }
2464 let stats = world.broadphase_stats();
2465 assert_eq!(stats.elements, 16, "every collider is a leaf");
2466 assert!(
2467 stats.nodes >= 16,
2468 "a binary tree holds at least one node per leaf; got {stats:?}"
2469 );
2470 assert!(
2471 stats.depth >= 1,
2472 "a non-empty tree has a depth; got {stats:?}"
2473 );
2474 }
2475
2476 /// A line of spheres, and the ids naming them.
2477 ///
2478 /// One row rather than a lattice: the refit counters are about *when* the
2479 /// tree is refit rather than about what it answers, so the cheapest fixture
2480 /// that still gives a real tree with real ancestors to walk back through is
2481 /// the right one.
2482 fn line_of_spheres(n: u32) -> (PhysicsWorld, Vec<ColliderId>) {
2483 let mut world = PhysicsWorld::new();
2484 let ids = (0..n)
2485 .map(|x| world.add_sphere(Sphere::new(DVec3::new(f64::from(x), 0.0, 0.0), 0.4)))
2486 .collect();
2487 (world, ids)
2488 }
2489
2490 /// **A small move is absorbed in place: one refit, nothing invalidated,
2491 /// nothing rebuilt.**
2492 ///
2493 /// The counters exist to answer "did that phase refit or did it rebuild",
2494 /// and this is the answer they have to give for the case a game actually
2495 /// runs — a body that walked a fraction of its own radius since last tick.
2496 #[test]
2497 fn a_small_update_is_counted_as_a_refit() {
2498 let (mut world, ids) = line_of_spheres(16);
2499 let before = world.broadphase_stats();
2500 assert_eq!(before.rebuilds, 1, "the reading itself built the tree");
2501 assert_eq!(before.refits, 0, "and nothing has been updated yet");
2502
2503 assert!(world.set_sphere(ids[7], Sphere::new(DVec3::new(7.05, 0.0, 0.0), 0.4)));
2504
2505 let after = world.broadphase_stats();
2506 assert_eq!(
2507 after.refits,
2508 before.refits + 1,
2509 "the update should have refit the tree in place; got {after:?}"
2510 );
2511 assert_eq!(
2512 after.updates_without_refit, before.updates_without_refit,
2513 "nothing should have been left for a rebuild; got {after:?}"
2514 );
2515 assert_eq!(
2516 after.rebuilds, before.rebuilds,
2517 "and no rebuild should have happened; got {after:?}"
2518 );
2519 }
2520
2521 /// **A teleport refits too — a tree is never thrown away for a move being
2522 /// large.**
2523 ///
2524 /// [`Bvh::update_aabb`] fails only when the element index names nothing. It
2525 /// has no notion of the new box escaping the old one, and grows the
2526 /// ancestors it walks instead. Worth pinning rather than assuming, because
2527 /// the opposite is the intuitive guess and a `refits` read under it would be
2528 /// read as a rebuild that never happened. The move is checked to have
2529 /// *landed* as well, so a refit that counted itself without touching the
2530 /// tree fails here rather than passing quietly.
2531 #[test]
2532 fn a_teleport_refits_rather_than_rebuilding() {
2533 let (mut world, ids) = line_of_spheres(16);
2534 let before = world.broadphase_stats();
2535
2536 assert!(world.set_sphere(ids[7], Sphere::new(DVec3::new(0.0, 900.0, 0.0), 0.4)));
2537
2538 let after = world.broadphase_stats();
2539 assert_eq!(
2540 after.refits,
2541 before.refits + 1,
2542 "a teleport is still a refit; got {after:?}"
2543 );
2544 assert_eq!(
2545 after.rebuilds, before.rebuilds,
2546 "and costs no rebuild; got {after:?}"
2547 );
2548 assert_eq!(
2549 after.updates_without_refit, before.updates_without_refit,
2550 "and leaves nothing for one; got {after:?}"
2551 );
2552
2553 assert_eq!(
2554 ids_of(&world.overlap_sphere(DVec3::new(0.0, 900.0, 0.0), 0.1)),
2555 vec![ids[7]],
2556 "the refit tree must answer at the new place"
2557 );
2558 assert!(
2559 world
2560 .overlap_sphere(DVec3::new(7.0, 0.0, 0.0), 0.1)
2561 .is_empty(),
2562 "and no longer at the old one"
2563 );
2564 }
2565
2566 #[test]
2567 fn a_spatially_loose_tree_rebuilds_when_the_quality_check_is_due() {
2568 let (mut world, ids) = line_of_spheres(16);
2569 let before = world.broadphase_stats();
2570
2571 for _ in 0..BROADPHASE_QUALITY_CHECK_REFIT_PASSES {
2572 for (x, &id) in (0_u32..).zip(&ids) {
2573 let side = if x % 2 == 0 { -1.0 } else { 1.0 };
2574 let centre = DVec3::new(side * (1_000.0 + f64::from(x)), 0.0, 0.0);
2575 assert!(world.set_sphere(id, Sphere::new(centre, 0.4)));
2576 }
2577 world.overlap_queries();
2578 }
2579
2580 let after = world.broadphase_stats();
2581 assert_eq!(
2582 after.rebuilds,
2583 before.rebuilds + 1,
2584 "the interleaved distant leaves should be repartitioned: {after:?}"
2585 );
2586 }
2587
2588 #[test]
2589 fn uniform_world_scaling_does_not_look_like_tree_degradation() {
2590 let mut world = PhysicsWorld::new();
2591 let ids: Vec<_> = (0..16)
2592 .map(|x| {
2593 world.add_box(BoxCollider::new(
2594 DVec3::new(f64::from(x), 0.0, 0.0),
2595 DVec3::splat(0.4),
2596 ))
2597 })
2598 .collect();
2599 let before = world.broadphase_stats();
2600
2601 for _ in 0..BROADPHASE_QUALITY_CHECK_REFIT_PASSES {
2602 for (x, &id) in (0_u32..).zip(&ids) {
2603 let scaled =
2604 BoxCollider::new(DVec3::new(f64::from(x) * 10.0, 0.0, 0.0), DVec3::splat(4.0));
2605 assert!(world.set_box(id, scaled));
2606 }
2607 world.overlap_queries();
2608 }
2609
2610 let after = world.broadphase_stats();
2611 assert_eq!(
2612 after.rebuilds, before.rebuilds,
2613 "scaling preserved the partition and should not rebuild it: {after:?}"
2614 );
2615 }
2616
2617 /// **An update the tree cannot absorb drops it, and the next query pays for
2618 /// the rebuild.**
2619 ///
2620 /// The state that produces it is unreachable through the public API — a
2621 /// live collider whose built tree holds no element for its slot — so the
2622 /// test reaches in and builds it. That state is the whole of what
2623 /// `updates_without_refit` counts while a tree exists, and leaving it
2624 /// unexercised would leave the invalidation branch guarded by nothing.
2625 #[test]
2626 fn an_update_with_no_element_to_refit_invalidates_and_the_next_query_rebuilds() {
2627 let (mut world, ids) = line_of_spheres(16);
2628 let before = world.broadphase_stats();
2629 assert!(world.bvh.is_some(), "the reading built the tree");
2630
2631 world.bvh_slot_to_elem[ids[3].index() as usize] = NO_ELEMENT;
2632 assert!(world.set_sphere(ids[3], Sphere::new(DVec3::new(3.0, 40.0, 0.0), 0.4)));
2633 assert!(
2634 world.bvh.is_none(),
2635 "an update that could not refit must drop the tree rather than \
2636 leave it holding the old bounds"
2637 );
2638
2639 let after = world.broadphase_stats();
2640 assert_eq!(
2641 after.updates_without_refit,
2642 before.updates_without_refit + 1,
2643 "the update should be counted as one that did not refit; got {after:?}"
2644 );
2645 assert_eq!(
2646 after.refits, before.refits,
2647 "and must not also count as a refit; got {after:?}"
2648 );
2649 assert_eq!(
2650 after.rebuilds,
2651 before.rebuilds + 1,
2652 "the reading after it should have rebuilt; got {after:?}"
2653 );
2654 assert_eq!(
2655 after.elements, 16,
2656 "and rebuilt the whole set; got {after:?}"
2657 );
2658
2659 assert_eq!(
2660 ids_of(&world.overlap_sphere(DVec3::new(3.0, 40.0, 0.0), 0.1)),
2661 vec![ids[3]],
2662 "the rebuilt tree must answer at the new place"
2663 );
2664 }
2665
2666 /// **Updates made before there is a tree are counted one by one, and cost
2667 /// one rebuild between them.**
2668 ///
2669 /// The counting rule in one test: the totals only climb, `refits` and
2670 /// `updates_without_refit` between them account for every `set_*` that
2671 /// resolved to a live collider, and one that resolved to nothing is counted
2672 /// by neither.
2673 #[test]
2674 fn updates_with_no_tree_yet_are_counted_per_update_not_per_rebuild() {
2675 let (mut world, ids) = line_of_spheres(16);
2676 assert!(world.set_sphere(ids[0], Sphere::new(DVec3::new(0.0, 1.0, 0.0), 0.4)));
2677 assert!(world.set_sphere(ids[1], Sphere::new(DVec3::new(1.0, 1.0, 0.0), 0.4)));
2678
2679 let stats = world.broadphase_stats();
2680 assert_eq!(
2681 stats.updates_without_refit, 2,
2682 "one per update, with no tree to refit; got {stats:?}"
2683 );
2684 assert_eq!(stats.refits, 0, "nothing was refit; got {stats:?}");
2685 assert_eq!(
2686 stats.rebuilds, 1,
2687 "and one rebuild between the two of them; got {stats:?}"
2688 );
2689
2690 assert!(world.remove(ids[5]));
2691 let before = world.broadphase_stats();
2692 assert!(!world.set_sphere(ids[5], Sphere::new(DVec3::ZERO, 0.4)));
2693 let after = world.broadphase_stats();
2694 assert_eq!(
2695 (after.refits, after.updates_without_refit),
2696 (before.refits, before.updates_without_refit),
2697 "a set_* on a stale id is counted by neither; got {after:?}"
2698 );
2699 }
2700
2701 /// **The shared view finds exactly what overlaps, checked against a scan
2702 /// rather than against the other form.**
2703 ///
2704 /// Comparing [`OverlapQueries`] with [`PhysicsWorld::overlap_sphere_into`]
2705 /// would prove nothing: they are one implementation, and a defect in it
2706 /// breaks both sides of that comparison equally — measured, not assumed, by
2707 /// reversing the core's output and watching the comparison stay green. So
2708 /// the oracle here is an exhaustive scan of every collider in the fixture,
2709 /// which shares no code with the traversal at all.
2710 ///
2711 /// It is a set comparison, because a scan cannot reproduce the tree's
2712 /// order. The *order* is what a caller reducing over the neighbourhood in
2713 /// `f64` depends on, and it comes from having one implementation rather than
2714 /// from this test — which is the reason the two forms were made to share
2715 /// one, and the reason `apps/horde`'s
2716 /// `steering_is_bit_identical_however_many_workers_run_it` is where that
2717 /// property is actually asserted.
2718 #[test]
2719 fn the_shared_view_finds_exactly_what_a_scan_would() {
2720 let mut world = PhysicsWorld::new();
2721 // A lattice, so a query sphere lands on a neighbourhood rather than on
2722 // one collider or none, and a descent that pruned a subtree it should
2723 // not have loses something the scan still finds.
2724 let mut expected: Vec<(ColliderId, Sphere)> = Vec::new();
2725 for x in -3..=3 {
2726 for y in -3..=3 {
2727 let sphere = Sphere::new(DVec3::new(f64::from(x), f64::from(y), 0.0), 0.4);
2728 expected.push((world.add_sphere(sphere), sphere));
2729 }
2730 }
2731 // A capsule and a box as well, so every arm of the exact test is
2732 // exercised rather than only the sphere one.
2733 let capsule = Capsule::new(DVec3::ZERO, 0.3, 1.0);
2734 let capsule_id = world.add_capsule(capsule);
2735 let boxed = BoxCollider::new(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.5));
2736 let box_id = world.add_box(boxed);
2737
2738 let centres = [
2739 DVec3::ZERO,
2740 DVec3::new(1.2, -0.7, 0.0),
2741 DVec3::new(-2.5, 2.5, 0.0),
2742 DVec3::new(50.0, 50.0, 0.0),
2743 ];
2744 let mut scratch = QueryScratch::new();
2745 let mut biggest = 0usize;
2746 for centre in centres {
2747 for radius in [0.1, 0.75, 2.0] {
2748 let probe = Sphere::new(centre, radius);
2749 // The oracle: every collider, tested directly, with no tree and
2750 // no traversal between the shapes and the answer.
2751 let mut scanned: Vec<(ColliderId, OverlapHit)> = expected
2752 .iter()
2753 .filter_map(|(id, s)| Some((*id, query::sphere_overlap_vs_sphere(&probe, s)?)))
2754 .collect();
2755 if let Some(hit) = query::sphere_overlap_vs_capsule(&probe, &capsule) {
2756 scanned.push((capsule_id, hit));
2757 }
2758 if let Some(hit) = query::sphere_overlap_vs_aabb(&probe, &boxed.aabb()) {
2759 scanned.push((box_id, hit));
2760 }
2761 scanned.sort_unstable_by_key(|(id, _)| id.index());
2762
2763 let mut shared = Vec::new();
2764 world.overlap_queries().overlap_sphere_into(
2765 centre,
2766 radius,
2767 &mut scratch,
2768 &mut shared,
2769 );
2770 shared.sort_unstable_by_key(|(id, _)| id.index());
2771
2772 assert_eq!(scanned, shared, "at {centre} r{radius}");
2773 biggest = biggest.max(shared.len());
2774 }
2775 }
2776 assert!(
2777 biggest > 4,
2778 "the widest query in the fixture found {biggest} colliders, so the \
2779 comparison above was mostly two empty vectors",
2780 );
2781 }
2782
2783 /// Every probe's answers, from one form or the other, so a whole run
2784 /// compares in a single `assert_eq!`.
2785 #[derive(Debug, PartialEq)]
2786 struct ProbeAnswers {
2787 rays: Vec<Option<(ColliderId, ShapeHit)>>,
2788 sweeps: Vec<Option<(ColliderId, ShapeHit)>>,
2789 excluded_sweeps: Vec<Option<(ColliderId, ShapeHit)>>,
2790 aabbs: Vec<Vec<ColliderId>>,
2791 }
2792
2793 /// The exact ray test for a collider, with no tree and no traversal
2794 /// between the shape and the answer.
2795 fn scan_ray_one(ray: &Ray, entry: &ColliderEntry) -> Option<ShapeHit> {
2796 match entry {
2797 ColliderEntry::Sphere(s) => query::ray_vs_sphere(ray, s),
2798 ColliderEntry::Box(b) => query::ray_vs_box(ray, b),
2799 ColliderEntry::Capsule(c) => query::ray_vs_capsule(ray, &c.capsule),
2800 ColliderEntry::Mesh(_) | ColliderEntry::Compound(_) => {
2801 unreachable!("the fixture holds no meshes or compounds")
2802 }
2803 }
2804 }
2805
2806 /// The exact swept-sphere test for a collider, likewise.
2807 fn scan_sweep_one(segment: &Segment, radius: f64, entry: &ColliderEntry) -> Option<ShapeHit> {
2808 match entry {
2809 ColliderEntry::Sphere(s) => query::swept_sphere_vs_sphere(segment, radius, s),
2810 ColliderEntry::Box(b) => query::swept_sphere_vs_box(segment, radius, b),
2811 ColliderEntry::Capsule(c) => {
2812 query::swept_sphere_vs_capsule(segment, radius, &c.capsule)
2813 }
2814 ColliderEntry::Mesh(_) | ColliderEntry::Compound(_) => {
2815 unreachable!("the fixture holds no meshes or compounds")
2816 }
2817 }
2818 }
2819
2820 /// **The ray, sweep and AABB queries answer a brute-force scan under a
2821 /// shared borrow, from every thread asking at once.**
2822 ///
2823 /// The companion to `the_shared_view_finds_exactly_what_a_scan_would`, and
2824 /// it is held to the same standard for the same reason: comparing
2825 /// [`OverlapQueries::cast_ray`] with [`PhysicsWorld::cast_ray`] proves
2826 /// nothing on its own, because they are one implementation and a defect in
2827 /// it moves both sides of that comparison together. So each answer is also
2828 /// checked against an exhaustive scan of the fixture, which shares no code
2829 /// with the traversal.
2830 ///
2831 /// What the scan can and cannot pin down:
2832 ///
2833 /// * For a ray or a sweep the scan gives the closest `t`, and the query's
2834 /// own `t` must equal it exactly — same inputs through the same shape
2835 /// functions, so this is not a tolerance question. The *identity* is then
2836 /// checked by re-running the exact test on the collider that came back:
2837 /// a query that returned a farther collider fails on `t`, and one that
2838 /// returned a mislabelled id fails on the re-test.
2839 /// * For an AABB overlap the scan gives the whole set, compared sorted —
2840 /// tree order is not something a scan can reproduce. The order is a
2841 /// property of the two forms sharing one traversal, which is why they do.
2842 ///
2843 /// The concurrent half is what the shared form exists for: one view, a
2844 /// [`QueryScratch`] per thread, and every thread must reach the answers the
2845 /// calling thread reached alone. It guards a future regression — putting
2846 /// the scratch back inside the view is exactly the change that would break
2847 /// it — rather than a race in today's code, which holds only shared
2848 /// references.
2849 #[test]
2850 fn the_shared_view_casts_sweeps_and_boxes_like_a_scan_would() {
2851 let mut world = PhysicsWorld::new();
2852 // (id, shape, is_trigger): the oracle, and all the scan below reads.
2853 let mut fixture: Vec<(ColliderId, ColliderEntry, bool)> = Vec::new();
2854 // A lattice, so a probe lands on a neighbourhood rather than on one
2855 // collider or none, and a descent that pruned a subtree it should not
2856 // have loses something the scan still finds.
2857 let mut row_start = None;
2858 for x in -3..=3 {
2859 for y in -3..=3 {
2860 let sphere = Sphere::new(DVec3::new(f64::from(x), f64::from(y), 0.0), 0.4);
2861 let id = world.add_sphere(sphere);
2862 if x == -3 && y == 0 {
2863 row_start = Some(id);
2864 }
2865 fixture.push((id, ColliderEntry::Sphere(sphere), false));
2866 }
2867 }
2868 let row_start = row_start.expect("the lattice contains (-3, 0, 0)");
2869 // A capsule and a box as well, so every arm of the exact test is
2870 // exercised rather than only the sphere one.
2871 let capsule = Capsule::new(DVec3::new(0.0, 0.0, 3.0), 0.3, 1.0);
2872 fixture.push((
2873 world.add_capsule(capsule),
2874 ColliderEntry::Capsule(TurnedCapsule::upright(capsule)),
2875 true,
2876 ));
2877 let boxed = BoxCollider::new(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.5));
2878 fixture.push((world.add_box(boxed), ColliderEntry::Box(boxed), false));
2879 // A trigger standing in front of the first ray's solid hits. Triggers
2880 // are non-solid, so a cast that reports this one has stopped skipping
2881 // them — and `the_skipped_trigger_was_in_the_way` below checks that
2882 // this collider really is in the way, so the skip is a branch the run
2883 // actually takes.
2884 let trigger = Sphere::new(DVec3::new(-5.0, 0.0, 0.0), 0.5);
2885 let trigger_id = world.add_sphere(trigger);
2886 assert!(world.set_trigger(trigger_id, true), "the trigger was added");
2887 fixture.push((trigger_id, ColliderEntry::Sphere(trigger), true));
2888
2889 let rays = [
2890 // Down the lattice's middle row, through the trigger first.
2891 Ray::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::X),
2892 // Another row, no trigger on it.
2893 Ray::new(DVec3::new(-10.0, 2.0, 0.0), DVec3::X),
2894 // Along +Z through a lattice sphere and the capsule behind it.
2895 Ray::new(DVec3::new(0.0, 0.0, -10.0), DVec3::Z),
2896 // Between the rows, so only the box is wide enough to be hit.
2897 Ray::new(DVec3::new(-10.0, 1.5, 0.0), DVec3::X),
2898 // Diagonally across the lattice.
2899 Ray::new(DVec3::new(-10.0, -10.0, 0.0), DVec3::new(1.0, 1.0, 0.0)),
2900 // Nowhere near anything.
2901 Ray::new(DVec3::new(-10.0, 20.0, 0.0), DVec3::X),
2902 // Bounded short of the first solid collider, so `t_max` decides.
2903 Ray::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::X).with_bounds(0.0, 5.0),
2904 ];
2905 let sweeps = [
2906 (
2907 Segment::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::new(10.0, 0.0, 0.0)),
2908 0.2,
2909 ),
2910 // Between two rows, close enough that the swept volume reaches
2911 // both — the case a centre-line traversal used to drop.
2912 (
2913 Segment::new(DVec3::new(-10.0, 0.7, 0.0), DVec3::new(10.0, 0.7, 0.0)),
2914 0.35,
2915 ),
2916 (
2917 Segment::new(DVec3::new(0.0, 3.0, -10.0), DVec3::new(0.0, 3.0, 10.0)),
2918 0.1,
2919 ),
2920 // Starting inside a collider.
2921 (
2922 Segment::new(DVec3::new(0.0, 3.0, 0.0), DVec3::new(0.1, 3.0, 0.0)),
2923 0.2,
2924 ),
2925 // Nowhere near anything.
2926 (
2927 Segment::new(DVec3::new(20.0, 20.0, 20.0), DVec3::new(30.0, 30.0, 30.0)),
2928 0.5,
2929 ),
2930 ];
2931 let aabbs = [
2932 Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.2)),
2933 Aabb::from_centre_half(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.6)),
2934 Aabb::from_centre_half(DVec3::new(50.0, 50.0, 0.0), DVec3::splat(1.0)),
2935 Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(10.0)),
2936 ];
2937
2938 // ── The exclusive form's answers, before the view borrows the world ──
2939 let plain_sweeps: Vec<Option<(ColliderId, ShapeHit)>> = sweeps
2940 .iter()
2941 .map(|(segment, radius)| world.sweep_sphere(segment, *radius))
2942 .collect();
2943 // The same sweeps with the collider each one actually hits left out —
2944 // the query a body sweeping its own path runs, and the only form of it
2945 // where the exclusion is guaranteed to change the answer. The last
2946 // entry is the opposite case: excluding a collider that sweep never
2947 // reaches, which must change nothing.
2948 let mut excluded_sweeps: Vec<(Segment, f64, ColliderId)> = sweeps
2949 .iter()
2950 .zip(&plain_sweeps)
2951 .filter_map(|((segment, radius), hit)| hit.map(|(id, _)| (*segment, *radius, id)))
2952 .collect();
2953 excluded_sweeps.push((sweeps[2].0, sweeps[2].1, row_start));
2954
2955 let exclusive = ProbeAnswers {
2956 rays: rays.iter().map(|ray| world.cast_ray(ray)).collect(),
2957 sweeps: plain_sweeps,
2958 excluded_sweeps: excluded_sweeps
2959 .iter()
2960 .map(|(segment, radius, skip)| {
2961 world.sweep_sphere_excluding(segment, *radius, Some(*skip))
2962 })
2963 .collect(),
2964 aabbs: aabbs
2965 .iter()
2966 .map(|aabb| {
2967 let mut ids = world.overlap_aabb(aabb);
2968 ids.sort_unstable_by_key(|id| id.index());
2969 ids
2970 })
2971 .collect(),
2972 };
2973
2974 // ── The scan, which shares no code with the traversal ─────────────
2975 let solid = |skip: Option<ColliderId>| {
2976 fixture
2977 .iter()
2978 .filter(move |(id, _, is_trigger)| !is_trigger && Some(*id) != skip)
2979 };
2980 let closest =
2981 |hits: &mut dyn Iterator<Item = ShapeHit>| hits.map(|hit| hit.t).min_by(f64::total_cmp);
2982 let entry_of = |wanted: ColliderId| {
2983 fixture
2984 .iter()
2985 .find(|(id, _, _)| *id == wanted)
2986 .map(|(_, entry, is_trigger)| (entry.clone(), *is_trigger))
2987 .expect("the query named a collider the fixture does not hold")
2988 };
2989
2990 let mut rays_that_hit = 0usize;
2991 for (ray, answer) in rays.iter().zip(&exclusive.rays) {
2992 let scanned =
2993 closest(&mut solid(None).filter_map(|(_, entry, _)| scan_ray_one(ray, entry)));
2994 assert_eq!(
2995 answer.map(|(_, hit)| hit.t),
2996 scanned,
2997 "the closest solid hit along {ray:?}",
2998 );
2999 if let Some((id, hit)) = answer {
3000 let (entry, is_trigger) = entry_of(*id);
3001 assert!(!is_trigger, "a cast reported a trigger: {ray:?}");
3002 assert_eq!(
3003 scan_ray_one(ray, &entry),
3004 Some(*hit),
3005 "the collider the cast named does not produce the hit it reported",
3006 );
3007 rays_that_hit += 1;
3008 }
3009 }
3010 assert!(
3011 rays_that_hit >= 4 && rays_that_hit < rays.len(),
3012 "{rays_that_hit} of {} ray probes hit, so the comparison above was \
3013 mostly empty on one side or never exercised a miss",
3014 rays.len(),
3015 );
3016
3017 // The trigger is genuinely in the way of the first ray, so skipping it
3018 // is a branch this run takes rather than one it never reaches.
3019 let with_triggers = closest(
3020 &mut fixture
3021 .iter()
3022 .filter_map(|(_, entry, _)| scan_ray_one(&rays[0], entry)),
3023 );
3024 assert!(
3025 with_triggers < exclusive.rays[0].map(|(_, hit)| hit.t),
3026 "the trigger is not in front of the first ray's solid hits, so \
3027 nothing here would notice if triggers stopped being skipped",
3028 );
3029
3030 let mut sweeps_that_hit = 0usize;
3031 for ((segment, radius), answer) in sweeps.iter().zip(&exclusive.sweeps) {
3032 let scanned = closest(
3033 &mut solid(None)
3034 .filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
3035 );
3036 assert_eq!(
3037 answer.map(|(_, hit)| hit.t),
3038 scanned,
3039 "the closest solid hit sweeping r{radius} along {segment:?}",
3040 );
3041 if let Some((id, hit)) = answer {
3042 let (entry, is_trigger) = entry_of(*id);
3043 assert!(!is_trigger, "a sweep reported a trigger: {segment:?}");
3044 assert_eq!(
3045 scan_sweep_one(segment, *radius, &entry),
3046 Some(*hit),
3047 "the collider the sweep named does not produce the hit it reported",
3048 );
3049 sweeps_that_hit += 1;
3050 }
3051 }
3052 assert!(
3053 sweeps_that_hit >= 3 && sweeps_that_hit < sweeps.len(),
3054 "{sweeps_that_hit} of {} sweep probes hit, so the comparison above \
3055 was mostly empty on one side or never exercised a miss",
3056 sweeps.len(),
3057 );
3058
3059 let mut exclusion_mattered = 0usize;
3060 let mut exclusion_was_moot = 0usize;
3061 for ((segment, radius, skip), answer) in
3062 excluded_sweeps.iter().zip(&exclusive.excluded_sweeps)
3063 {
3064 let scanned = closest(
3065 &mut solid(Some(*skip))
3066 .filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
3067 );
3068 assert_eq!(
3069 answer.map(|(_, hit)| hit.t),
3070 scanned,
3071 "the closest hit excluding {skip:?}, sweeping r{radius} along {segment:?}",
3072 );
3073 assert_ne!(
3074 answer.map(|(id, _)| id),
3075 Some(*skip),
3076 "the excluded collider came back anyway",
3077 );
3078 // Whether the exclusion was load-bearing is the scan's to say, not
3079 // the query's: it is whether the closest solid hit moved when that
3080 // collider left the fixture.
3081 let unexcluded = closest(
3082 &mut solid(None)
3083 .filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
3084 );
3085 if unexcluded == scanned {
3086 exclusion_was_moot += 1;
3087 } else {
3088 exclusion_mattered += 1;
3089 }
3090 }
3091 assert!(
3092 exclusion_mattered >= 3 && exclusion_was_moot >= 1,
3093 "{exclusion_mattered} exclusions changed the answer and \
3094 {exclusion_was_moot} did not, so one of the two cases never ran",
3095 );
3096
3097 let mut widest = 0usize;
3098 for (aabb, answer) in aabbs.iter().zip(&exclusive.aabbs) {
3099 let mut scanned: Vec<ColliderId> = fixture
3100 .iter()
3101 .filter(|(_, entry, _)| entry.aabb().intersects(aabb))
3102 .map(|(id, _, _)| *id)
3103 .collect();
3104 scanned.sort_unstable_by_key(|id| id.index());
3105 assert_eq!(&scanned, answer, "the AABBs meeting {aabb:?}");
3106 widest = widest.max(answer.len());
3107 }
3108 assert!(
3109 widest > 4,
3110 "the widest AABB probe found {widest} colliders, so the comparison \
3111 above was mostly two empty vectors",
3112 );
3113
3114 // ── The same answers under a shared borrow, from several threads ──
3115 // One scratch and one output buffer for the whole run, which is how a
3116 // `par_for` chunk holds them — and what makes a query that forgot to
3117 // clear its output visible here.
3118 let ask = |queries: &OverlapQueries<'_>| {
3119 let mut scratch = QueryScratch::new();
3120 let mut ids = Vec::new();
3121 ProbeAnswers {
3122 rays: rays
3123 .iter()
3124 .map(|ray| queries.cast_ray(ray, &mut scratch))
3125 .collect(),
3126 sweeps: sweeps
3127 .iter()
3128 .map(|(segment, radius)| queries.sweep_sphere(segment, *radius, &mut scratch))
3129 .collect(),
3130 excluded_sweeps: excluded_sweeps
3131 .iter()
3132 .map(|(segment, radius, skip)| {
3133 queries.sweep_sphere_excluding(segment, *radius, Some(*skip), &mut scratch)
3134 })
3135 .collect(),
3136 aabbs: aabbs
3137 .iter()
3138 .map(|aabb| {
3139 queries.overlap_aabb_into(aabb, &mut scratch, &mut ids);
3140 let mut found = ids.clone();
3141 found.sort_unstable_by_key(|id| id.index());
3142 found
3143 })
3144 .collect(),
3145 }
3146 };
3147
3148 let queries = world.overlap_queries();
3149 assert_eq!(ask(&queries), exclusive, "the calling thread's own answers");
3150
3151 std::thread::scope(|scope| {
3152 let handles: Vec<_> = (0..4).map(|_| scope.spawn(|| ask(&queries))).collect();
3153 for handle in handles {
3154 assert_eq!(
3155 handle.join().expect("a query thread panicked"),
3156 exclusive,
3157 "a thread sharing the view disagreed with the scan",
3158 );
3159 }
3160 });
3161 }
3162
3163 /// **A sphere overlap is shape-aware: the query radius is expanded by each
3164 /// collider's own radius.**
3165 ///
3166 /// `overlap_sphere(centre, R)` returns every collider whose *shape* overlaps
3167 /// the query sphere, so a sphere collider of radius `r_b` is returned iff
3168 /// its centre is within `R + r_b` of the query's — on every axis by the
3169 /// broadphase prefilter (whose leaf AABBs carry the collider's own extent),
3170 /// and off-axis by the exact shape test, which trims the prefilter's square
3171 /// back to the circle. The contract matters to `apps/horde`: its separation
3172 /// query passes `r_self + slack` and expects neighbours out to
3173 /// `r_self + slack + r_b`, which is only right because of this expansion —
3174 /// the guard for that lives here rather than in the consumer.
3175 ///
3176 /// The two families of cases exercise the two layers separately: the
3177 /// on-axis ones are decided by the broadphase, the 45° ones (in the z = 0
3178 /// plane) are admitted by the broadphase and decided by the exact shape
3179 /// test.
3180 #[test]
3181 fn a_sphere_overlap_is_expanded_by_the_colliders_own_radius() {
3182 let mut world = PhysicsWorld::new();
3183 let body = world.add_sphere(Sphere::new(DVec3::ZERO, 0.5));
3184 let mut scratch = QueryScratch::new();
3185 let mut out = Vec::new();
3186 let queries = world.overlap_queries();
3187
3188 let query_radius = 1.0;
3189 let boundary = query_radius + 0.5; // the body's radius
3190
3191 // On the query's own axis, the broadphase's AABB admission decides.
3192 queries.overlap_sphere_into(
3193 DVec3::new(boundary - 0.01, 0.0, 0.0),
3194 query_radius,
3195 &mut scratch,
3196 &mut out,
3197 );
3198 assert_eq!(
3199 ids_of(&out),
3200 vec![body],
3201 "a body whose centre is inside R + r_b is returned"
3202 );
3203
3204 queries.overlap_sphere_into(
3205 DVec3::new(boundary + 0.01, 0.0, 0.0),
3206 query_radius,
3207 &mut scratch,
3208 &mut out,
3209 );
3210 assert!(
3211 out.is_empty(),
3212 "a body whose centre is outside R + r_b is not returned"
3213 );
3214
3215 // The boundary is R + r_b, not R: a query radius alone, with the body's
3216 // centre at R + r_b/2, must still find it.
3217 queries.overlap_sphere_into(
3218 DVec3::new(query_radius + 0.25, 0.0, 0.0),
3219 query_radius,
3220 &mut scratch,
3221 &mut out,
3222 );
3223 assert_eq!(
3224 ids_of(&out),
3225 vec![body],
3226 "the query radius is expanded by the collider's own radius, not used raw"
3227 );
3228
3229 // At 45° in the z = 0 plane, the AABB prefilter still admits both
3230 // (axis offsets below R + r_b), so the exact shape test decides: the
3231 // boundary is the circle of radius R + r_b, not the square.
3232 // (R + r_b)/√2 ≈ 1.0607.
3233 queries.overlap_sphere_into(
3234 DVec3::new(1.05, 1.05, 0.0),
3235 query_radius,
3236 &mut scratch,
3237 &mut out,
3238 );
3239 assert_eq!(
3240 ids_of(&out),
3241 vec![body],
3242 "a body within the circle of radius R + r_b is returned even off-axis"
3243 );
3244
3245 queries.overlap_sphere_into(
3246 DVec3::new(1.07, 1.07, 0.0),
3247 query_radius,
3248 &mut scratch,
3249 &mut out,
3250 );
3251 assert!(
3252 out.is_empty(),
3253 "a body outside the circle of radius R + r_b is not returned, \
3254 even where the broadphase AABB would admit it"
3255 );
3256 }
3257
3258 /// One scratch, many queries: the buffers carry nothing between calls.
3259 ///
3260 /// The whole point of handing the caller the scratch is that it is reused,
3261 /// so a query that read a stale `candidates` from the call before it would
3262 /// be a defect this API introduced and the owning form cannot have.
3263 #[test]
3264 fn a_reused_scratch_does_not_leak_one_query_into_the_next() {
3265 let mut world = PhysicsWorld::new();
3266 world.add_sphere(Sphere::new(DVec3::ZERO, 0.5));
3267 world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 0.5));
3268
3269 let mut scratch = QueryScratch::new();
3270 let mut out = Vec::new();
3271 let queries = world.overlap_queries();
3272
3273 queries.overlap_sphere_into(DVec3::ZERO, 1.0, &mut scratch, &mut out);
3274 assert_eq!(out.len(), 1);
3275 queries.overlap_sphere_into(DVec3::new(0.0, 100.0, 0.0), 1.0, &mut scratch, &mut out);
3276 assert!(out.is_empty(), "a stale candidate survived the next query");
3277 queries.overlap_sphere_into(DVec3::new(20.0, 0.0, 0.0), 1.0, &mut scratch, &mut out);
3278 assert_eq!(out.len(), 1);
3279 }
3280
3281 #[test]
3282 fn adding_and_removing_a_collider_leaves_the_world_empty_again() {
3283 let mut world = PhysicsWorld::new();
3284 let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
3285 assert_eq!(world.len(), 1);
3286 assert!(!world.is_empty());
3287 assert!(world.remove(id));
3288 assert!(world.is_empty());
3289 }
3290
3291 #[test]
3292 fn remove_invalid_id_returns_false() {
3293 let mut world = PhysicsWorld::new();
3294 assert!(!world.remove(ColliderId::new(999, 0)));
3295 // A double remove is the same stale-id case.
3296 let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
3297 assert!(world.remove(id));
3298 assert!(!world.remove(id));
3299 }
3300
3301 #[test]
3302 fn add_sphere_then_cast_ray_hits() {
3303 let mut world = PhysicsWorld::new();
3304 world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
3305 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3306 let result = world.cast_ray(&ray);
3307 assert!(result.is_some());
3308 let (_id, hit) = result.unwrap();
3309 assert!((hit.t - 4.0).abs() < 0.001);
3310 }
3311
3312 #[test]
3313 fn cast_ray_misses_when_no_colliders() {
3314 let mut world = PhysicsWorld::new();
3315 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3316 assert!(world.cast_ray(&ray).is_none());
3317 }
3318
3319 #[test]
3320 fn add_multiple_and_cast_ray_finds_closest() {
3321 let mut world = PhysicsWorld::new();
3322 world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
3323 let close = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
3324 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3325 let (id, hit) = world.cast_ray(&ray).unwrap();
3326 assert_eq!(id, close);
3327 assert!((hit.t - 4.0).abs() < 0.001);
3328 }
3329
3330 /// **The excluded collider is dropped before the winner is picked, so the
3331 /// next-closest hit survives.**
3332 ///
3333 /// `near` sits where the swept sphere reaches it first and `far` behind it,
3334 /// so an implementation that ran the ordinary sweep and threw the answer
3335 /// away when it named `near` would report nothing at all. Excluding `near`
3336 /// has to return `far`, and excluding an id the world never issued has to
3337 /// return `near` again.
3338 #[test]
3339 fn sweep_sphere_excluding_keeps_the_next_closest_hit() {
3340 let mut world = PhysicsWorld::new();
3341 let near = world.add_sphere(Sphere::new(DVec3::new(0.0, 0.0, 0.0), 1.0));
3342 let far = world.add_sphere(Sphere::new(DVec3::new(3.0, 0.0, 0.0), 1.0));
3343 let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
3344
3345 let (id, _) = world.sweep_sphere(&seg, 0.5).expect("the sweep hits both");
3346 assert_eq!(id, near, "the unfiltered sweep answers the closest");
3347
3348 let (id, hit) = world
3349 .sweep_sphere_excluding(&seg, 0.5, Some(near))
3350 .expect("the one behind it is still there");
3351 assert_eq!(id, far, "excluding the closest must not lose the rest");
3352 assert!(
3353 (hit.t - 0.65).abs() < 0.001,
3354 "expected ~0.65, got {}",
3355 hit.t
3356 );
3357
3358 let (id, _) = world
3359 .sweep_sphere_excluding(&seg, 0.5, Some(ColliderId::new(999, 0)))
3360 .expect("an id the world never issued excludes nothing");
3361 assert_eq!(id, near);
3362
3363 // **The dangerous stale id is the one whose slot is still live.** An id
3364 // the world never issued names no slot at all, so ignoring it is easy;
3365 // an id whose index was reused names a slot that *is* occupied, by
3366 // something else. Excluding on the index alone would take the new
3367 // occupant out of the sweep, which is a hit silently lost rather than a
3368 // filter that did nothing.
3369 assert!(world.remove(near), "the collider was live");
3370 let reused = world.add_sphere(Sphere::new(DVec3::new(0.0, 0.0, 0.0), 1.0));
3371 assert_eq!(
3372 reused.index, near.index,
3373 "this test only says anything while the slot is actually reused"
3374 );
3375 assert_ne!(
3376 reused.generation, near.generation,
3377 "and the id has moved on"
3378 );
3379 let (id, _) = world
3380 .sweep_sphere_excluding(&seg, 0.5, Some(near))
3381 .expect("the stale id must not hide the collider that took its slot");
3382 assert_eq!(
3383 id, reused,
3384 "a generation that has moved on excludes nothing, so the sweep still \
3385 answers the shape occupying that slot"
3386 );
3387 }
3388
3389 #[test]
3390 fn sweep_sphere_hits_box() {
3391 let mut world = PhysicsWorld::new();
3392 world.add_box(BoxCollider::new(DVec3::ZERO, DVec3::splat(1.0)));
3393 let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
3394 let result = world.sweep_sphere(&seg, 0.5);
3395 assert!(result.is_some());
3396 let (_id, hit) = result.unwrap();
3397 // t should be (distance from start to inflated box near plane) / segment length
3398 // start=-5, sphere_r=0.5, box half=1.0, near=-1.5, distance=3.5, segment=10
3399 assert!(
3400 (hit.t - 0.35).abs() < 0.001,
3401 "expected ~0.35, got {}",
3402 hit.t
3403 );
3404 assert_eq!(hit.normal, DVec3::NEG_X);
3405 }
3406
3407 /// A sphere whose *centre* never enters the box still touches it, and the
3408 /// sweep has to say so.
3409 ///
3410 /// The broadphase used to traverse the centre line as a ray, so a box the
3411 /// sphere overlaps by anything less than its radius was dropped before the
3412 /// exact test ran. Every case below is a real contact: the centre line
3413 /// passes 0.3 above a box whose top is at y = 0, with a sphere of radius
3414 /// 0.5, so the sphere is 0.2 deep at its closest.
3415 #[test]
3416 fn sweep_sphere_hits_a_box_its_centre_line_misses() {
3417 let mut world = PhysicsWorld::new();
3418 world.add_box(BoxCollider::new(
3419 DVec3::new(0.0, -1.0, 0.0),
3420 DVec3::splat(1.0),
3421 ));
3422
3423 // Along the top face, never crossing it.
3424 let along = Segment::new(DVec3::new(-5.0, 0.3, 0.0), DVec3::new(5.0, 0.3, 0.0));
3425 let (_, hit) = world
3426 .sweep_sphere(&along, 0.5)
3427 .expect("a sphere grazing the top face touches it");
3428 assert!(hit.point.y <= 0.0 + 1e-9, "contact on the box: {hit:?}");
3429
3430 // Coming down onto it and stopping short: the surfaces meet, the
3431 // centres do not.
3432 let onto = Segment::new(DVec3::new(0.0, 1.0, 0.0), DVec3::new(0.0, 0.3, 0.0));
3433 let (_, hit) = world
3434 .sweep_sphere(&onto, 0.5)
3435 .expect("a sphere landing on the face touches it");
3436 assert!(hit.normal.y > 0.5, "the top face's normal: {hit:?}");
3437
3438 // And a genuine miss is still a miss: 0.6 clear of a 0.5 sphere.
3439 let clear = Segment::new(DVec3::new(-5.0, 0.6, 0.0), DVec3::new(5.0, 0.6, 0.0));
3440 assert!(
3441 world.sweep_sphere(&clear, 0.5).is_none(),
3442 "a sphere that does not reach the box must not report a hit",
3443 );
3444 }
3445
3446 #[test]
3447 fn rebuilding_after_the_last_removal_leaves_nothing_for_a_ray_to_hit() {
3448 let mut world = PhysicsWorld::new();
3449 let id = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
3450 world.remove(id);
3451 world.rebuild(); // no panics
3452 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3453 assert!(world.cast_ray(&ray).is_none());
3454 }
3455
3456 #[test]
3457 fn churn_after_the_first_query_keeps_the_tree() {
3458 // The behaviour the asteroids sample turns on: once the tree exists,
3459 // spawning and killing colliders updates it in place. If either path
3460 // dropped the tree instead, `bvh_cached` would read false right after
3461 // the mutation and every frame would pay a rebuild.
3462 let mut world = PhysicsWorld::new();
3463 let keep = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
3464 assert!(world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).is_some());
3465 assert!(format!("{world:?}").contains("bvh_cached: true"));
3466
3467 let bullet = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 0.5));
3468 assert!(
3469 format!("{world:?}").contains("bvh_cached: true"),
3470 "adding a collider threw the tree away"
3471 );
3472 // The new collider is in the tree, not merely in the slot array: the
3473 // ray now stops at it rather than at the one it used to reach.
3474 let (hit_id, _) = world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).unwrap();
3475 assert_eq!(hit_id, bullet);
3476
3477 assert!(world.remove(bullet));
3478 assert!(
3479 format!("{world:?}").contains("bvh_cached: true"),
3480 "removing a collider threw the tree away"
3481 );
3482 let (hit_id, _) = world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).unwrap();
3483 assert_eq!(hit_id, keep, "the removed collider still answers queries");
3484 assert_eq!(world.len(), 1);
3485 }
3486
3487 #[test]
3488 fn churn_through_a_recycled_slot_tracks_the_right_element() {
3489 // Collider slots and BVH element indices are two independent recycling
3490 // schemes. If the mapping between them went stale, the new occupant of
3491 // a slot would refit the *old* occupant's leaf — a collider that moves
3492 // when a different one is moved.
3493 let mut world = PhysicsWorld::new();
3494 let far = world.add_sphere(Sphere::new(DVec3::new(100.0, 0.0, 0.0), 1.0));
3495 let doomed = world.add_sphere(Sphere::new(DVec3::new(10.0, 0.0, 0.0), 1.0));
3496 assert!(world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).is_some());
3497
3498 assert!(world.remove(doomed));
3499 let reused = world.add_sphere(Sphere::new(DVec3::new(30.0, 0.0, 0.0), 1.0));
3500 assert_eq!(reused.index(), doomed.index(), "the slot must be recycled");
3501
3502 // Move the new occupant, then ask a *local* question about where it
3503 // landed. A local query is the one that can tell: it only descends
3504 // into leaves whose bounds reach the query, so a refit applied to some
3505 // other collider's leaf leaves this one still sitting at its old
3506 // bounds and out of reach. A long ray would not catch it — the ray
3507 // would pass through the stale bounds anyway and the narrow phase
3508 // would re-read the correct shape and paper over the mistake.
3509 assert!(world.set_sphere(reused, Sphere::new(DVec3::new(3.0, 0.0, 0.0), 1.0)));
3510 assert_eq!(
3511 ids_of(&world.overlap_sphere(DVec3::new(3.0, 0.0, 0.0), 0.5)),
3512 vec![reused],
3513 "the refit did not move the collider that was asked to move"
3514 );
3515 // And nothing else moved with it.
3516 assert!(
3517 world
3518 .overlap_sphere(DVec3::new(30.0, 0.0, 0.0), 0.5)
3519 .is_empty()
3520 );
3521 assert_eq!(
3522 world.aabb_of(far).unwrap().centre(),
3523 DVec3::new(100.0, 0.0, 0.0)
3524 );
3525 }
3526
3527 #[test]
3528 fn aabb_of_returns_correct_bounds() {
3529 let mut world = PhysicsWorld::new();
3530 let id = world.add_sphere(Sphere::new(DVec3::new(1.0, 2.0, 3.0), 0.5));
3531 let aabb = world.aabb_of(id).unwrap();
3532 assert_eq!(aabb.min, DVec3::new(0.5, 1.5, 2.5));
3533 assert_eq!(aabb.max, DVec3::new(1.5, 2.5, 3.5));
3534 }
3535
3536 #[test]
3537 fn aabb_of_unknown_id_returns_none() {
3538 let world = PhysicsWorld::new();
3539 assert!(world.aabb_of(ColliderId::new(42, 0)).is_none());
3540 }
3541
3542 #[test]
3543 fn stale_id_does_not_address_the_slot_s_new_occupant() {
3544 // ABA: remove a collider, add another that recycles the same slot, and
3545 // check the retained id resolves to nothing rather than to the new
3546 // occupant.
3547 let mut world = PhysicsWorld::new();
3548 let old = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
3549 assert!(world.remove(old));
3550
3551 let new = world.add_sphere(Sphere::new(DVec3::new(9.0, 0.0, 0.0), 2.0));
3552 assert_eq!(new.index(), old.index(), "the slot must be recycled");
3553 assert_ne!(new, old, "but the id must not be");
3554
3555 assert!(world.aabb_of(old).is_none());
3556 assert!(!world.remove(old));
3557 assert!(!world.set_trigger(old, true));
3558 assert!(!world.is_trigger(old));
3559 assert!(!world.set_sphere(old, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));
3560
3561 // The new occupant is untouched by any of the above.
3562 let aabb = world.aabb_of(new).unwrap();
3563 assert_eq!(aabb.centre(), DVec3::new(9.0, 0.0, 0.0));
3564 assert_eq!(world.len(), 1);
3565 }
3566
3567 #[test]
3568 fn the_worlds_debug_output_reports_how_many_colliders_it_holds() {
3569 let mut world = PhysicsWorld::new();
3570 world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
3571 let s = format!("{world:?}");
3572 assert!(s.contains("collider_count: 1"));
3573 }
3574
3575 // ── Overlap tests ─────────────────────────────────────────────────
3576
3577 #[test]
3578 fn overlap_sphere_finds_sphere() {
3579 let mut world = PhysicsWorld::new();
3580 world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
3581 let results = world.overlap_sphere(DVec3::ZERO, 4.0);
3582 assert_eq!(results.len(), 1);
3583 }
3584
3585 #[test]
3586 fn overlap_sphere_misses_distant() {
3587 let mut world = PhysicsWorld::new();
3588 world.add_sphere(Sphere::new(DVec3::new(10.0, 0.0, 0.0), 1.0));
3589 let results = world.overlap_sphere(DVec3::ZERO, 2.0);
3590 assert!(results.is_empty());
3591 }
3592
3593 #[test]
3594 fn overlap_sphere_finds_box() {
3595 let mut world = PhysicsWorld::new();
3596 world.add_box(BoxCollider::new(DVec3::ZERO, DVec3::splat(1.0)));
3597 let results = world.overlap_sphere(DVec3::new(2.0, 0.0, 0.0), 1.5);
3598 assert_eq!(results.len(), 1);
3599 }
3600
3601 #[test]
3602 fn overlap_sphere_finds_capsule() {
3603 let mut world = PhysicsWorld::new();
3604 world.add_capsule(Capsule::new(DVec3::ZERO, 0.5, 2.0));
3605 let results = world.overlap_sphere(DVec3::new(0.0, 0.0, 0.0), 3.0);
3606 assert_eq!(results.len(), 1);
3607 }
3608
3609 #[test]
3610 fn overlap_sphere_finds_multiple() {
3611 let mut world = PhysicsWorld::new();
3612 world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
3613 world.add_sphere(Sphere::new(DVec3::new(-2.0, 0.0, 0.0), 1.0));
3614 world.add_sphere(Sphere::new(DVec3::new(0.0, 6.0, 0.0), 1.0));
3615 let results = world.overlap_sphere(DVec3::ZERO, 4.0);
3616 assert_eq!(results.len(), 2); // only the two on x-axis
3617 }
3618
3619 #[test]
3620 fn overlap_aabb_finds_all_intersecting() {
3621 let mut world = PhysicsWorld::new();
3622 world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
3623 world.add_sphere(Sphere::new(DVec3::new(-2.0, 0.0, 0.0), 1.0));
3624 world.add_sphere(Sphere::new(DVec3::new(0.0, 10.0, 0.0), 1.0));
3625 let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(3.0));
3626 let results = world.overlap_aabb(&query);
3627 assert_eq!(results.len(), 2);
3628 }
3629
3630 #[test]
3631 fn overlap_aabb_empty_world() {
3632 let mut world = PhysicsWorld::new();
3633 let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(10.0));
3634 assert!(world.overlap_aabb(&query).is_empty());
3635 }
3636
3637 // ── Dynamic update (refit) tests ────────────────────────────────────
3638
3639 #[test]
3640 fn set_sphere_moves_collider_in_ray_cast() {
3641 let mut world = PhysicsWorld::new();
3642 let id = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
3643 // Initially hits.
3644 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3645 assert!(world.cast_ray(&ray).is_some());
3646
3647 // Move the sphere far away via set_sphere.
3648 assert!(world.set_sphere(id, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));
3649
3650 // Should no longer hit with +X ray.
3651 assert!(world.cast_ray(&ray).is_none());
3652 }
3653
3654 #[test]
3655 fn set_box_updates_overlap_query() {
3656 let mut world = PhysicsWorld::new();
3657 let id = world.add_box(BoxCollider::new(
3658 DVec3::new(5.0, 0.0, 0.0),
3659 DVec3::splat(1.0),
3660 ));
3661
3662 // Overlap near origin should not find it.
3663 let results = world.overlap_sphere(DVec3::ZERO, 2.0);
3664 assert!(results.is_empty());
3665
3666 // Move it to origin.
3667 assert!(world.set_box(
3668 id,
3669 BoxCollider::new(DVec3::new(1.0, 0.0, 0.0), DVec3::splat(1.0))
3670 ));
3671
3672 // Now overlap should find it.
3673 let results = world.overlap_sphere(DVec3::ZERO, 3.0);
3674 assert_eq!(results.len(), 1);
3675 assert_eq!(results[0].0, id);
3676 }
3677
3678 #[test]
3679 fn set_sphere_on_invalid_id_returns_false() {
3680 let mut world = PhysicsWorld::new();
3681 assert!(!world.set_sphere(ColliderId::new(999, 0), Sphere::new(DVec3::ZERO, 1.0)));
3682 }
3683
3684 #[test]
3685 fn set_sphere_refits_the_right_leaf_when_colliders_are_not_centroid_ordered() {
3686 // The BVH sorts each range by centroid while building, so the leaf
3687 // order differs from the order colliders were added. Moving slot 0
3688 // must move the collider at x = 20, not the one at x = 5.
3689 let mut world = PhysicsWorld::new();
3690 let far = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
3691 let near = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
3692
3693 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3694 let (id, hit) = world
3695 .cast_ray(&ray)
3696 .expect("the near sphere is ahead of the ray");
3697 assert_eq!(id, near);
3698 assert!((hit.t - 4.0).abs() < 1e-9, "t = {}", hit.t);
3699
3700 // Move the *far* sphere behind the ray origin. The near one must
3701 // still be found, at the same distance.
3702 assert!(world.set_sphere(far, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));
3703 let (id, hit) = world
3704 .cast_ray(&ray)
3705 .expect("the untouched sphere must not vanish");
3706 assert_eq!(id, near);
3707 assert!((hit.t - 4.0).abs() < 1e-9, "t = {}", hit.t);
3708 }
3709
3710 #[test]
3711 fn set_capsule_refits_bvh() {
3712 let mut world = PhysicsWorld::new();
3713 let id = world.add_capsule(Capsule::new(DVec3::new(5.0, 0.0, 0.0), 0.5, 1.0));
3714 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3715
3716 // Initially hits.
3717 assert!(world.cast_ray(&ray).is_some());
3718
3719 // Move it.
3720 assert!(world.set_capsule(id, Capsule::new(DVec3::new(-30.0, 30.0, 0.0), 0.5, 1.0)));
3721
3722 // Should miss with +X ray.
3723 assert!(world.cast_ray(&ray).is_none());
3724 }
3725
3726 #[test]
3727 fn set_sphere_after_removal_fails() {
3728 let mut world = PhysicsWorld::new();
3729 let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
3730 world.remove(id);
3731 assert!(!world.set_sphere(id, Sphere::new(DVec3::new(1.0, 0.0, 0.0), 1.0)));
3732 }
3733
3734 #[test]
3735 fn sweep_sphere_hits_capsule_exact() {
3736 let mut world = PhysicsWorld::new();
3737 world.add_capsule(Capsule::new(DVec3::ZERO, 0.5, 2.0));
3738 let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
3739 let result = world.sweep_sphere(&seg, 0.5);
3740 assert!(result.is_some());
3741 }
3742
3743 #[test]
3744 fn sweep_sphere_misses_distant_capsule() {
3745 let mut world = PhysicsWorld::new();
3746 world.add_capsule(Capsule::new(DVec3::new(100.0, 0.0, 0.0), 0.5, 2.0));
3747 let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
3748 assert!(world.sweep_sphere(&seg, 0.5).is_none());
3749 }
3750
3751 // ── Trigger tests ──────────────────────────────────────────────────
3752
3753 #[test]
3754 fn trigger_defaults_to_false() {
3755 let mut world = PhysicsWorld::new();
3756 let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
3757 assert!(!world.is_trigger(id));
3758 }
3759
3760 #[test]
3761 fn set_trigger_toggles_flag() {
3762 let mut world = PhysicsWorld::new();
3763 let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
3764 assert!(world.set_trigger(id, true));
3765 assert!(world.is_trigger(id));
3766 assert!(world.set_trigger(id, false));
3767 assert!(!world.is_trigger(id));
3768 }
3769
3770 #[test]
3771 fn set_trigger_on_invalid_id_returns_false() {
3772 let mut world = PhysicsWorld::new();
3773 assert!(!world.set_trigger(ColliderId::new(42, 0), true));
3774 }
3775
3776 #[test]
3777 fn trigger_is_transparent_to_rays_and_sweeps() {
3778 let mut world = PhysicsWorld::new();
3779 let trigger = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
3780 assert!(world.set_trigger(trigger, true));
3781
3782 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3783 assert!(
3784 world.cast_ray(&ray).is_none(),
3785 "a trigger must not stop a bullet"
3786 );
3787
3788 let seg = Segment::new(DVec3::ZERO, DVec3::new(10.0, 0.0, 0.0));
3789 assert!(world.sweep_sphere(&seg, 0.5).is_none());
3790 }
3791
3792 #[test]
3793 fn trigger_still_shows_up_in_overlap_queries() {
3794 let mut world = PhysicsWorld::new();
3795 let trigger = world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
3796 assert!(world.set_trigger(trigger, true));
3797
3798 assert_eq!(
3799 ids_of(&world.overlap_sphere(DVec3::ZERO, 4.0)),
3800 vec![trigger]
3801 );
3802 let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(4.0));
3803 assert_eq!(world.overlap_aabb(&query), vec![trigger]);
3804 }
3805
3806 #[test]
3807 fn solid_collider_behind_a_trigger_is_still_hit() {
3808 let mut world = PhysicsWorld::new();
3809 let trigger = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
3810 world.set_trigger(trigger, true);
3811 let solid = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
3812
3813 let ray = Ray::new(DVec3::ZERO, DVec3::X);
3814 let (id, hit) = world.cast_ray(&ray).expect("the solid sphere is behind it");
3815 assert_eq!(id, solid);
3816 assert!((hit.t - 19.0).abs() < 1e-9, "t = {}", hit.t);
3817 }
3818
3819 // ── Swept capsule ──────────────────────────────────────────────────
3820
3821 /// **The broadphase bounds of a capsule sweep reach as high as the
3822 /// capsule.** A ledge above the sphere's bounds and below the capsule's is
3823 /// never offered to the narrow phase if the traversal box is only inflated
3824 /// by the radius — the exact test that would have caught it never runs.
3825 #[test]
3826 fn a_capsule_sweeps_broadphase_reaches_a_ledge_the_sphere_sweeps_does_not() {
3827 let (radius, half_height) = (0.4, 1.5);
3828 let mut world = PhysicsWorld::new();
3829 // Sits above the radius the sphere sweep inflates by, and well inside
3830 // the `radius + half_height` the capsule sweep needs.
3831 let ledge = world.add_box(BoxCollider::new(
3832 DVec3::new(2.0, 1.1, 0.0),
3833 DVec3::new(1.0, 0.1, 1.0),
3834 ));
3835 let segment = Segment::new(DVec3::new(-3.0, 0.0, 0.0), DVec3::new(3.0, 0.0, 0.0));
3836
3837 assert!(
3838 world.sweep_sphere(&segment, radius).is_none(),
3839 "the sphere passes under the ledge, or the capsule reaching it proves nothing",
3840 );
3841 let (id, hit) = world
3842 .sweep_capsule(&segment, radius, half_height)
3843 .expect("the capsule's shoulder is level with the ledge");
3844 assert_eq!(id, ledge);
3845 assert_eq!(hit.normal, DVec3::NEG_X);
3846 }
3847
3848 /// A character registered in the world sits on the start of every segment
3849 /// it sweeps. Excluding it in the narrow phase keeps the *next* hit — the
3850 /// wall it was walking into — which a caller discarding a self-hit
3851 /// afterwards has already lost.
3852 #[test]
3853 fn a_capsule_sweep_excluding_its_own_collider_keeps_the_wall_behind_it() {
3854 let (radius, half_height) = (0.4, 0.9);
3855 let mut world = PhysicsWorld::new();
3856 let character = world.add_capsule(Capsule::new(DVec3::ZERO, radius, half_height));
3857 let wall = world.add_box(BoxCollider::new(
3858 DVec3::new(3.0, 0.0, 0.0),
3859 DVec3::new(0.5, 5.0, 5.0),
3860 ));
3861 let segment = Segment::new(DVec3::ZERO, DVec3::new(4.0, 0.0, 0.0));
3862
3863 let (self_id, self_hit) = world
3864 .sweep_capsule(&segment, radius, half_height)
3865 .expect("without the exclusion the character finds itself");
3866 assert_eq!(self_id, character);
3867 assert_eq!(self_hit.t, 0.0);
3868
3869 let (id, hit) = world
3870 .sweep_capsule_excluding(&segment, radius, half_height, Some(character))
3871 .expect("the wall survives the exclusion");
3872 assert_eq!(id, wall);
3873 // Wall's -X face at x = 2.5, the flank meets it at x = 2.1 along a 4 m path.
3874 assert!((hit.t - 0.525).abs() < 1e-12, "t = {}", hit.t);
3875 }
3876
3877 /// A trigger is non-solid for the capsule sweep exactly as it is for the
3878 /// sphere sweep — the two share one candidate loop, and this is what says
3879 /// the capsule path goes through it.
3880 #[test]
3881 fn a_capsule_sweep_passes_through_a_trigger_to_the_solid_behind_it() {
3882 let (radius, half_height) = (0.4, 0.9);
3883 let mut world = PhysicsWorld::new();
3884 let trigger = world.add_box(BoxCollider::new(
3885 DVec3::new(2.0, 0.0, 0.0),
3886 DVec3::new(0.5, 5.0, 5.0),
3887 ));
3888 assert!(world.set_trigger(trigger, true));
3889 let solid = world.add_box(BoxCollider::new(
3890 DVec3::new(6.0, 0.0, 0.0),
3891 DVec3::new(0.5, 5.0, 5.0),
3892 ));
3893 let segment = Segment::new(DVec3::ZERO, DVec3::new(10.0, 0.0, 0.0));
3894
3895 let (id, hit) = world
3896 .sweep_capsule(&segment, radius, half_height)
3897 .expect("the solid slab is behind the trigger");
3898 assert_eq!(
3899 id, solid,
3900 "the trigger is in the way and must be passed through"
3901 );
3902 // Solid's -X face at x = 5.5, flank meets it at x = 5.1 along a 10 m path.
3903 assert!((hit.t - 0.51).abs() < 1e-12, "t = {}", hit.t);
3904 }
3905}
3906
3907#[cfg(test)]
3908#[path = "world/ray_exclusion_tests.rs"]
3909mod ray_exclusion_tests;
3910
3911#[cfg(test)]
3912#[path = "world/query_filter_tests.rs"]
3913mod query_filter_tests;
3914
3915#[cfg(test)]
3916#[path = "world/overlap_hit_tests.rs"]
3917mod overlap_hit_tests;
3918
3919#[cfg(test)]
3920#[path = "world/lying_capsule_tests.rs"]
3921mod lying_capsule_tests;
3922
3923#[cfg(test)]
3924#[path = "world/turned_box_tests.rs"]
3925mod turned_box_tests;
3926
3927#[cfg(test)]
3928#[path = "world/candidate_sweep_tests.rs"]
3929mod candidate_sweep_tests;
3930
3931#[cfg(test)]
3932#[path = "world/query_digest_tests.rs"]
3933mod query_digest_tests;
3934
3935#[cfg(test)]
3936#[path = "world/turned_body_tests.rs"]
3937mod turned_body_tests;
3938
3939#[cfg(test)]
3940#[path = "world/compound_tests.rs"]
3941mod compound_tests;
3942
3943#[cfg(test)]
3944#[path = "world/turned_capsule_tests.rs"]
3945mod turned_capsule_tests;
3946
3947#[cfg(test)]
3948#[path = "world/arc_selection_tests.rs"]
3949mod arc_selection_tests;
3950#[cfg(test)]
3951#[path = "world/arc_sweep_tests.rs"]
3952mod arc_sweep_tests;
3953
3954#[cfg(test)]
3955#[path = "world/layer_prune_tests.rs"]
3956mod layer_prune_tests;