wecs_core/entity/
entity.rs

1use crate::archetype::ArchetypeId;
2
3#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4pub struct EntityId {
5    pub(crate) index: usize,
6    pub(crate) gen: usize,
7}
8
9pub(crate) struct EntityData {
10    pub(crate) gen: usize,
11    pub(crate) archetype_id: ArchetypeId,
12}
13
14pub struct Entities {
15    pub(crate) data: Vec<EntityData>,
16    pub(crate) free_ids: Vec<usize>,
17}
18
19impl Default for Entities {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl Entities {
26    pub fn new() -> Self {
27        Self {
28            data: Vec::new(),
29            free_ids: Vec::new(),
30        }
31    }
32
33    pub fn spawn_empty(&mut self) -> EntityId {
34        if let Some(index) = self.free_ids.pop() {
35            let data = self.data.get_mut(index).expect("");
36            data.gen += 1;
37            data.archetype_id = ArchetypeId::UNINIT; // TODO: set not init
38
39            return EntityId {
40                index,
41                gen: data.gen,
42            };
43        }
44
45        let index = self.data.len();
46        self.data.insert(
47            index,
48            EntityData {
49                gen: 0,
50                archetype_id: ArchetypeId::UNINIT, // TODO: set not init
51            },
52        );
53
54        EntityId { index, gen: 0 }
55    }
56
57    pub fn spawn(&mut self, archetype_id: ArchetypeId) -> EntityId {
58        if let Some(index) = self.free_ids.pop() {
59            let data = self.data.get_mut(index).expect("");
60            data.gen += 1;
61            data.archetype_id = archetype_id;
62
63            return EntityId {
64                index,
65                gen: data.gen,
66            };
67        }
68
69        let index = self.data.len();
70        self.data.insert(
71            index,
72            EntityData {
73                gen: 0,
74                archetype_id: archetype_id,
75            },
76        );
77
78        EntityId { index, gen: 0 }
79    }
80
81    pub fn modify(&mut self, entity_id: EntityId, archetype_id: ArchetypeId) {
82        if let Some(data) = self.data.get_mut(entity_id.index) {
83            if data.gen != entity_id.gen {
84                panic!()
85            }
86
87            data.archetype_id = archetype_id;
88        }
89    }
90
91    pub fn get(&self, entity_id: &EntityId) -> Option<ArchetypeId> {
92        if let Some(data) = self.data.get(entity_id.index) {
93            if data.gen != entity_id.gen {
94                return None;
95            }
96
97            return Some(data.archetype_id);
98        }
99
100        None
101    }
102}