use std::collections::{HashMap, VecDeque}; use crate::Record; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct EntityId(pub u64); #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct Entity { pub(crate) id: EntityId, pub(crate) generation: u64, } impl Entity { pub fn id(&self) -> EntityId { self.id } pub fn generation(&self) -> u64 { self.generation } } #[derive(Clone)] pub struct Entities { pub(crate) arch_index: HashMap, dead: VecDeque, next_id: EntityId, } impl Default for Entities { fn default() -> Self { Self { arch_index: Default::default(), dead: Default::default(), next_id: EntityId(0), } } } impl Entities { pub fn reserve(&mut self) -> Entity { match self.dead.pop_front() { Some(mut e) => { e.generation += 1; e } None => { let new_id = self.next_id; self.next_id.0 += 1; Entity { id: new_id, generation: 0, } } } } /// Returns the number of spawned entities pub fn len(&self) -> usize { self.next_id.0 as usize - self.dead.len() } /// Retrieves the Archetype Record for the entity pub(crate) fn entity_record(&self, entity: Entity) -> Option { self.arch_index.get(&entity.id).cloned() } pub(crate) fn insert_entity_record(&mut self, entity: Entity, record: Record) { self.arch_index.insert(entity.id, record); } }