fennel_engine/
registry.rs

1use ron::Value;
2use specs::{Entity, LazyUpdate, World};
3use std::collections::HashMap;
4
5/// All components must have a factory implementing this trait to be able created from a scene
6/// config
7pub trait ComponentFactory: Send + Sync {
8    /// Build a component from `value` and insert it into `entity` of `world`
9    fn insert(&self, world: &mut World, entity: Entity, value: &Value);
10    /// Build a component from `value` and lazily insert it into `entity` of `world`
11    fn insert_lazy(&self, lazy: &LazyUpdate, entity: Entity, value: &Value);
12}
13
14/// Registry of component name - component factory
15pub struct ComponentRegistry {
16    map: HashMap<String, Box<dyn ComponentFactory>>,
17}
18
19impl ComponentRegistry {
20    /// Creates a new instance of [`ComponentRegistry`]
21    pub fn new() -> Self {
22        Self {
23            map: HashMap::new(),
24        }
25    }
26
27    /// Registers a component factory
28    pub fn register(&mut self, name: &str, f: Box<dyn ComponentFactory>) {
29        self.map.insert(name.to_string(), f);
30    }
31
32    /// Fetches a component factory by name
33    pub fn get(&self, name: &str) -> Option<&dyn ComponentFactory> {
34        self.map.get(name).map(|v| &**v)
35    }
36}
37
38impl Default for ComponentRegistry {
39    fn default() -> Self {
40        Self::new()
41    }
42}