Skip to main content

nadir/
collisions.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! [`Collisions`]: the entities' colliders, for movement, triggers and
16//! queries, and the trigger events.
17
18use nadir_collision::{CollisionWorld, Contact, TileGrid, Triggers, move_and_slide};
19use nadir_core::Vec2;
20use nadir_ecs::{Entity, Events, SparseSet};
21
22use crate::{Collider, Transform, Velocity};
23
24/// A collider began to overlap a trigger, in this tick. The system
25/// `nadir::triggers` sends it, in the tick stage `PostMovement`.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct TriggerEnter {
28    /// The entity with the trigger.
29    pub trigger: Entity,
30    /// The entity whose collider it detects.
31    pub other: Entity,
32}
33
34/// A collider stopped overlapping a trigger, in this tick, or one of the
35/// two left: lost its collider or its `Transform`, or was despawned. The
36/// system `nadir::triggers` sends it, in the tick stage `PostMovement`.
37/// Either entity may be dead by then: check with `World::is_alive`.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub struct TriggerExit {
40    /// The entity with the trigger.
41    pub trigger: Entity,
42    /// The entity whose collider it detected.
43    pub other: Entity,
44}
45
46/// A slot of no collider.
47const NONE: u32 = u32::MAX;
48
49/// The colliders of the entities that have a [`Collider`] and a
50/// [`Transform`], in a [`CollisionWorld`]: a resource that the engine
51/// rebuilds each tick, in the system `nadir::movement`.
52///
53/// Systems query it through [`Collisions::world`], whose answers are
54/// collider indices: [`Collisions::entity`] turns them into entities, and
55/// [`Collisions::index`] an entity into the index to `ignore` in a cast.
56/// The tile grid is set here too.
57///
58/// What it holds during a tick:
59///
60/// - From `nadir::movement` on, the colliders of this tick, each moved as
61///   its entity moved.
62/// - `nadir::triggers` copies every collider's position from its
63///   `Transform` before it looks for overlaps, so a system that moves an
64///   entity in `Movement` after the engine's movement, or in
65///   `PostMovement` before `nadir::triggers`, moves its collider too.
66/// - After that, and until the next tick's `nadir::movement` (in the
67///   `Input` and `Gameplay` stages, and in frames), it is as the last
68///   tick left it. An entity despawned since still answers, and one
69///   spawned since is missing: check what [`Collisions::entity`] gives
70///   with `World::is_alive`.
71pub struct Collisions {
72    world: CollisionWorld,
73    /// Each collider's entity, by index: `[0]` for the last rebuild, `[1]`
74    /// for the one before, which the exits of the last tick's pairs are
75    /// looked up in.
76    entities: [Vec<Entity>; 2],
77    /// Each entity's collider index, by the entity's index, for the same
78    /// two rebuilds. A slot may be stale: it counts only when `entities`
79    /// gives back the same entity.
80    slots: [Vec<u32>; 2],
81    triggers: Triggers,
82    /// What the last move touched. Nothing reads it yet.
83    contacts: Vec<Contact>,
84}
85
86impl Collisions {
87    /// No colliders and an empty tile grid, hashing in cells of
88    /// [`CollisionWorld::DEFAULT_CELL_SIZE`].
89    pub fn new() -> Self {
90        Self::with_world(CollisionWorld::new())
91    }
92
93    /// No colliders and an empty tile grid, hashing in cells of
94    /// `cell_size` pixels: use at least twice the size of a typical
95    /// collider. Insert it as a resource to replace the engine's.
96    ///
97    /// # Panics
98    ///
99    /// If `cell_size` is not a finite number above 0.
100    pub fn with_cell_size(cell_size: f32) -> Self {
101        Self::with_world(CollisionWorld::with_cell_size(cell_size))
102    }
103
104    fn with_world(world: CollisionWorld) -> Self {
105        Self {
106            world,
107            entities: [Vec::new(), Vec::new()],
108            slots: [Vec::new(), Vec::new()],
109            triggers: Triggers::new(),
110            contacts: Vec::new(),
111        }
112    }
113
114    /// The collision world, for queries and casts.
115    pub fn world(&self) -> &CollisionWorld {
116        &self.world
117    }
118
119    /// The tile grid.
120    pub fn grid(&self) -> &TileGrid {
121        self.world.grid()
122    }
123
124    /// The tile grid, to change tiles.
125    pub fn grid_mut(&mut self) -> &mut TileGrid {
126        self.world.grid_mut()
127    }
128
129    /// Replaces the tile grid.
130    pub fn set_grid(&mut self, grid: TileGrid) {
131        self.world.set_grid(grid);
132    }
133
134    /// The entity of collider `index`, as of the last rebuild. It may have
135    /// been despawned since (see [`Collisions`]).
136    ///
137    /// # Panics
138    ///
139    /// If there is no collider `index`.
140    pub fn entity(&self, index: u32) -> Entity {
141        match self.entities[0].get(index as usize) {
142            Some(&entity) => entity,
143            None => panic!(
144                "there is no collider {index}: the world has {}",
145                self.entities[0].len()
146            ),
147        }
148    }
149
150    /// The index of `entity`'s collider as of the last rebuild, or `None`
151    /// if it had none then.
152    pub fn index(&self, entity: Entity) -> Option<u32> {
153        let index = *self.slots[0].get(entity.index() as usize)?;
154        (self.entities[0].get(index as usize) == Some(&entity)).then_some(index)
155    }
156
157    /// Replaces the colliders with those of the entities that have a
158    /// `Collider` and a `Transform`, each at its entity's position.
159    pub(crate) fn rebuild(
160        &mut self,
161        colliders: &SparseSet<Collider>,
162        transforms: &SparseSet<Transform>,
163    ) {
164        self.entities.swap(0, 1);
165        self.slots.swap(0, 1);
166        let entities = &mut self.entities[0];
167        let slots = &mut self.slots[0];
168        entities.clear();
169        // In the colliders' order, which their insert and remove history
170        // fixes: the order the movers move in.
171        let colliders = colliders.iter().filter_map(|(entity, collider)| {
172            let transform = transforms.get(entity)?;
173            let at = entity.index() as usize;
174            if slots.len() <= at {
175                slots.resize(at + 1, NONE);
176            }
177            slots[at] = u32::try_from(entities.len()).unwrap_or(NONE);
178            entities.push(entity);
179            Some((bits(entity), transform.position, collider.0))
180        });
181        self.world.rebuild(colliders);
182    }
183
184    /// Moves every collider whose entity has a `Velocity` by its velocity
185    /// for `dt` seconds, sliding along what it meets, in index order: each
186    /// sees where the ones before it went. Writes their `Transform`s.
187    pub(crate) fn move_colliders(
188        &mut self,
189        velocities: &SparseSet<Velocity>,
190        transforms: &mut SparseSet<Transform>,
191        dt: f32,
192    ) {
193        for (index, &entity) in (0u32..).zip(&self.entities[0]) {
194            let Some(velocity) = velocities.get(entity) else {
195                continue;
196            };
197            let delta = velocity.0 * dt;
198            let Some(transform) = transforms.get_mut(entity) else {
199                continue;
200            };
201            if delta == Vec2::ZERO {
202                continue;
203            }
204            let end = move_and_slide(
205                &self.world,
206                index,
207                transform.position,
208                delta,
209                &mut self.contacts,
210            );
211            self.world.set_position(index, end);
212            transform.position = end;
213        }
214    }
215
216    /// Moves every collider to its entity's position, where they differ.
217    pub(crate) fn sync(&mut self, transforms: &SparseSet<Transform>) {
218        for (index, &entity) in (0u32..).zip(&self.entities[0]) {
219            if let Some(transform) = transforms.get(entity)
220                && self.world.position(index) != transform.position
221            {
222                self.world.set_position(index, transform.position);
223            }
224        }
225    }
226
227    /// Finds the trigger pairs that began and ended since the last call,
228    /// and sends them as events.
229    pub(crate) fn update_triggers(
230        &mut self,
231        enter: &mut Events<TriggerEnter>,
232        exit: &mut Events<TriggerExit>,
233    ) {
234        self.triggers.update(&self.world);
235        for pair in self.triggers.entered() {
236            if let (Some(trigger), Some(other)) =
237                (self.resolve(0, pair.trigger), self.resolve(0, pair.other))
238            {
239                enter.send(TriggerEnter { trigger, other });
240            }
241        }
242        // The pairs that ended were found among the last rebuild's
243        // colliders.
244        for pair in self.triggers.exited() {
245            if let (Some(trigger), Some(other)) =
246                (self.resolve(1, pair.trigger), self.resolve(1, pair.other))
247            {
248                exit.send(TriggerExit { trigger, other });
249            }
250        }
251    }
252
253    /// The entity whose collider had `id` in rebuild `which`: 0 for the
254    /// last, 1 for the one before.
255    fn resolve(&self, which: usize, id: u64) -> Option<Entity> {
256        // The low half of an id is its entity's index.
257        let index = *self.slots[which].get(id as u32 as usize)?;
258        let entity = *self.entities[which].get(index as usize)?;
259        // In a tick, a pair's ids come from the rebuild it is looked up in,
260        // which wrote this slot for this very entity. A `Collisions` put in
261        // mid-tick, between the movement and the triggers, breaks that:
262        // its pair is dropped rather than given to the wrong entity.
263        (bits(entity) == id).then_some(entity)
264    }
265}
266
267impl Default for Collisions {
268    fn default() -> Self {
269        Self::new()
270    }
271}
272
273/// A collider's id: its entity's generation and index, which tell it from
274/// every other entity there ever was.
275fn bits(entity: Entity) -> u64 {
276    (u64::from(entity.generation().get()) << 32) | u64::from(entity.index())
277}