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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use core::any::{Any, TypeId};

use std::collections::HashMap;

use super::{Component, ComponentBox, ComponentStore, Entity, SharedComponentBox};
use crate::error::NotFound;

/// The `TypeComponentBuilder` is used to build a set of type key based components.
#[derive(Default)]
pub struct TypeComponentBuilder {
    components: HashMap<TypeId, Box<dyn Any>>,
    shared: HashMap<TypeId, Entity>,
}

impl TypeComponentBuilder {
    /// Creates an new builder with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a component of type `C` to the entity.
    pub fn with<C: Component>(mut self, component: C) -> Self {
        self.components
            .insert(TypeId::of::<C>(), Box::new(component));
        self
    }

    /// Adds an entity as `source` for a shared component of type `C`.
    pub fn with_shared<C: Component>(mut self, source: Entity) -> Self {
        self.shared.insert(TypeId::of::<C>(), source);
        self
    }

    /// Adds an entity as `source` for a shared component box.
    pub fn with_shared_box(mut self, source: SharedComponentBox) -> Self {
        self.shared.insert(source.type_id, source.source);
        self
    }

    /// Adds a component box to the entity.
    pub fn with_box(mut self, component_box: ComponentBox) -> Self {
        let (type_id, component) = component_box.consume();
        self.components.insert(type_id, component);
        self
    }

    /// Finishing the creation of the entity.
    pub fn build(self) -> (HashMap<TypeId, Box<dyn Any>>, HashMap<TypeId, Entity>) {
        (self.components, self.shared)
    }
}

/// The `TypeComponentStore` stores the components of all entities. It could be used to
/// borrow the components of the entities.
#[derive(Default, Debug)]
pub struct TypeComponentStore {
    components: HashMap<(Entity, TypeId), Box<dyn Any>>,
    shared: HashMap<(Entity, TypeId), Entity>,
}

impl ComponentStore for TypeComponentStore {
    type Components = (HashMap<TypeId, Box<dyn Any>>, HashMap<TypeId, Entity>);

    fn append(&mut self, entity: Entity, components: Self::Components) {
        for (key, value) in components.0 {
            self.components.insert((entity, key), value);
        }
        for (key, value) in components.1 {
            self.shared.insert((entity, key), value);
        }
    }

    fn remove_entity(&mut self, entity: impl Into<Entity>) {
        let entity = entity.into();
        let keys: Vec<(Entity, TypeId)> = self
            .components
            .iter()
            .filter(|&(k, _)| k.0 == entity)
            .map(|(k, _)| *k)
            .collect();

        for k in keys {
            self.components.remove(&k);
        }

        let keys: Vec<(Entity, TypeId)> = self
            .shared
            .iter()
            .filter(|&(k, _)| k.0 == entity)
            .map(|(k, _)| *k)
            .collect();

        for k in keys {
            self.shared.remove(&k);
        }
    }

    fn print_entity(&self, entity: impl Into<Entity>) {
        let entity = entity.into();
        let _blub = self
            .components
            .iter()
            .filter(|(k, _)| k.0 == entity)
            .map(|(_, _)| println!("blub"));
    }
}

impl TypeComponentStore {
    /// Register a `component` for the given `entity`.
    pub fn register<C: Component>(&mut self, entity: Entity, component: C) {
        self.components
            .insert((entity, TypeId::of::<C>()), Box::new(component));
    }

    /// Registers a sharing of the given component between the given entities.
    pub fn register_shared<C: Component>(&mut self, target: Entity, source: Entity) {
        let target_key = (target, TypeId::of::<C>());
        self.components.remove(&target_key);
        self.shared.insert(target_key, source);
    }

    /// Registers a sharing of the given component between the given entities.
    pub fn register_shared_box(&mut self, target: impl Into<Entity>, source: SharedComponentBox) {
        let target_key = (target.into(), source.type_id);
        self.components.remove(&target_key);
        self.shared.insert(target_key, source.source);
    }

    /// Register a `component_box` for the given `entity`.
    pub fn register_box(&mut self, entity: impl Into<Entity>, component_box: ComponentBox) {
        let entity = entity.into();
        let (type_id, component) = component_box.consume();

        self.components.insert((entity, type_id), component);
    }

    /// Returns the number of components in the store.
    pub fn len(&self) -> usize {
        self.components.len()
    }

    /// Returns true if the components are empty.
    pub fn is_empty(&self) -> bool {
        self.components.is_empty()
    }

    /// Returns `true` if the store contains the specific entity.
    pub fn contains_entity(&self, entity: Entity) -> bool {
        self.components.iter().any(|(k, _)| k.0 == entity)
    }

    /// Returns `true` if entity is the origin of the requested component `false`.
    pub fn is_origin<C: Component>(&self, entity: Entity) -> bool {
        self.components.contains_key(&(entity, TypeId::of::<C>()))
    }

    // Search the the source in the entity map.
    fn source_from_shared<C: Component>(&self, entity: Entity) -> Result<Entity, NotFound> {
        self.shared
            .get(&(entity, TypeId::of::<C>()))
            .ok_or_else(|| NotFound::Entity(entity))
            .map(|s| *s)
    }

