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
334
335
336
337
338
339
340
341
342

//! Entity identifier and manager types.

#[cfg(feature="serialisation")] use cereal::{CerealData, CerealError, CerealResult};

use std::collections::hash_map::{HashMap, Values};
use std::default::Default;
use std::marker::PhantomData;
use std::ops::Deref;

use Aspect;
use BuildData;
use ComponentManager;
use EntityData;
use EntityBuilder;
use ServiceManager;
use SystemManager;

pub type Id = u64;

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct Entity(Id);

#[cfg(feature="serialisation")]
impl_cereal_data!(Entity(), a);

#[derive(Debug, Eq, Hash, PartialEq)]
pub struct IndexedEntity<T: ComponentManager>(usize, Entity, PhantomData<T>);

// TODO: Cleanup
#[cfg(feature="serialisation")]
unsafe impl<T: ComponentManager> CerealData for IndexedEntity<T> {
    fn write(&self, write: &mut ::std::io::Write) -> CerealResult<()> {
        try!((self.0 as u64).write(write));
        self.1.write(write)
    }

    fn read(read: &mut ::std::io::Read) -> CerealResult<IndexedEntity<T>> {
        Ok(IndexedEntity(try!(u64::read(read)) as usize, try!(CerealData::read(read)), PhantomData))
    }
}

impl Entity
{
    pub fn nil() -> Entity
    {
        Entity(0)
    }

    /// Returns the entity's unique identifier.
    #[inline]
    pub fn id(&self) -> Id
    {
        self.0
    }
}

impl<T: ComponentManager> IndexedEntity<T>
{
    pub fn index(&self) -> usize
    {
        self.0
    }

    #[doc(hidden)]
    pub fn __clone(&self) -> IndexedEntity<T>
    {
        IndexedEntity(self.0, self.1, self.2)
    }
}

impl<T: ComponentManager> Deref for IndexedEntity<T>
{
    type Target = Entity;
    fn deref(&self) -> &Entity
    {
        &self.1
    }
}

impl Default for Entity
{
    fn default() -> Entity
    {
        Entity::nil()
    }
}

pub struct FilteredEntityIter<'a, T: ComponentManager>
{
    inner: EntityIter<'a, T>,
    aspect: Aspect<T>,
    components: &'a T,
}

// Inner Entity Iterator
pub enum EntityIter<'a, T: ComponentManager>
{
    Map(Values<'a, Entity, IndexedEntity<T>>),
}

impl<'a, T: ComponentManager> EntityIter<'a, T>
{
    pub fn filter(self, aspect: Aspect<T>, components: &'a T) -> FilteredEntityIter<'a, T>
    {
        FilteredEntityIter
        {
            inner: self,
            aspect: aspect,
            components: components,
        }
    }

    pub fn clone(&self) -> Self {
        let EntityIter::Map(ref values) = *self;
        EntityIter::Map(values.clone())
    }
}

impl<'a, T: ComponentManager> Iterator for EntityIter<'a, T>
{
    type Item = EntityData<'a, T>;
    fn next(&mut self) -> Option<EntityData<'a, T>>
    {
        match *self
        {
            EntityIter::Map(ref mut values) => values.next().map(|x| EntityData(x))
        }
    }
}

impl<'a, T: ComponentManager> Iterator for FilteredEntityIter<'a, T>
{
    type Item = EntityData<'a, T>;
    fn next(&mut self) -> Option<EntityData<'a, T>>
    {
        for x in self.inner.by_ref()
        {
            if self.aspect.check(&x, self.components)
            {
                return Some(x);
            }
            else
            {
                continue
            }
        }
        None
    }
}

enum Event
{
    BuildEntity(Entity),
    RemoveEntity(Entity),
}

/// Handles creation, activation, and validating of entities.
#[doc(hidden)]
pub struct EntityManager<T: ComponentManager>
{
    indices: IndexPool,
    entities: HashMap<Entity, IndexedEntity<T>>,
    event_queue: Vec<Event>,
    next_id: Id,
}

// TODO: Cleanup
#[cfg(feature="serialisation")]
unsafe impl<T: ComponentManager> CerealData for EntityManager<T> {
    fn write(&self, write: &mut ::std::io::Write) -> CerealResult<()> {
        if self.event_queue.len() != 0 {
            Err(CerealError::Msg("Please flush events before serialising the world".to_string()))
        } else {
            try!(self.indices.write(write));
            try!(self.entities.write(write));
            self.next_id.write(write)
        }
    }

