big_space 0.12.0

A floating origin plugin for bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Spatial hashing acceleration structure. See [`CellHashingPlugin`].

use core::marker::PhantomData;

use crate::prelude::*;
use bevy_app::prelude::*;
use bevy_ecs::entity::EntityHashSet;
use bevy_ecs::{prelude::*, query::QueryFilter};

pub mod component;
pub mod map;

/// Add spatial hashing acceleration to `big_space`, accessible through the [`CellLookup`] resource,
/// and [`CellId`] components.
///
/// You can optionally add a [`SpatialHashFilter`] to this plugin to only run the spatial hashing on
/// entities that match the query filter. This is useful if you only want to, say, compute hashes
/// and insert in the [`CellLookup`] for `Player` entities.
///
/// If you are adding multiple copies of this plugin with different filters, there are optimizations
/// in place to avoid duplicating work. However, you should still take care to avoid excessively
/// overlapping filters.
pub struct CellHashingPlugin<F = ()>(PhantomData<F>)
where
    F: SpatialHashFilter;

impl<F> CellHashingPlugin<F>
where
    F: SpatialHashFilter,
{
    /// Create a new instance of [`CellHashingPlugin`].
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<F> Plugin for CellHashingPlugin<F>
where
    F: SpatialHashFilter,
{
    fn build(&self, app: &mut App) {
        app.init_resource::<CellLookup<F>>()
            .init_resource::<ChangedCells<F>>()
            .register_type::<CellId>()
            .add_systems(
                PostUpdate,
                (
                    CellId::update::<F>
                        .in_set(SpatialHashSystems::UpdateCellHashes)
                        .after(BigSpaceSystems::RecenterLargeTransforms),
                    CellLookup::<F>::update
                        .in_set(SpatialHashSystems::UpdateCellLookup)
                        .after(SpatialHashSystems::UpdateCellHashes),
                ),
            );
    }
}

impl Default for CellHashingPlugin<()> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

/// System sets for [`CellHashingPlugin`].
#[derive(SystemSet, Hash, Debug, PartialEq, Eq, Clone)]
pub enum SpatialHashSystems {
    /// [`CellId`] and [`CellHash`] updated.
    UpdateCellHashes,
    /// [`CellLookup`] updated.
    UpdateCellLookup,
    /// [`PartitionLookup`] updated.
    UpdatePartitionLookup,
    /// [`PartitionEntities`] updated.
    UpdatePartitionChange,
}

/// Used as a [`QueryFilter`] to include or exclude certain types of entities from spatial
/// hashing.The trait is automatically implemented for all compatible types, like [`With`] or
/// [`Without`].
///
/// By default, this is `()`, but it can be overridden when adding the [`CellHashingPlugin`] and
/// [`CellLookup`]. For example, if you use `With<Players>` as your filter, only `Player`s would be
/// considered when building spatial hash maps. This is useful when you only care about querying
/// certain entities and want to avoid the plugin doing bookkeeping work for entities you don't
/// care about.
pub trait SpatialHashFilter: QueryFilter + Send + Sync + 'static {}
impl<T: QueryFilter + Send + Sync + 'static> SpatialHashFilter for T {}

/// Resource to manually track entities that have moved between cells, for optimization purposes.
///
/// Updated every frame in [`CellId::update`] in [`SpatialHashSystems::UpdateCellHashes`].
///
/// We use a manual collection instead of a `Changed` query because a query that uses `Changed`
/// still has to iterate over every single entity. By making a shortlist of changed entities
/// ourselves, we can make this 1000x faster.
///
/// Note that this is optimized for *sparse* updates, this may perform worse if you are updating
/// every entity. The observation here is that usually entities are not moving between grid cells,
/// and thus their spatial hash is not changing. On top of that, many entities are completely
/// static.
///
/// It may be possible to remove this if bevy gets archetype change detection, or observers that can
/// react to a component being mutated. For now, this performs well enough.
#[derive(Resource)]
pub struct ChangedCells<F: SpatialHashFilter> {
    updated: EntityHashSet,
    spooky: PhantomData<F>,
}

impl<F: SpatialHashFilter> Default for ChangedCells<F> {
    fn default() -> Self {
        Self {
            updated: Default::default(),
            spooky: PhantomData,
        }
    }
}

impl<F: SpatialHashFilter> ChangedCells<F> {
    /// Iterate over all entities that have moved between cells.
    pub fn iter(&self) -> impl Iterator<Item = &Entity> {
        self.updated.iter()
    }
}

// TODO:
//
// - When an entity is re-parented, is is removed/updated in the spatial map?
// - Entities are hashed with their parent - what happens if an entity is moved to the root? Is the
//   hash ever recomputed? Is it removed? Is the spatial map updated?
#[cfg(test)]
mod tests {
    use crate::plugin::BigSpaceMinimalPlugins;
    use crate::{hash::map::SpatialEntryToEntities, prelude::*};
    use bevy_ecs::entity::EntityHashSet;
    use bevy_platform::sync::OnceLock;

    #[test]
    fn entity_despawn() {
        use bevy::prelude::*;

        static ENTITY: OnceLock<Entity> = OnceLock::new();

        let setup = |mut commands: Commands| {
            commands.spawn_big_space_default(|root| {
                let entity = root.spawn_spatial(CellCoord::ZERO).id();
                ENTITY.set(entity).ok();
            });
        };

        let mut app = App::new();
        app.add_plugins(CellHashingPlugin::default())
            .add_systems(Update, setup)
            .update();

        let hash = *app
            .world()
            .entity(*ENTITY.get().unwrap())
            .get::<CellId>()
            .unwrap();

        assert!(app.world().resource::<CellLookup>().get(&hash).is_some());

        app.world_mut().despawn(*ENTITY.get().unwrap());

        app.update();

        assert!(app.world().resource::<CellLookup>().get(&hash).is_none());
    }

    #[test]
    fn get_hash() {
        use bevy::prelude::*;

        #[derive(Resource, Clone)]
        struct ParentSet {
            a: Entity,
            b: Entity,
            c: Entity,
        }

        #[derive(Resource, Clone)]
        struct ChildSet {
            x: Entity,
            y: Entity,
            z: Entity,
        }

        let setup = |mut commands: Commands| {
            commands.spawn_big_space_default(|root| {
                let a = root.spawn_spatial(CellCoord::new(0, 1, 2)).id();
                let b = root.spawn_spatial(CellCoord::new(0, 1, 2)).id();
                let c = root.spawn_spatial(CellCoord::new(5, 5, 5)).id();

                root.commands().insert_resource(ParentSet { a, b, c });

                root.with_grid_default(|grid| {
                    let x = grid.spawn_spatial(CellCoord::new(0, 1, 2)).id();
                    let y = grid.spawn_spatial(CellCoord::new(0, 1, 2)).id();
                    let z = grid.spawn_spatial(CellCoord::new(5, 5, 5)).id();
                    grid.commands().insert_resource(ChildSet { x, y, z });
                });
            });
        };

        let mut app = App::new();
        app.add_plugins(CellHashingPlugin::default())
            .add_systems(Update, setup);

        app.update();

        let mut spatial_hashes = app.world_mut().query::<&CellId>();

        let parent = app.world().resource::<ParentSet>().clone();
        let child = app.world().resource::<ChildSet>().clone();

        assert_eq!(
            spatial_hashes.get(app.world(), parent.a).unwrap(),
            spatial_hashes.get(app.world(), parent.b).unwrap(),
            "Same parent, same cell"
        );

        assert_ne!(
            spatial_hashes.get(app.world(), parent.a).unwrap(),
            spatial_hashes.get(app.world(), parent.c).unwrap(),
            "Same parent, different cell"
        );

        assert_eq!(
            spatial_hashes.get(app.world(), child.x).unwrap(),
            spatial_hashes.get(app.world(), child.y).unwrap(),
            "Same parent, same cell"
        );

        assert_ne!(
            spatial_hashes.get(app.world(), child.x).unwrap(),
            spatial_hashes.get(app.world(), child.z).unwrap(),
            "Same parent, different cell"
        );

        assert_ne!(
            spatial_hashes.get(app.world(), parent.a).unwrap(),
            spatial_hashes.get(app.world(), child.x).unwrap(),
            "Same cell, different parent"
        );

        let entities = &app
            .world()
            .resource::<CellLookup>()
            .get(spatial_hashes.get(app.world(), parent.a).unwrap())
            .unwrap()
            .entities;

        assert!(entities.contains(&parent.a));
        assert!(entities.contains(&parent.b));
        assert!(!entities.contains(&parent.c));
        assert!(!entities.contains(&child.x));
        assert!(!entities.contains(&child.y));
        assert!(!entities.contains(&child.z));
    }

    #[test]
    fn neighbors() {
        use bevy::prelude::*;

        #[derive(Resource, Clone)]
        struct Entities {
            a: Entity,
            b: Entity,
            c: Entity,
        }

        let setup = |mut commands: Commands| {
            commands.spawn_big_space_default(|root| {
                let a = root.spawn_spatial(CellCoord::new(0, 0, 0)).id();
                let b = root.spawn_spatial(CellCoord::new(1, 1, 1)).id();
                let c = root.spawn_spatial(CellCoord::new(2, 2, 2)).id();

                root.commands().insert_resource(Entities { a, b, c });
            });
        };

        let mut app = App::new();
        app.add_plugins(CellHashingPlugin::default())
            .add_systems(Startup, setup);

        app.update();

        let entities = app.world().resource::<Entities>().clone();
        let parent = app
            .world_mut()
            .query::<&ChildOf>()
            .get(app.world(), entities.a)
            .unwrap();

        let map = app.world().resource::<CellLookup>();
        let entry = map.get(&CellId::new(parent, &CellCoord::ZERO)).unwrap();
        let neighbors: EntityHashSet = map.nearby(entry).entities().collect();

        assert!(neighbors.contains(&entities.a));
        assert!(neighbors.contains(&entities.b));
        assert!(!neighbors.contains(&entities.c));

        let flooded: EntityHashSet = map
            .flood(&CellId::new(parent, &CellCoord::ZERO), None)
            .entities()
            .collect();

        assert!(flooded.contains(&entities.a));
        assert!(flooded.contains(&entities.b));
        assert!(flooded.contains(&entities.c));
    }

    #[test]
    fn query_filters() {
        use bevy::prelude::*;

        #[derive(Component)]
        struct Player;

        static ROOT: OnceLock<Entity> = OnceLock::new();

        let setup = |mut commands: Commands| {
            commands.spawn_big_space_default(|root| {
                root.spawn_spatial((CellCoord::ZERO, Player));
                root.spawn_spatial(CellCoord::ZERO);
                root.spawn_spatial(CellCoord::ZERO);
                ROOT.set(root.id()).ok();
            });
        };

        let mut app = App::new();
        app.add_plugins((
            CellHashingPlugin::default(),
            CellHashingPlugin::<With<Player>>::new(),
            CellHashingPlugin::<Without<Player>>::new(),
        ))
        .add_systems(Startup, setup)
        .update();

        let zero_hash = CellId::from_parent(*ROOT.get().unwrap(), &CellCoord::ZERO);

        let map = app.world().resource::<CellLookup>();
        assert_eq!(
            map.get(&zero_hash).unwrap().entities.iter().count(),
            3,
            "There are a total of 3 spatial entities"
        );

        let map = app.world().resource::<CellLookup<With<Player>>>();
        assert_eq!(
            map.get(&zero_hash).unwrap().entities.iter().count(),
            1,
            "There is only one entity with the Player component"
        );

        let map = app.world().resource::<CellLookup<Without<Player>>>();
        assert_eq!(
            map.get(&zero_hash).unwrap().entities.iter().count(),
            2,
            "There are two entities without the player component"
        );
    }

    /// Verify that [`CellLookup::newly_emptied`] and [`CellLookup::newly_occupied`] work correctly when
    /// entities are spawned and move between cells.
    #[test]
    fn spatial_map_changed_cell_tracking() {
        use bevy::prelude::*;

        #[derive(Resource, Clone)]
        struct Entities {
            a: Entity,
            b: Entity,
            c: Entity,
        }

        let setup = |mut commands: Commands| {
            commands.spawn_big_space_default(|root| {
                let a = root.spawn_spatial(CellCoord::new(0, 0, 0)).id();
                let b = root.spawn_spatial(CellCoord::new(1, 1, 1)).id();
                let c = root.spawn_spatial(CellCoord::new(2, 2, 2)).id();

                root.commands().insert_resource(Entities { a, b, c });
            });
        };

        let mut app = App::new();
        app.add_plugins((BigSpaceMinimalPlugins, CellHashingPlugin::default()))
            .add_systems(Startup, setup);

        app.update();

        let entities = app.world().resource::<Entities>().clone();
        let get_hash = |app: &mut App, entity| {
            *app.world_mut()
                .query::<&CellId>()
                .get(app.world(), entity)
                .unwrap()
        };

        let a_hash_t0 = get_hash(&mut app, entities.a);
        let b_hash_t0 = get_hash(&mut app, entities.b);
        let c_hash_t0 = get_hash(&mut app, entities.c);
        let map = app.world().resource::<CellLookup>();
        assert!(map.newly_occupied().contains(&a_hash_t0));
        assert!(map.newly_occupied().contains(&b_hash_t0));
        assert!(map.newly_occupied().contains(&c_hash_t0));

        // Move entities and run an update
        app.world_mut()
            .entity_mut(entities.a)
            .get_mut::<CellCoord>()
            .unwrap()
            .z += 1;
        app.world_mut()
            .entity_mut(entities.b)
            .get_mut::<Transform>()
            .unwrap()
            .translation
            .z += 1e10;
        app.update();

        let a_hash_t1 = get_hash(&mut app, entities.a);
        let b_hash_t1 = get_hash(&mut app, entities.b);
        let c_hash_t1 = get_hash(&mut app, entities.c);
        let map = app.world().resource::<CellLookup>();

        // Last grid
        assert!(map.newly_emptied().contains(&a_hash_t0)); // Moved cell
        assert!(map.newly_emptied().contains(&b_hash_t0)); // Moved cell via transform
        assert!(!map.newly_emptied().contains(&c_hash_t0)); // Did not move

        // Current grid
        assert!(map.newly_occupied().contains(&a_hash_t1)); // Moved cell
        assert!(map.newly_occupied().contains(&b_hash_t1)); // Moved cell via transform
        assert!(!map.newly_occupied().contains(&c_hash_t1)); // Did not move
    }
}