    // Returns the source. First search in entities map. If not found search in shared entity map.
    fn source<C: Component>(&self, entity: Entity) -> Result<Entity, NotFound> {
        if !self.components.contains_key(&(entity, TypeId::of::<C>())) {
            return self.source_from_shared::<C>(entity);
        }

        Result::Ok(entity)
    }

    /// Returns a reference of a component of type `C` from the given `entity`. If the entity does
    /// not exists or it doesn't have a component of type `C` `NotFound` will be returned.
    pub fn get<C: Component>(&self, entity: Entity) -> Result<&C, NotFound> {
        let source = self.source::<C>(entity);

        match source {
            Ok(entity) => self
                .components
                .get(&(entity, TypeId::of::<C>()))
                .ok_or_else(|| NotFound::Entity(entity))
                .map(|component| {
                    component
                        .downcast_ref()
                        .expect("EntityComponentManager.get: internal downcast error")
                }),
            Err(_) => Result::Err(NotFound::Entity(entity)),
        }
    }

    /// Returns a mutable reference of a component of type `C` from the given `entity`. If the entity does
    /// not exists or it doesn't have a component of type `C` `NotFound` will be returned.
    pub fn get_mut<C: Component>(&mut self, entity: Entity) -> Result<&mut C, NotFound> {
        let source = self.source::<C>(entity);

        match source {
            Ok(entity) => self
                .components
                .get_mut(&(entity, TypeId::of::<C>()))
                .ok_or_else(|| NotFound::Entity(entity))
                .map(|component| {
                    component
                        .downcast_mut()
                        .expect("EntityComponentManager.get_mut: internal downcast error")
                }),
            Err(_) => Result::Err(NotFound::Entity(entity)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::any::TypeId;

    #[test]
    fn builder_with() {
        let builder = TypeComponentBuilder::new();
        let component = String::from("Test");
        let (map, _) = builder.with(component).build();

        assert!(map.contains_key(&TypeId::of::<String>()));
    }

    #[test]
    fn builder_with_shared() {
        let builder = TypeComponentBuilder::new();
        let source = Entity::from(1);
        let (_, map) = builder.with_shared::<String>(source).build();

        assert!(map.contains_key(&TypeId::of::<String>()));
        assert_eq!(*map.get(&TypeId::of::<String>()).unwrap(), source);
    }

    #[test]
    fn builder_with_shared_box() {
        let builder = TypeComponentBuilder::new();
        let source = Entity::from(1);
        let (_, map) = builder
            .with_shared_box(SharedComponentBox::new(TypeId::of::<String>(), source))
            .build();

        assert!(map.contains_key(&TypeId::of::<String>()));
    }

    #[test]
    fn builder_with_box() {
        let builder = TypeComponentBuilder::new();
        let component = String::from("Test");
        let (map, _) = builder.with_box(ComponentBox::new(component)).build();

        assert!(map.contains_key(&TypeId::of::<String>()));
    }

    #[test]
    fn remove_entity() {
        let mut store = TypeComponentStore::default();
        let entity = Entity::from(1);
        store.register(entity, String::from("Test"));
        store.remove_entity(entity);

        assert!(!store.contains_entity(entity));
    }

    #[test]
    fn register() {
        let mut store = TypeComponentStore::default();
        let entity = Entity::from(1);
        let component = String::from("Test");

        store.register(entity, component);

        assert!(store.get::<String>(entity).is_ok());
    }

    #[test]
    fn len() {
        let mut store = TypeComponentStore::default();
        let entity = Entity::from(1);

        store.register(entity, String::from("Test"));
        store.register(entity, 5 as f64);

        assert_eq!(store.len(), 2);
    }

    #[test]
    fn register_shared() {
        let mut store = TypeComponentStore::default();
        let entity = Entity::from(1);
        let target = Entity::from(2);
        let component = String::from("Test");

        store.register(entity, component);
        store.register_shared::<String>(target, entity);

        assert!(store.get::<String>(entity).is_ok());
        assert!(store.get::<String>(target).is_ok());
        assert!(store.is_origin::<String>(entity));
        assert!(!store.is_origin::<String>(target));
    }

    #[test]
    fn register_box() {
        let mut store = TypeComponentStore::default();
        let entity = Entity::from(1);
        let component = String::from("Test");

        store.register_box(entity, ComponentBox::new(component));

        assert!(store.get::<String>(entity).is_ok());
    }

    #[test]
    fn register_shared_box() {
        let mut store = TypeComponentStore::default();
        let entity = Entity::from(1);
        let target = Entity::from(2);
        let component = String::from("Test");

        store.register(entity, component);
        store.register_shared_box(
            target,
            SharedComponentBox::new(TypeId::of::<String>(), entity),
        );
        assert!(store.get::<String>(entity).is_ok());
        assert!(store.get::<String>(target).is_ok());
        assert!(store.is_origin::<String>(entity));
        assert!(!store.is_origin::<String>(target));
    }
}