    fn read(read: &mut ::std::io::Read) -> CerealResult<EntityManager<T>> {
        Ok(EntityManager {
            indices: try!(CerealData::read(read)),
            entities: try!(CerealData::read(read)),
            next_id: try!(CerealData::read(read)),
            event_queue: Vec::new(),
        })
    }
}

impl<T: ComponentManager> EntityManager<T>
{
    /// Returns a new `EntityManager`
    pub fn new() -> EntityManager<T>
    {
        EntityManager
        {
            indices: IndexPool::new(),
            entities: HashMap::new(),
            next_id: 0,
            event_queue: Vec::new(),
        }
    }

    pub fn flush_queue<M, S>(&mut self, c: &mut T, m: &mut M, s: &mut S)
    where M: ServiceManager, S: SystemManager<Components=T, Services=M>
    {
        let queue = ::std::mem::replace(&mut self.event_queue, Vec::new());
        for e in queue {
            match e {
                Event::BuildEntity(entity) => s.__activated(
                    EntityData(self.indexed(&entity)),
                    c,
                    m
                ),
                Event::RemoveEntity(entity) => {
                    {
                        let indexed = self.indexed(&entity);
                        s.__deactivated(EntityData(indexed), c, m);
                        c.__remove_all(indexed);
                    }
                    self.remove(&entity);
                }
            }
        }
    }

    pub fn create_entity<B>(&mut self, builder: B, c: &mut T) -> Entity where B: EntityBuilder<T>
    {
        let entity = self.create();
        builder.build(BuildData(self.indexed(&entity)), c);
        self.event_queue.push(Event::BuildEntity(entity));
        entity
    }

    pub fn remove_entity(&mut self, entity: Entity)
    {
        self.event_queue.push(Event::RemoveEntity(entity));
    }

    pub fn iter(&self) -> EntityIter<T>
    {
        EntityIter::Map(self.entities.values())
    }

    pub fn count(&self) -> usize
    {
        self.indices.count()
    }

    pub fn indexed(&self, entity: &Entity) -> &IndexedEntity<T>
    {
        &self.entities[entity]
    }

    /// Creates a new `Entity`, assigning it the first available index.
    pub fn create(&mut self) -> Entity
    {
        self.next_id += 1;
        let ret = Entity(self.next_id);
        self.entities.insert(ret, IndexedEntity(self.indices.get_index(), ret, PhantomData));
        ret
    }

    /// Returns true if an entity is valid (not removed from the manager).
    #[inline]
    pub fn is_valid(&self, entity: &Entity) -> bool
    {
        self.entities.contains_key(entity)
    }

    /// Deletes an entity from the manager.
    pub fn remove(&mut self, entity: &Entity)
    {
        self.entities.remove(entity).map(|e| self.indices.return_id(e.index()));
    }
}

struct IndexPool
{
    recycled: Vec<usize>,
    next_index: usize,
}

// TODO: Cleanup
#[cfg(feature="serialisation")]
unsafe impl CerealData for IndexPool {
    fn write(&self, write: &mut ::std::io::Write) -> CerealResult<()> {
        try!((self.recycled.len() as u64).write(write));
        for &idx in &self.recycled {
            try!((idx as u64).write(write));
        }
        (self.next_index as u64).write(write)
    }

    fn read(read: &mut ::std::io::Read) -> CerealResult<IndexPool> {
        let len = try!(u64::read(read)) as usize;
        let mut indices = Vec::with_capacity(len);
        for _ in 0..len {
            indices.push(try!(u64::read(read)) as usize);
        }
        Ok(IndexPool {
            recycled: indices,
            next_index: try!(u64::read(read)) as usize,
        })
    }
}


impl IndexPool
{
    pub fn new() -> IndexPool
    {
        IndexPool
        {
            recycled: Vec::new(),
            next_index: 0,
        }
    }

    pub fn count(&self) -> usize
    {
        self.next_index - self.recycled.len()
    }

    pub fn get_index(&mut self) -> usize
    {
        match self.recycled.pop()
        {
            Some(id) => id,
            None => {
                self.next_index += 1;
                self.next_index - 1
            }
        }
    }

    pub fn return_id(&mut self, id: usize)
    {
        self.recycled.push(id);
    }
}