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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use std::sync::atomic::{AtomicUsize, Ordering};
use std::fmt;
use crossbeam::sync::SegQueue;

/// Only one entity with a given index may be alive at a time.
pub type Index = u32;

/// Generation is incremented each time an index is re-used.
pub type Generation = u8;

/// A handle is formed out of an Index and a Generation
pub trait Handle<TIndex, TGeneration>: Clone + Copy + fmt::Display {
    /// Constructs a new handle.
    fn new(index: TIndex, generation: TGeneration) -> Self;

    /// Gets the index component of the handle.
    fn index(&self) -> TIndex;

    /// Gets the generation component of the handle.
    fn generation(&self) -> TGeneration;
}

/// A handle onto an entity in a scene.
#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash)]
pub struct Entity(u32);

const INDEX_BITS: u8 = 24;
const INDEX_MASK: u32 = (1 << INDEX_BITS) - 1;
const GENERATION_BITS: u8 = 8;
const GENERATION_MASK: u32 = (1 << GENERATION_BITS) - 1;
const MINIMUM_FREE_INDICES: usize = 1024;

impl Handle<Index, Generation> for Entity {
    fn new(index: Index, generation: Generation) -> Entity {
        Entity((index & INDEX_MASK) | ((generation as u32 & GENERATION_MASK) << INDEX_BITS))
    }

    fn index(&self) -> Index {
        self.0 & INDEX_MASK
    }

    fn generation(&self) -> Generation {
        let gen = (self.0 >> INDEX_BITS) & GENERATION_MASK;
        gen as u8
    }
}

impl fmt::Display for Entity {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "(index: {}, gen: {})", self.index(), self.generation())
    }
}

/// Manages the allocation and delection of `Entity` IDs.
pub struct Entities {
    free_count_approx: AtomicUsize,
    allocated: AtomicUsize,
    generations: Vec<Generation>,
    free: SegQueue<Index>,
    deleted_pool: SegQueue<Vec<Entity>>,
}

impl Entities {
    /// Constructs a new `Entities`.
    pub fn new() -> Entities {
        Entities {
            generations: Vec::new(),
            free: SegQueue::new(),
            free_count_approx: AtomicUsize::new(0),
            allocated: AtomicUsize::new(0),
            deleted_pool: SegQueue::new(),
        }
    }

    /// Creates a new `Entity`. Allocated entities cannot be deleted until after
    /// `commit_allocations` has been called.
    pub fn allocate(&self) -> Entity {
        if self.free_count_approx.load(Ordering::Relaxed) > MINIMUM_FREE_INDICES {
            if let Some(index) = self.free.try_pop() {
                self.free_count_approx.fetch_sub(1, Ordering::Relaxed);
                let generation = self.generations[index as usize];
                return Entity::new(index, generation);
            }
        }

        let index = self.allocated.fetch_add(1, Ordering::SeqCst);
        return Entity::new(index as Index, 0 as Generation);
    }

    /// Determines if the specified `Entity` is still alive.
    pub fn is_alive(&self, entity: &Entity) -> bool {
        let index = entity.index() as usize;
        match self.generations.get(index) {
            Some(&g) => g == entity.generation(),
            None => self.allocated.load(Ordering::Relaxed) > index,
        }
    }

    /// Gets the count of currently allocated entities.
    pub fn count(&self) -> usize {
        self.allocated.load(Ordering::Relaxed)
    }

    /// Gets the currently living `Entity` with the given `Index`.
    pub fn by_index(&self, index: Index) -> Entity {
        match self.generations.get(index as usize) {
            Some(&g) => Entity::new(index, g),
            None => Entity::new(index, 0),
        }
    }

    /// Creates a new entity transaction. Transactions can be used to allocate
    /// or delete entities in multiple threads concurrently. Entity deletions
    /// are comitted with the transaction is merged via `merge`.
    pub fn transaction(&self) -> EntitiesTransaction {
        EntitiesTransaction {
            entities: self,
            deleted: self.deleted_pool.try_pop().unwrap_or(Vec::new()),
        }
    }

    /// Merges a set of entity transactions, comitting their allocations and
    /// delections.
    pub fn merge<T: Iterator<Item = EntityChangeSet>>(&mut self, changes: T) {
        self.commit_allocations();

        let mut freed = 0;
        for set in changes {
            let mut deleted = set.deleted;
            for e in deleted.drain(..) {
                let index = e.index() as usize;
                self.generations[index] = self.generations[index] + 1;
                self.free.push(e.index());
                freed = freed + 1;
            }

            self.deleted_pool.push(deleted);
        }

        self.free_count_approx.fetch_add(freed, Ordering::Relaxed);
    }

    fn commit_allocations(&mut self) {
        let allocated = self.allocated.load(Ordering::Acquire);
        let new_entities = allocated - self.generations.len();
        if new_entities > 0 {
            self.generations.resize(allocated, 0);
        }
    }
}

