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
//! Yet Another Entity Component System
//! #![deny(missing_docs)]
extern crate anymap;

use anymap::AnyMap;

use std::ops::Index;

use std::any::Any;
use std::fmt::{Debug, Formatter, Result};

/// An `Entity` is simply an identifier for a bag of components. In general, `System`s operate on
/// a subset of all entities that posess components the `System` is interested in.
#[derive(Debug)]
pub struct Entity {
    /// A user-defined label for this entity. This could be thrown out if in future we run into
    /// memory issues, but for now its convenient as it allows us to more easily identify an entity.
    pub label: String,
    /// Bag of components
    pub components: AnyMap,
}

impl Entity {
    /// Creates a new `Entity` with an empty bag of components
    pub fn new(label: &'static str) -> Entity {
        Entity {
            label: String::from(label),
            components: AnyMap::new(),
        }
    }
}

pub struct Entities(Vec<Entity>);

impl Entities {
    pub fn new() -> Entities {
        Entities(vec![])
    }

    pub fn push(&mut self, entity: Entity) {
        self.0.push(entity);
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn with_component<T: 'static>(&self) -> Vec<&T> {
        self.0
            .iter()
            .filter_map(|e| e.components.get::<T>())
            .collect()
    }
}

impl Index<usize> for Entities {
    type Output = Entity;

    fn index(&self, index: usize) -> &Entity {
        &self.0[index]
    }
}

pub struct EntityBuilder(Entity);

impl EntityBuilder {
    pub fn create(label: &'static str) -> EntityBuilder {
        EntityBuilder(Entity::new(label))
    }

    pub fn add<T: Any>(mut self, component: T) -> EntityBuilder {
        self.0.components.insert(component);
        self
    }

    pub fn build(self) -> Entity {
        self.0
    }
}

pub type Globals = AnyMap;

pub trait System {
    fn process(&self, entities: &mut Entities, globals: &mut Globals);
}

impl Debug for System {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "System")
    }
}

pub struct World {
    entities: Entities,
    globals: Globals,
    systems: Vec<Box<System>>,
}

impl World {
    pub fn new() -> World {
        World {
            entities: Entities::new(),
            globals: Globals::new(),
            systems: vec![],
        }
    }

    pub fn add_entity(&mut self, entity: Entity) {
        self.entities.push(entity);
    }

    pub fn add_global<T: Any>(&mut self, global: T) {
        self.globals.insert(global);
    }

    pub fn add_system<T: System + 'static>(&mut self, system: T) {
        self.systems.push(Box::new(system));
    }

    pub fn get_global<T: Any>(&self) -> Option<&T> {
        self.globals.get::<T>()
    }

    pub fn update(&mut self) {
        for system in &self.systems {
            (*system).process(&mut self.entities, &mut self.globals);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anymap::AnyMap;

    #[derive(Debug, PartialEq)]
    struct TestComponent(u8);

    struct AnotherComponent;

    #[derive(Debug, PartialEq)]
    struct TestSystem;

    impl System for TestSystem {
        fn process(&self, _: &mut Entities, _: &mut AnyMap) {}
    }

    #[test]
    fn entity_can_be_built() {
        let entity = EntityBuilder::create("test").build();
        assert_eq!(entity.label, "test");
    }

    #[test]
    fn entity_can_contain_components() {
        let entity = EntityBuilder::create("test")
            .add(TestComponent(1))
            .build();
        assert_eq!(entity.label, "test");
        assert_eq!(entity.components.get::<TestComponent>(),
                   Some(&TestComponent(1)));
    }

    #[test]
    fn entity_has_components_works() {
        let entity = EntityBuilder::create("test")
            .add(TestComponent(1))
            .build();
        assert!(entity.components.contains::<TestComponent>());
        assert!(!entity.components.contains::<AnotherComponent>());

        let entity = EntityBuilder::create("test")
            .add(AnotherComponent)
            .build();
        assert!(!entity.components.contains::<TestComponent>());
        assert!(entity.components.contains::<AnotherComponent>());
    }

    #[test]
    fn entities_with_component_works() {
        let mut entities = Entities::new();
        entities.push(EntityBuilder::create("test")
            .add(TestComponent(1))
            .build());
        entities.push(EntityBuilder::create("test")
            .add(AnotherComponent)
            .build());

        let test_component = entities.with_component::<TestComponent>().pop();
        assert_eq!(test_component, Some(&TestComponent(1)));
    }

    #[test]
    fn world_can_be_created() {
        let world = World::new();
        assert!(world.entities.is_empty());
    }

    #[test]
    fn world_can_contain_entities() {
        let mut world = World::new();
        world.add_entity(EntityBuilder::create("test")
            .add(TestComponent(1))
            .build());

        assert!(!world.entities.is_empty());
        let ref entity = world.entities[0];
        assert_eq!(entity.label, "test");
        assert_eq!(entity.components.get(), Some(&TestComponent(1)));
    }

    #[test]
    fn world_can_contain_systems() {
        let mut world = World::new();

        assert!(world.systems.is_empty());
        world.add_system(TestSystem);
        assert!(!world.systems.is_empty());
    }
}