Skip to main content

naia_shared/world/
shared_global_world_manager.rs

1use std::hash::Hash;
2
3use crate::{
4    EntityAndGlobalEntityConverter, EntityEvent, GlobalEntity, GlobalWorldManagerType, WorldMutType,
5};
6
7/// Shared helpers for world-manager implementations that operate on the global entity registry.
8pub struct SharedGlobalWorldManager;
9
10impl SharedGlobalWorldManager {
11    /// Removes all components from and despawns each entity in `entities`, returning one [`EntityEvent`] per removed component and per despawn.
12    pub fn despawn_all_entities<E: Copy + Eq + Hash + Send + Sync, W: WorldMutType<E>>(
13        world: &mut W,
14        converter: &dyn EntityAndGlobalEntityConverter<E>,
15        global_world_manager: &dyn GlobalWorldManagerType,
16        entities: Vec<GlobalEntity>,
17    ) -> Vec<EntityEvent> {
18        let mut output = Vec::new();
19
20        for global_entity in entities {
21            // Get world entity
22            let world_entity = converter.global_entity_to_entity(&global_entity).unwrap();
23
24            // Generate remove event for each component, handing references off just in
25            // case
26            if let Some(component_kinds) = global_world_manager.component_kinds(&global_entity) {
27                for component_kind in component_kinds {
28                    if let Some(component) =
29                        world.remove_component_of_kind(&world_entity, &component_kind)
30                    {
31                        output.push(EntityEvent::RemoveComponent(global_entity, component));
32                    } else {
33                        panic!("Global World Manager must not have an accurate component list");
34                    }
35                }
36            }
37
38            // Generate despawn event
39            output.push(EntityEvent::Despawn(global_entity));
40
41            // Despawn entity
42            world.despawn_entity(&world_entity);
43        }
44
45        output
46    }
47}