/// An iterator which converts indexes into entitiy IDs.
pub struct EntityIter<'a, T>
    where T: Iterator<Item = Index>
{
    entities: &'a Entities,
    iter: T,
}

impl<'a, T: Iterator<Item = Index>> EntityIter<'a, T> {
    /// Constructs a new 'EntityIter'.
    pub fn new(entities: &'a Entities, iter: T) -> EntityIter<'a, T> {
        EntityIter {
            entities: entities,
            iter: iter,
        }
    }
}

impl<'a, T: Iterator<Item = Index>> Iterator for EntityIter<'a, T> {
    type Item = Entity;

    #[inline]
    fn next(&mut self) -> Option<Entity> {
        self.iter.next().map(|i| self.entities.by_index(i))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

/// An entity transaction allows concurrent creations and deletions of entities
/// from an `Entities`.
pub struct EntitiesTransaction<'a> {
    entities: &'a Entities,
    deleted: Vec<Entity>,
}

/// Summarises the final changes made during the lifetime of an
/// entity transaction.
pub struct EntityChangeSet {
    /// The entities deleted in the transaction.
    pub deleted: Vec<Entity>,
}

impl<'a> EntitiesTransaction<'a> {
    /// Creates a new `Entity`.
    ///
    /// This `Entity` can immediately be used to register data with resources,
    /// and the calling system may destroy the entity, but other systems running
    /// concurrently will not observe the entity's creation.
    pub fn create(&mut self) -> Entity {
        self.entities.allocate()
    }

    /// Destroys an `Entity`.
    ///
    /// Entity destructions are deferred until after the system has completed
    /// execution. All related data stored in entity resources will also be
    /// removed at this time.
    pub fn destroy(&mut self, entity: Entity) {
        self.deleted.push(entity);
    }

    /// Determines if the given `Entity` is still alive.
    pub fn is_alive(&self, entity: &Entity) -> bool {
        self.entities.is_alive(entity)
    }

    /// Gets the currently living `Entity` with the given `Index`.
    pub fn by_index(&self, index: Index) -> Entity {
        self.entities.by_index(index)
    }

    /// Converts this transaction into a change set,
    /// consuming the transaction in the process.
    pub fn to_change_set(self) -> EntityChangeSet {
        EntityChangeSet { deleted: self.deleted }
    }
}

#[cfg(test)]
mod entities_tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn deconstruct_entity() {
        let entity = Entity::new(5, 10);
        assert!(entity.index() == 5);
        assert!(entity.generation() == 10);
    }

    #[test]
    fn new() {
        Entities::new();
    }

    #[test]
    fn allocate() {
        let em = Entities::new();
        em.allocate();
    }

    #[test]
    fn allocated_entity_is_alive() {
        let em = Entities::new();
        let entity = em.allocate();
        assert!(em.is_alive(&entity));
    }

    #[test]
    fn allocate_many_no_duplicates() {
        let em = Entities::new();
        let mut entities: HashSet<Entity> = HashSet::new();

        for _ in 0..10000 {
            let e = em.allocate();
            assert!(!entities.contains(&e));

            entities.insert(e);
        }
    }

    #[test]
    fn allocate_many_no_duplicates_comitted() {
        let mut em = Entities::new();
        let mut entities: HashSet<Entity> = HashSet::new();

        for _ in 0..10000 {
            let e = em.allocate();
            assert!(!entities.contains(&e));

            entities.insert(e);
        }

        em.commit_allocations();

        for _ in 0..10000 {
            let e = em.allocate();
            assert!(!entities.contains(&e));

            entities.insert(e);
        }
    }
}

#[cfg(test)]
mod entities_transaction_tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn new() {
        let em = Entities::new();
        em.transaction();
    }

    #[test]
    fn create() {
        let em = Entities::new();
        let mut tx = em.transaction();

        tx.create();
    }

    #[test]
    fn created_is_alive() {
        let em = Entities::new();
        let mut tx = em.transaction();

        let entity = tx.create();
        assert!(tx.is_alive(&entity));
    }

    #[test]
    fn merge_allocates() {
        let mut em = Entities::new();

        let entity: Entity;
        let cs: EntityChangeSet;

        {
            let mut tx = em.transaction();
            entity = tx.create();
            cs = tx.to_change_set();
        }

        em.merge((vec![cs]).into_iter());

        assert!(em.is_alive(&entity));
    }

    #[test]
    fn merge_deletes() {
        let mut em = Entities::new();
        let mut entities: HashSet<Entity> = HashSet::new();

        for _ in 0..10000 {
            let e = em.allocate();
            assert!(!entities.contains(&e));

            entities.insert(e);
        }

        em.commit_allocations();

        let cs: EntityChangeSet;

        {
            let mut tx = em.transaction();

            for entity in entities.iter() {
                tx.destroy(*entity);
            }

            cs = tx.to_change_set();
        }

        for entity in entities.iter() {
            assert!(em.is_alive(&entity));
        }

        em.merge((vec![cs]).into_iter());

        for entity in entities {
            assert!(!em.is_alive(&entity));
        }
    }
}