wecs_core/archetype/
archetype.rs1use std::collections::HashMap;
2
3use crate::{
4 component::{ComponentId, ComponentList},
5 storage::TableId,
6};
7
8#[derive(Clone, Copy, Debug)]
9pub struct ArchetypeId(usize);
10
11impl ArchetypeId {
12 pub(crate) const UNINIT: ArchetypeId = ArchetypeId(usize::MAX);
13
14 pub(crate) fn is_init(&self) -> bool {
15 self.0 != ArchetypeId::UNINIT.0
16 }
17}
18
19type ArchetypeComponentIds = Vec<ComponentId>;
20
21#[derive(Clone)]
22pub(crate) struct ArchetypeData {
23 pub(crate) components_ids: Vec<ComponentId>,
24 table_id: TableId,
25}
26
27pub struct Archetypes {
28 data: Vec<ArchetypeData>,
29 id_mappings: HashMap<ArchetypeComponentIds, usize>,
30}
31
32impl Default for Archetypes {
33 fn default() -> Self {
34 Self::new()
35 }
36}
37
38impl Archetypes {
39 pub fn new() -> Self {
40 Self {
41 data: Vec::new(),
42 id_mappings: HashMap::new(),
43 }
44 }
45
46 pub fn get_or_init<CL>(&mut self) -> ArchetypeId
47 where
48 CL: ComponentList,
49 {
50 let mut sorted_component_ids = CL::get_ids();
51 sorted_component_ids.sort();
52
53 if let Some(index) = self.id_mappings.get(&sorted_component_ids) {
54 return ArchetypeId(*index);
55 } else {
56 let index = self.data.len();
57 self.id_mappings.insert(sorted_component_ids.clone(), index);
58 self.data.insert(
59 index,
60 ArchetypeData {
61 components_ids: sorted_component_ids,
62 table_id: TableId::UNINIT,
63 },
64 );
65
66 return ArchetypeId(index);
67 }
68 }
69
70 pub(crate) fn get_data(&self, archetype_id: &ArchetypeId) -> &ArchetypeData {
71 self.data.get(archetype_id.0).expect("")
72 }
73
74 pub fn get_table_id(&self, archetype_id: &ArchetypeId) -> TableId {
75 self.data.get(archetype_id.0).clone().expect("").table_id
76 }
77
78 pub fn update_table_id(&mut self, archetype_id: &ArchetypeId, table_id: &TableId) {
79 let data = self.data.get_mut(archetype_id.0).unwrap();
80 data.table_id = *table_id;
81 }
82}