summaryrefslogtreecommitdiff
path: root/ecs/src/relationship.rs
blob: b7c5c020edd6f95c69da73d8164a3a7d023b37d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use std::any::{type_name, Any};
use std::marker::PhantomData;
use std::sync::{Arc, Weak};

use crate::component::storage::Storage as ComponentStorage;
use crate::component::{
    is_optional as component_is_optional,
    Component,
    FromOptional as ComponentFromOptional,
    Id as ComponentId,
    Metadata as ComponentMetadata,
};
use crate::entity::Uid as EntityUid;
use crate::lock::{Lock, ReadGuard};
use crate::system::{ComponentRefMut, Input as SystemInput};
use crate::type_name::TypeName;
use crate::World;

#[derive(Debug)]
pub struct Relationship<Kind, ComponentT: Component>
{
    entity_uid: EntityUid,
    component_storage: Weak<Lock<ComponentStorage>>,
    _pd: PhantomData<(Kind, ComponentT)>,
}

impl<Kind, ComponentT> Relationship<Kind, ComponentT>
where
    ComponentT: Component,
{
    pub fn new(world: &World, entity_uid: EntityUid) -> Self
    {
        Self {
            entity_uid,
            component_storage: Arc::downgrade(&world.data.component_storage),
            _pd: PhantomData,
        }
    }
}

impl<Kind, ComponentT> Component for Relationship<Kind, ComponentT>
where
    Kind: 'static,
    ComponentT: Component,
{
    type Component = Self;
    type RefMut<'component> = Relation<'component, Kind, ComponentT>;

    fn id(&self) -> ComponentId
    {
        ComponentId::of::<Self>()
    }

    fn as_any_mut(&mut self) -> &mut dyn Any
    {
        self
    }

    fn as_any(&self) -> &dyn Any
    {
        self
    }
}

impl<Kind, ComponentT> SystemInput for Relationship<Kind, ComponentT>
where
    Kind: 'static,
    ComponentT: Component,
{
}

impl<Kind, ComponentT: Component> TypeName for Relationship<Kind, ComponentT>
where
    ComponentT: Component,
{
    fn type_name(&self) -> &'static str
    {
        type_name::<Self>()
    }
}

pub struct Relation<'rel_comp, Kind, ComponentT>
where
    Kind: 'static,
    ComponentT: Component,
{
    component_storage_lock: ReadGuard<'static, ComponentStorage>,
    relationship_comp: ComponentRefMut<'rel_comp, Relationship<Kind, ComponentT>>,
    _component_storage: Arc<Lock<ComponentStorage>>,
}

impl<'rel_comp, Kind, ComponentT> ComponentFromOptional<'rel_comp>
    for Relation<'rel_comp, Kind, ComponentT>
where
    ComponentT: Component,
{
    fn from_optional_component(
        optional_component: Option<
            crate::lock::WriteGuard<'rel_comp, Box<dyn Component>>,
        >,
    ) -> Self
    {
        let relationship_comp =
            ComponentRefMut::<Relationship<Kind, ComponentT>>::from_optional_component(
                optional_component,
            );

        let component_storage = relationship_comp
            .component_storage
            .upgrade()
            .expect("World has been dropped");

        let component_storage_lock = component_storage
            .read_nonblock()
            .expect("Failed to aquire read-only component storage lock");

        Self {
            relationship_comp,
            // SAFETY: The component lock is not used for longer than the original
            // lifetime
            component_storage_lock: unsafe { component_storage_lock.upgrade_lifetime() },
            _component_storage: component_storage,
        }
    }
}

impl<'rel_comp, Kind, ComponentT> Relation<'rel_comp, Kind, ComponentT>
where
    ComponentT: Component,
{
    /// Retrieves the related-to component.
    pub fn get(&self) -> Option<ComponentRefMut<'_, ComponentT>>
    {
        let mut archetype_iter =
            self.component_storage_lock
                .find_entities([ComponentMetadata {
                    id: ComponentId::of::<ComponentT>(),
                    is_optional: component_is_optional::<ComponentT>().into(),
                }]);

        let (entity, archetype) = archetype_iter.find_map(|archetype| {
            let Some(entity) = archetype.get_entity(self.relationship_comp.entity_uid)
            else {
                return None;
            };

            Some((entity, archetype))
        })?;

        let component_index =
            archetype.get_index_for_component(&ComponentId::of::<ComponentT>())?;

        let component = ComponentRefMut::new(
            entity
                .get_component(component_index)?
                .component
                .write_nonblock()
                .unwrap_or_else(|_| {
                    panic!(
                        "Failed to aquire read-write lock of component {}",
                        type_name::<ComponentT>()
                    )
                }),
        );

        Some(component)
    }
}