entity_data/system/
component.rs1use crate::{ArchetypeStorage, Component, EntityId};
2use std::cell::{Ref, RefMut};
3use std::marker::PhantomData;
4
5pub(crate) type CompMutability = bool;
6
7#[derive(Clone)]
8pub struct GenericComponentGlobalAccess<'a> {
9 pub(crate) filtered_archetype_ids: Vec<usize>,
10 pub(crate) all_archetypes: &'a [ArchetypeStorage],
11 pub(crate) mutable: bool,
12}
13
14impl GenericComponentGlobalAccess<'_> {
15 fn count_entities(&self) -> usize {
16 self.filtered_archetype_ids
17 .iter()
18 .map(|v| self.all_archetypes[*v].entities.count())
19 .sum::<usize>()
20 }
21}
22
23pub struct GlobalComponentAccess<'a, C> {
24 pub(crate) generic: Ref<'a, GenericComponentGlobalAccess<'a>>,
25 pub(crate) _ty: PhantomData<C>,
26}
27
28impl<'a, C: Component> GlobalComponentAccess<'a, C> {
29 pub fn contains(&self, entity_id: &EntityId) -> bool {
31 self.generic
32 .all_archetypes
33 .get(entity_id.archetype_id as usize)
34 .and_then(|v| Some(v.contains(entity_id.id)))
35 .unwrap_or(false)
36 }
37
38 pub fn get(&self, entity_id: &EntityId) -> Option<&C> {
40 self.generic
41 .all_archetypes
42 .get(entity_id.archetype_id as usize)?
43 .get(entity_id.id)
44 }
45
46 pub fn count_entities(&self) -> usize {
48 self.generic.count_entities()
49 }
50}
51
52pub struct GlobalComponentAccessMut<'a, 'b, C> {
53 pub(crate) generic: RefMut<'b, GenericComponentGlobalAccess<'a>>,
54 pub(crate) _ty: PhantomData<C>,
55}
56
57impl<'a, 'b, C: Component> GlobalComponentAccessMut<'a, 'b, C> {
58 pub fn contains(&self, entity_id: &EntityId) -> bool {
60 self.generic
61 .all_archetypes
62 .get(entity_id.archetype_id as usize)
63 .and_then(|v| Some(v.contains(entity_id.id)))
64 .unwrap_or(false)
65 }
66
67 pub fn get(&self, entity_id: &EntityId) -> Option<&C> {
69 self.generic
70 .all_archetypes
71 .get(entity_id.archetype_id as usize)?
72 .get(entity_id.id)
73 }
74
75 pub fn get_mut(&mut self, entity_id: &EntityId) -> Option<&mut C> {
77 let comp = self
78 .generic
79 .all_archetypes
80 .get(entity_id.archetype_id as usize)?
81 .component::<C>()?;
82 comp.contains(entity_id.id)
83 .then(|| unsafe { comp.get_mut_unsafe(entity_id.id) })
84 }
85
86 pub fn count_entities(&self) -> usize {
88 self.generic.count_entities()
89 }
90}