fennel_engine/
registry.rs

1use ron::Value;
2use specs::{Entity, 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}
11
12/// Registry of component name - component factory
13pub struct ComponentRegistry {
14    map: HashMap<String, Box<dyn ComponentFactory>>,
15}
16
17impl ComponentRegistry {
18    /// Creates a new instance of [`ComponentRegistry`]
19    pub fn new() -> Self {
20        Self {
21            map: HashMap::new(),
22        }
23    }
24
25    /// Registers a component factory
26    pub fn register(&mut self, name: &str, f: Box<dyn ComponentFactory>) {
27        self.map.insert(name.to_string(), f);
28    }
29
30    /// Fetches a component factory by name
31    pub fn get(&self, name: &str) -> Option<&dyn ComponentFactory> {
32        self.map.get(name).map(|v| &**v)
33    }
34}
35
36impl Default for ComponentRegistry {
37    fn default() -> Self {
38        Self::new()
39    }
40}