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
/*!
Topaz is a tiny game engine. It is based on the Entity-Component-System (ECS) model.

Each game object is an entity, which has certain components. Components define everything
about the entity. For example, one entity may have the `Drawable` and `Position` components,
while another also has the `Solid` component.

Systems operate on the entities when certain events occur. For example, a `Rendering` system 
should operate on all entities with a `Drawable` component every frame. In Topaz, systems are
'subscribed' to events, meaning the system runs when the event occurs. The `EVENT_UPDATE` event
is automatically fired every frame, so the `Rendering` system we just described would be subscribed
to `EVENT_UPDATE`, thus causing the game objects to be drawn every frame.

For basic boilerplate code, check out the 'hello-world' example.

The `Universe` struct contains much of the important documentation; look there first.
*/

extern crate time;

use std::rc::Rc;
use std::cell::RefCell;

///Convenience type for defining mutable entity component fields.
pub type MutComponent<T> = Option<RefCell<T>>;
///Convenience type for defining immutable entity component fields.
pub type Component<T> = Option<Rc<T>>;

///Triggered when the universe starts up.
pub const EVENT_INIT:   usize   = 0;
///Triggered every frame while the universe is running.
pub const EVENT_UPDATE: usize   = 1;
///Triggering this event causes the universe to shut down, and `Universe.run()` to return.
pub const EVENT_QUIT:   usize   = 2;

/**
Entities must implement this trait.
*/
pub trait HasComponents {
    ///Return whether the current entity has any components.
    fn has_components(&self) -> bool;
    ///Return a componentless entity.
    fn empty() -> Self;
}

/**
A null entity. Use when no components are required.
*/
pub struct NullEntity;   
impl HasComponents for NullEntity {
    fn has_components(&self) -> bool {false}
    fn empty() -> Self {Self{}}
}

/**
All systems must implement this trait.

The `operate` method is called when an event to which the system is subscribed is
triggered.
*/
pub trait System<T: HasComponents,S> {
    fn operate(&self, &mut Universe<T,S>);
}

/**
The built-in system which handles EVENT_QUIT. It is installed and subscribed by
default; you do not need to mess with it.
*/
struct QuitSystem;
impl<T: HasComponents,S> System<T,S> for QuitSystem{
    fn operate(&self, universe: &mut Universe<T,S>) {
        universe.stop();
    }
}

/**
The Universe contains all the meta-data neccessary for the game engine.

 - `T`: The type of entities.
 - `S`: A singleton used to contain things that don't fit comfortably elsewhere.
 
 */
pub struct Universe<T,S> {
    ///Entities in the universe.
    pub entities: Vec<Rc<T>>,
    ///Systems in the universe.
    pub systems: Vec<Rc<System<T,S>>>,
    ///An instance of the `Special` type, meant to store data that
    ///doesn't fit comfortably elsewhere.
    pub special: S,
    ///List of possible events, and their subscribers.
    pub events: Vec<Vec<usize>>,
    running: bool,
    ///Amount of time in seconds since the last frame.
    pub time_delta: f64,
    last_frame: f64,
    event_queue: Vec<usize>,
    ///Number of frames the universe has run so far.
    pub frames: usize,
    destruction_queue: RefCell<Vec<usize>>
}

impl<T: HasComponents,S> Universe<T,S> {
    ///Create a new `Universe`. Takes one instance of the `Special` type. (See [the field documentation](#special.v).)
    pub fn new(special: S) -> Self {
        let mut s = Self {
            entities: Vec::new(),
            systems: Vec::new(),
            special: special,
            events: vec![Vec::new(),Vec::new(),Vec::new()],
            running: false,
            time_delta: 0.0,
            last_frame: time::precise_time_s(),
            event_queue: Vec::new(),
            frames: 0,
            destruction_queue: RefCell::new(Vec::new())
        };
        let sys_index = s.new_system(Rc::new(QuitSystem{}));
        s.subscribe(sys_index,EVENT_QUIT);
        s
    }
    
    ///Run the universe. Returns when `EVENT_QUIT` is triggered.
    pub fn run(&mut self) {
        self.running = true;
        self.do_event(EVENT_INIT);
        
        while self.running {
            let current_time = time::precise_time_s();
            self.time_delta = current_time - self.last_frame;
            self.last_frame = current_time;
            self.frames += 1;
            self.do_event(EVENT_UPDATE);
            while self.event_queue.len() != 0 {
                let event = self.event_queue.pop().unwrap();
                let iter = self.events[event].clone();
                for system in iter {
                    self.systems[system].clone().operate(self);
                    let destruction_queue = self.destruction_queue.borrow().clone();
                    //self.destruction_queue = RefCell::new(Vec::new());
                    for item in &destruction_queue {
                        self.destroy(*item);
                    }
                    self.destruction_queue = RefCell::new(Vec::new());
                }
            }
        }
        
        self.do_event(EVENT_QUIT);
    }
    
    /**
    Stop the universe. Using `EVENT_QUIT` is favored, since it allows
    subscribed systems to save and shutdown safely.
    */
    pub fn stop(&mut self) {
        self.running = false;
    }
    
    /**
    Allocate a new event.
    */
    pub fn new_event(&mut self) -> usize {
        let o = self.events.len();
        self.events.push(Vec::new());
        o
    }
    
    /**
    Install a system.
    */
    pub fn new_system(&mut self, system: Rc<System<T,S>>) -> usize {
        let o = self.systems.len();
        self.systems.push(system);
        o
    }
    
    /**
    Subscribe an installed system to an event.
    */
    pub fn subscribe(&mut self, system: usize, event: usize) {
        self.events[event].push(system);
    }
    
    /**
    Install a system and subscribe it to as many events as needed.
    */
    pub fn add_and_subscribe(&mut self, system: Rc<System<T,S>>, events: Vec<usize>) {
        let index = self.new_system(system);
        for event in &events {
            self.subscribe(index,*event);
        }
    }
    
    /**
    Queue an event. The event will be triggered after all the systems subscribed
    to the currently running event have been run.
    */
    pub fn do_event(&mut self, event: usize) {
        self.event_queue.push(event);
    }
    
    /**
    Allocate space for a new entity.
    
    Componentless entities are considered un-allocated and consequently can be overwritten.
    Keep this in mind when implementing `HasComponents`.
    */
    pub fn alloc(&mut self) -> usize {
        for index in 0..self.entities.len() {
            if !self.entities[index].has_components() { return index; }
        }
        let o = self.entities.len();
        self.entities.push(Rc::new(T::empty()));
        o
    }
    
    /**
    Queue an entity for destruction. The entity will be destroyed after the system is finished running.
    */
    pub fn queue_destroy(&self, index: usize) {
        self.destruction_queue.borrow_mut().push(index);
    }
    
    /**
    Immediately destroy an entity.
    */
    pub fn destroy(&mut self, index: usize) {
        self.entities[index] = Rc::new(T::empty());
    }
    
    /**
    Set an index to an entity.
    */
    pub fn set(&mut self, index: usize, entity: T) {
        self.entities[index] = Rc::new(entity);
    }
    
    /**
    Combines `alloc` and `set`. Allocates space for a new entity and installs it.
    */
    pub fn add_entity(&mut self, entity: T) -> usize {
        let index = self.alloc();
        self.set(index,entity);
        index
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}