valence_entity/
manager.rs

1use std::num::Wrapping;
2
3use bevy_ecs::prelude::*;
4use rustc_hash::FxHashMap;
5use tracing::warn;
6
7use super::EntityId;
8
9/// A [`Resource`] which maintains information about all spawned Minecraft
10/// entities.
11#[derive(Resource, Debug)]
12pub struct EntityManager {
13    /// Maps protocol IDs to ECS entities.
14    pub(super) id_to_entity: FxHashMap<i32, Entity>,
15    next_id: Wrapping<i32>,
16}
17
18impl EntityManager {
19    pub(super) fn new() -> Self {
20        Self {
21            id_to_entity: FxHashMap::default(),
22            next_id: Wrapping(1), // Skip 0.
23        }
24    }
25
26    /// Returns the next unique entity ID and increments the counter.
27    pub fn next_id(&mut self) -> EntityId {
28        if self.next_id.0 == 0 {
29            warn!("entity ID overflow!");
30            // ID 0 is reserved for clients, so skip over it.
31            self.next_id.0 = 1;
32        }
33
34        let id = EntityId(self.next_id.0);
35
36        self.next_id += 1;
37
38        id
39    }
40
41    /// Gets the entity with the given entity ID.
42    pub fn get_by_id(&self, entity_id: i32) -> Option<Entity> {
43        self.id_to_entity.get(&entity_id).copied()
44    }
45}