bones_ecs/
entities.rs

1//! [`Entity`] implementation, storage, and interation.
2
3use std::{marker::PhantomData, rc::Rc};
4
5use crate::prelude::*;
6
7/// An entity index.
8///
9/// They are created using the `Entities` struct. They are used as indices with `Components`
10/// structs.
11///
12/// Entities are conceptual "things" which possess attributes (Components). As an exemple, a Car
13/// (Entity) has a Color (Component), a Position (Component) and a Speed (Component).
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[derive(HasSchema, Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
16#[repr(C)]
17pub struct Entity(u32, u32);
18impl Entity {
19    /// An invalid entity, useful for placeholder entity values.
20    const INVALID: Entity = Entity(u32::MAX, u32::MAX);
21
22    /// Creates a new `Entity` from the provided index and generation.
23    ///
24    /// > ⚠️ **Warning:** It is not generally recommended to manually create [`Entity`]s unless you
25    /// > know exactly what you are doing. This can be useful in certain advanced or unusual
26    /// > use-cases, but usually you should use [`Entities::create()`] to spawn entities.
27    pub fn new(index: u32, generation: u32) -> Entity {
28        Entity(index, generation)
29    }
30
31    /// Returns the index of this `Entity`.
32    ///
33    /// In most cases, you do not want to use this directly.
34    /// However, it can be useful to create caches to improve performances.
35    pub fn index(&self) -> u32 {
36        self.0
37    }
38
39    /// Returns the generation of this `Entity`.
40    ///
41    ///
42    /// In most cases, you do not want to use this directly.
43    /// However, it can be useful to create caches to improve performances.
44    pub fn generation(&self) -> u32 {
45        self.1
46    }
47}
48impl Default for Entity {
49    fn default() -> Self {
50        Self::INVALID
51    }
52}
53
54/// Holds a list of alive entities.
55///
56/// It also holds a list of entities that were recently killed, which allows to remove components of
57/// deleted entities at the end of a game frame.
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59#[derive(Clone, HasSchema)]
60pub struct Entities {
61    /// Bitset containing all living entities
62    alive: BitSetVec,
63    generation: Vec<u32>,
64    killed: Vec<Entity>,
65    next_id: usize,
66    /// helps to know if we should directly append after next_id or if we should look through the
67    /// bitset.
68    has_deleted: bool,
69}
70impl std::fmt::Debug for Entities {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("Entities").finish_non_exhaustive()
73    }
74}
75
76impl Default for Entities {
77    fn default() -> Self {
78        Self {
79            alive: create_bitset(),
80            generation: vec![0u32; BITSET_SIZE],
81            killed: vec![],
82            next_id: 0,
83            has_deleted: false,
84        }
85    }
86}
87
88/// A type representing a component-joining entity query.
89pub trait QueryItem {
90    /// The type of iterator this query item creates
91    type Iter: Iterator;
92    /// Modify the iteration bitset
93    fn apply_bitset(&self, bitset: &mut BitSetVec);
94    /// Return the item that matches the query within the given bitset if there is exactly one
95    /// entity that matches this query item.
96    fn get_single_with_bitset(
97        self,
98        bitset: Rc<BitSetVec>,
99    ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError>;
100    /// Return an iterator over the provided bitset.
101    fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter;
102}
103
104/// An error that may occur when querying for a single entity. For example, via
105/// [`Entities::get_single_with`], or more directly with
106/// [`ComponentStore::get_single_with_bitset`] or
107/// [`ComponentStore::get_single_mut_with_bitset`].
108#[derive(Debug, PartialEq, Eq)]
109pub enum QuerySingleError {
110    /// No entity matches the query.
111    NoEntities,
112    /// More than one entity matches the query.
113    MultipleEntities,
114}
115
116/// Wrapper for the [`Comp`] [`SystemParam`] used as [`QueryItem`] to iterate
117/// over entities optionally retrieving components from [`ComponentStore`].
118/// Entities iterated over will not be filtered by [`OptionalQueryItem`].
119///
120/// See [`Optional`] helper func for constructing `OptionalQueryItem` and usage.
121pub struct OptionalQueryItem<'a, T: HasSchema, S>(pub &'a S, pub PhantomData<&'a T>);
122
123/// Wrapper for the [`CompMut`] [`SystemParam`] used as [`QueryItem`] to iterate
124/// over entities optionally and mutably retrieving components from [`ComponentStore`].
125/// Entities iterated over will not be filtered by [`OptionalQueryItemMut`].
126///
127/// See [`OptionalMut`] helper func for constructing `OptionalQueryItemMut` and usage
128pub struct OptionalQueryItemMut<'a, T: HasSchema, S>(pub &'a mut S, pub PhantomData<&'a T>);
129
130/// Helper func to construct a [`OptionalQueryItem`] wrapping a [`Comp`] [`SystemParam`].
131/// Used to iterate over enities optionally retrieving components from [`ComponentStore`].
132/// Entities iterated over will not be filtered by this `QueryItem`.
133///
134/// This example filters entities by `compC`, optionally retrieves `compA` as mutable, and
135/// `compB` as immutable. ([`OptionalMut`] is used for mutation).
136///
137/// `entities.iter_with(&mut OptionalMut(&mut compA), &Optional(&compB), &compC)`
138///
139/// This will implement [`QueryItem`] as long as generic type implements [`std::ops::Deref`] for
140/// [`ComponentStore`], such as [`Comp`] and [`CompMut`].
141#[allow(non_snake_case)]
142pub fn Optional<'a, T: HasSchema, C, S>(component_ref: &'a S) -> OptionalQueryItem<'a, T, S>
143where
144    C: ComponentIterBitset<'a, T> + 'a,
145    S: std::ops::Deref<Target = C> + 'a,
146{
147    OptionalQueryItem(component_ref, PhantomData)
148}
149
150/// Helper func to construct a [`OptionalQueryItemMut`] wrapping a [`CompMut`] [`SystemParam`].
151/// Used to iterate over enities optionally and mutably retrieving components from [`ComponentStore`].
152/// Entities iterated over will not be filtered by this `QueryItem`.
153///
154/// This example filters entities by `compC`, optionally retrieves `compA` as mutable, and
155/// `compB` as immutable.
156///
157/// `entities.iter_with(&mut OptionalMut(&mut compA), &Optional(&compB), &compC)`
158///
159/// This will implement [`QueryItem`] as long as generic type implements [`std::ops::DerefMut`] for
160/// [`ComponentStore`], such as [`CompMut`].
161#[allow(non_snake_case)]
162pub fn OptionalMut<'a, T: HasSchema, C, S>(
163    component_ref: &'a mut S,
164) -> OptionalQueryItemMut<'a, T, S>
165where
166    C: ComponentIterBitset<'a, T> + 'a,
167    S: std::ops::DerefMut<Target = C> + 'a,
168{
169    OptionalQueryItemMut(component_ref, PhantomData)
170}
171
172impl<'a> QueryItem for &'a Ref<'a, UntypedComponentStore> {
173    type Iter = UntypedComponentBitsetIterator<'a>;
174
175    fn apply_bitset(&self, bitset: &mut BitSetVec) {
176        bitset.bit_and(self.bitset());
177    }
178
179    fn get_single_with_bitset(
180        self,
181        bitset: Rc<BitSetVec>,
182    ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
183        UntypedComponentStore::get_single_with_bitset(self, bitset)
184    }
185
186    fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
187        UntypedComponentStore::iter_with_bitset(self, bitset)
188    }
189}
190
191impl<'a, 'q, T: HasSchema> QueryItem for &'a Comp<'q, T> {
192    type Iter = ComponentBitsetIterator<'a, T>;
193
194    fn apply_bitset(&self, bitset: &mut BitSetVec) {
195        bitset.bit_and(self.bitset());
196    }
197
198    fn get_single_with_bitset(
199        self,
200        bitset: Rc<BitSetVec>,
201    ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
202        ComponentStore::get_single_with_bitset(&**self, bitset)
203    }
204
205    fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
206        ComponentStore::iter_with_bitset(&**self, bitset)
207    }
208}
209
210impl<'a, 'q, T: HasSchema> QueryItem for &'a CompMut<'q, T> {
211    type Iter = ComponentBitsetIterator<'a, T>;
212
213    fn apply_bitset(&self, bitset: &mut BitSetVec) {
214        bitset.bit_and(self.bitset());
215    }
216
217    fn get_single_with_bitset(
218        self,
219        bitset: Rc<BitSetVec>,
220    ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
221        ComponentStore::get_single_with_bitset(&**self, bitset)
222    }
223
224    fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
225        ComponentStore::iter_with_bitset(&**self, bitset)
226    }
227}
228
229impl<'a, 'q, T: HasSchema> QueryItem for &'a mut CompMut<'q, T> {
230    type Iter = ComponentBitsetIteratorMut<'a, T>;
231
232    fn apply_bitset(&self, bitset: &mut BitSetVec) {
233        bitset.bit_and(self.bitset());
234    }
235
236    fn get_single_with_bitset(
237        self,
238        bitset: Rc<BitSetVec>,
239    ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
240        ComponentStore::get_single_with_bitset_mut(self, bitset)
241    }
242
243    fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
244        ComponentStore::iter_mut_with_bitset(self, bitset)
245    }
246}
247
248/// Immutably iterate over optional component with syntax: `&Optional(&Comp<T>)` / `&Optional(&CompMut<T>)`.
249/// (For mutable optional iteration we require `&mut OptionalMut(&mut CompMut<T>)`)
250impl<'a, T: HasSchema, S, C> QueryItem for &'a OptionalQueryItem<'a, T, S>
251where
252    C: ComponentIterBitset<'a, T> + 'a,
253    S: std::ops::Deref<Target = C> + 'a,
254{
255    type Iter = ComponentBitsetOptionalIterator<'a, T>;
256
257    fn apply_bitset(&self, _bitset: &mut BitSetVec) {}
258
259    fn get_single_with_bitset(
260        self,
261        bitset: Rc<BitSetVec>,
262    ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
263        match self.0.get_single_with_bitset(bitset) {
264            Ok(single) => Ok(Some(single)),
265            Err(QuerySingleError::NoEntities) => Ok(None),
266            Err(err) => Err(err),
267        }
268    }
269
270    fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
271        self.0.iter_with_bitset_optional(bitset)
272    }
273}
274
275/// Mutably iterate over optional component with syntax: `&mut OptionalMut(&mut RefMut<ComponentStore<T>>)`
276impl<'a, T: HasSchema, S, C> QueryItem for &'a mut OptionalQueryItemMut<'a, T, S>
277where
278    C: ComponentIterBitset<'a, T> + 'a,
279    S: std::ops::DerefMut<Target = C> + 'a,
280{
281    type Iter = ComponentBitsetOptionalIteratorMut<'a, T>;
282
283    fn apply_bitset(&self, _bitset: &mut BitSetVec) {}
284
285    fn get_single_with_bitset(
286        self,
287        bitset: Rc<BitSetVec>,
288    ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
289        match self.0.get_single_mut_with_bitset(bitset) {
290            Ok(x) => Ok(Some(x)),
291            Err(QuerySingleError::NoEntities) => Ok(None),
292            Err(err) => Err(err),
293        }
294    }
295
296    fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
297        self.0.iter_mut_with_bitset_optional(bitset)
298    }
299}
300
301#[doc(hidden)]
302pub struct MultiQueryIter<T> {
303    data: T,
304}
305
306macro_rules! impl_query {
307    ( $( $args:ident, )* ) => {
308        impl<
309            'q,
310            $(
311                $args: Iterator,
312            )*
313        >
314        Iterator for MultiQueryIter<($($args,)*)> {
315            type Item = (
316                $(
317                    $args::Item,
318                )*
319            );
320
321            #[allow(non_snake_case)]
322            fn next(&mut self) -> Option<Self::Item> {
323                let (
324                    $(
325                        $args,
326                    )*
327                ) = &mut self.data;
328
329                match (
330                    $(
331                        $args.next(),
332                    )*
333                ) {
334                    (
335                        $(
336                            Some($args),
337                        )*
338                    ) => Some((
339                        $(
340                            $args,
341                        )*
342                    )),
343                    _ => None
344                }
345            }
346        }
347
348        impl<
349            $(
350                $args: QueryItem,
351            )*
352        > QueryItem for (
353            $(
354                $args,
355            )*
356        ) {
357            type Iter = MultiQueryIter< (
358                $(
359                    <$args as QueryItem>::Iter,
360                )*
361            )>;
362
363            #[allow(non_snake_case)]
364            fn apply_bitset(&self, bitset: &mut BitSetVec) {
365                let (
366                    $(
367                        $args,
368                    )*
369                ) = self;
370                $(
371                    $args.apply_bitset(bitset);
372                )*
373            }
374
375            #[allow(non_snake_case)]
376            fn get_single_with_bitset(
377                self,
378                bitset: Rc<BitSetVec>,
379            ) -> Result<<Self::Iter as Iterator>::Item, QuerySingleError> {
380                let (
381                    $(
382                        $args,
383                    )*
384                ) = self;
385                let mut query = MultiQueryIter {
386                    data: (
387                        $(
388                            $args.iter_with_bitset(bitset.clone()),
389                        )*
390                    )
391                };
392                let Some(items) = query.next() else {
393                    return Err(QuerySingleError::NoEntities);
394                };
395                match query.next() {
396                    Some(_) => Err(QuerySingleError::MultipleEntities),
397                    None => Ok(items),
398                }
399            }
400
401            #[allow(non_snake_case)]
402            fn iter_with_bitset(self, bitset: Rc<BitSetVec>) -> Self::Iter {
403                let (
404                    $(
405                        $args,
406                    )*
407                ) = self;
408                MultiQueryIter {
409                    data: (
410                        $(
411                            $args.iter_with_bitset(bitset.clone()),
412                        )*
413                    ),
414                }
415            }
416        }
417    };
418}
419
420macro_rules! impl_queries {
421    // base case
422    () => {};
423    (
424        $head:ident,
425        $(
426            $tail:ident,
427        )*
428    ) => {
429        // recursive call
430        impl_query!($head, $( $tail, )* );
431        impl_queries!($( $tail, )* );
432    }
433}
434
435impl_queries!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,);
436
437/// Iterator over entities returned by [`Entities::iter_with`].
438pub struct EntitiesIterWith<'e, I> {
439    current_id: usize,
440    next_id: usize,
441    bitset: Rc<BitSetVec>,
442    generations: &'e Vec<u32>,
443    query: I,
444}
445
446impl<'a, I: Iterator> Iterator for EntitiesIterWith<'a, I> {
447    type Item = (Entity, I::Item);
448
449    fn next(&mut self) -> Option<Self::Item> {
450        while !self.bitset.bit_test(self.current_id) && self.current_id < self.next_id {
451            self.current_id += 1;
452        }
453
454        if self.current_id >= self.next_id {
455            return None;
456        }
457
458        let entity = Entity::new(self.current_id as u32, self.generations[self.current_id]);
459
460        self.current_id += 1;
461        self.query.next().map(|item| (entity, item))
462    }
463}
464
465impl Entities {
466    /// Get a single entity and components in the given query if there is exactly one entity
467    /// matching the query.
468    ///
469    /// # Panics
470    ///
471    /// This method panics if the number of matching entities is not *exactly one*.
472    pub fn single_with<Q: QueryItem>(
473        &self,
474        query: Q,
475    ) -> (Entity, <<Q as QueryItem>::Iter as Iterator>::Item) {
476        self.get_single_with(query).unwrap()
477    }
478
479    /// Get a single entity and components in the given query if there is exactly one entity
480    /// matching the query.
481    pub fn get_single_with<Q: QueryItem>(
482        &self,
483        query: Q,
484    ) -> Result<(Entity, <<Q as QueryItem>::Iter as Iterator>::Item), QuerySingleError> {
485        let mut bitset = self.bitset().clone();
486        query.apply_bitset(&mut bitset);
487
488        let entity = {
489            let mut ids = (0..self.next_id).filter(|&i| bitset.bit_test(i));
490            let id = ids.next().ok_or(QuerySingleError::NoEntities)?;
491            if ids.next().is_some() {
492                return Err(QuerySingleError::MultipleEntities);
493            }
494            Entity::new(id as u32, self.generation[id])
495        };
496
497        let bitset = Rc::new(bitset);
498
499        query
500            .get_single_with_bitset(bitset)
501            .map(|item| (entity, item))
502    }
503
504    /// Get the first entity in the given bitset.
505    ///
506    /// # Panics
507    ///
508    /// This method panics if there are no entities in the bitset.
509    pub fn first_with_bitset(&self, bitset: &BitSetVec) -> Entity {
510        self.get_first_with_bitset(bitset).unwrap()
511    }
512
513    /// Get the first entity in the given bitset.
514    pub fn get_first_with_bitset(&self, bitset: &BitSetVec) -> Option<Entity> {
515        self.iter_with_bitset(bitset).next()
516    }
517
518    /// Get the first entity and components in the given query.
519    ///
520    /// # Panics
521    ///
522    /// This method panics if there are no entities that match the query.
523    pub fn first_with<Q: QueryItem>(
524        &self,
525        query: Q,
526    ) -> (Entity, <<Q as QueryItem>::Iter as Iterator>::Item) {
527        self.get_first_with(query).unwrap()
528    }
529
530    /// Get the first entity and components in the given query.
531    pub fn get_first_with<Q: QueryItem>(
532        &self,
533        query: Q,
534    ) -> Option<(Entity, <<Q as QueryItem>::Iter as Iterator>::Item)> {
535        self.iter_with(query).next()
536    }
537
538    /// Iterates over entities using the provided bitset.
539    pub fn iter_with_bitset<'a>(&'a self, bitset: &'a BitSetVec) -> EntityIterator<'a> {
540        EntityIterator {
541            current_id: 0,
542            next_id: self.next_id,
543            entities: &self.alive,
544            generations: &self.generation,
545            bitset,
546        }
547    }
548
549    /// Iterate over the entities and components in the given query.
550    ///
551    /// The [`QueryItem`] trait is automatically implemented for references to [`Comp`] and
552    /// [`CompMut`] and for tuples of up to 26 items, so you can join over your mutable or immutable
553    /// component borrows in your systems.
554    ///
555    /// You can also pass a single component, to iterate only over the components that have alive
556    /// entities.
557    ///
558    /// # Example
559    ///
560    /// ```
561    /// # use bones_ecs::prelude::*;
562    /// # #[derive(HasSchema, Clone, Default)]
563    /// # #[repr(C)]
564    /// # struct Pos { x: f32, y: f32 };
565    /// # #[derive(HasSchema, Clone, Default)]
566    /// # #[repr(C)]
567    /// # struct Vel { x: f32, y: f32 };
568    ///
569    /// fn my_system(entities: Res<Entities>, mut pos: CompMut<Pos>, vel: Comp<Vel>) {
570    ///     for (entity, (pos, vel)) in entities.iter_with((&mut pos, &vel)) {
571    ///         pos.x += vel.x;
572    ///         pos.y += vel.y;
573    ///     }
574    /// }
575    /// ```
576    ///
577    /// You may optionally iterate over components with `&Optional(&comp)` or mutably with
578    /// `&mut OptionalMut(&mut comp_mut)`. Entities are not filtered by component in [`OptionalQueryItem`].
579    /// None is returned for these. If done with single Optional query item, all entities are iterated over.
580    ///
581    /// Syntax is `&Optional(&comp)`, or `&mut OptionalMut(&mut comp)`. Reference to comp and reference to Optional
582    /// is required for now.
583    ///
584    /// # [`Optional`] Example
585    ///
586    /// ```
587    /// # use bones_ecs::prelude::*;
588    /// # #[derive(HasSchema, Clone, Default)]
589    /// # #[repr(C)]
590    /// # struct Pos { x: f32, y: f32 };
591    /// # #[derive(HasSchema, Clone, Default)]
592    /// # #[repr(C)]
593    /// # struct Vel { x: f32, y: f32 };
594    /// # #[derive(HasSchema, Clone, Default)]
595    /// # #[repr(C)]
596    /// # struct PosMax { x: f32, y: f32 }
597    ///
598    /// fn my_system(entities: Res<Entities>, mut pos: CompMut<Pos>, vel: Comp<Vel>, pos_max: Comp<PosMax>) {
599    ///     for (entity, (pos, vel, pos_max)) in entities.iter_with((&mut pos, &vel, &Optional(&pos_max))) {
600    ///         // Update pos from vel on all entities that have pos and vel components
601    ///         pos.x += vel.x;
602    ///         pos.y += vel.y;
603    ///
604    ///         // limit pos.x by pos_max.x if entity has PosMax component
605    ///         if let Some(pos_max) = pos_max {
606    ///             if pos.x > pos_max.x {
607    ///                 pos.x = pos_max.x
608    ///             }
609    ///         }
610    ///     }
611    /// }
612    /// ```
613    pub fn iter_with<Q: QueryItem>(
614        &self,
615        query: Q,
616    ) -> EntitiesIterWith<'_, <Q as QueryItem>::Iter> {
617        let mut bitset = self.bitset().clone();
618        query.apply_bitset(&mut bitset);
619        let bitset = Rc::new(bitset);
620
621        EntitiesIterWith {
622            current_id: 0,
623            next_id: self.next_id,
624            bitset: bitset.clone(),
625            generations: &self.generation,
626            query: query.iter_with_bitset(bitset),
627        }
628    }
629
630    /// Creates a new `Entity` and returns it.
631    ///
632    /// This function will not reuse the index of an entity that is still in the killed entities.
633    pub fn create(&mut self) -> Entity {
634        if !self.has_deleted {
635            let i = self.next_id;
636            if i >= BITSET_SIZE {
637                panic!("Exceeded maximum amount of concurrent entities.");
638            }
639            self.next_id += 1;
640            self.alive.bit_set(i);
641            Entity::new(i as u32, self.generation[i])
642        } else {
643            // Skip over sections where all bits are enabled
644            let mut section = 0;
645            while self.alive[section].bit_all() {
646                section += 1;
647            }
648
649            // Start at the beginning of the first section with at least 1 unset bit
650            let mut i = section * (32 * 8);
651            // Find the first bit that is not used by an alive or dead entity
652            while i < BITSET_SIZE
653                && (self.alive.bit_test(i) || self.killed.iter().any(|e| e.index() == i as u32))
654            {
655                i += 1;
656            }
657            if i >= BITSET_SIZE {
658                panic!("Exceeded maximum amount of concurrent entities.");
659            }
660
661            // Create the entity
662            self.alive.bit_set(i);
663            if i >= self.next_id {
664                self.next_id = i + 1;
665                self.has_deleted = false;
666            }
667            let entity = Entity::new(i as u32, self.generation[i]);
668
669            // Make sure we never return the invalid entity.
670            if unlikely(entity == Entity::INVALID) {
671                panic!("Ran out of entity IDs");
672            }
673
674            entity
675        }
676    }
677
678    /// Checks if the `Entity` is still alive.
679    ///
680    /// Returns true if it is alive. Returns false if it has been killed.
681    pub fn is_alive(&self, entity: Entity) -> bool {
682        self.alive.bit_test(entity.index() as usize)
683            && self.generation[entity.index() as usize] == entity.generation()
684    }
685
686    /// Kill an entity.
687    pub fn kill(&mut self, entity: Entity) {
688        if self.alive.bit_test(entity.index() as usize) {
689            self.alive.bit_reset(entity.index() as usize);
690            self.generation[entity.index() as usize] += 1;
691            self.killed.push(entity);
692            self.has_deleted = true;
693        }
694    }
695
696    /// Returns a list of all `Entity`s cloned into a new vec.
697    pub fn all_cloned(&self) -> Vec<Entity> {
698        self.iter().collect()
699    }
700
701    /// Kills all entities.
702    pub fn kill_all(&mut self) {
703        let entities: Vec<Entity> = self.all_cloned();
704        for entity in entities {
705            self.kill(entity);
706        }
707    }
708
709    /// Returns entities in the killed list.
710    pub fn killed(&self) -> &Vec<Entity> {
711        &self.killed
712    }
713
714    /// Clears the killed entity list.
715    pub fn clear_killed(&mut self) {
716        self.killed.clear();
717    }
718
719    /// Returns a bitset where each index where the bit is set to 1 indicates the index of an alive
720    /// entity.
721    ///
722    /// Useful for joining over [`Entity`] and [`ComponentStore<T>`] at the same time.
723    pub fn bitset(&self) -> &BitSetVec {
724        &self.alive
725    }
726
727    /// Iterates over all alive entities.
728    pub fn iter(&self) -> EntityIterator<'_> {
729        EntityIterator {
730            current_id: 0,
731            next_id: self.next_id,
732            entities: self.bitset(),
733            generations: &self.generation,
734            bitset: self.bitset(),
735        }
736    }
737}
738
739/// Iterator over entities using the provided bitset.
740pub struct EntityIterator<'a> {
741    pub(crate) current_id: usize,
742    pub(crate) next_id: usize,
743    pub(crate) entities: &'a BitSetVec,
744    pub(crate) generations: &'a Vec<u32>,
745    //pub(crate) bitset: &'a BitSetVec,
746    pub(crate) bitset: &'a BitSetVec,
747}
748
749impl<'a> Iterator for EntityIterator<'a> {
750    type Item = Entity;
751    fn next(&mut self) -> Option<Self::Item> {
752        while !(self.bitset.bit_test(self.current_id) && self.entities.bit_test(self.current_id))
753            && self.current_id < self.next_id
754        {
755            self.current_id += 1;
756        }
757        let ret = if self.current_id < self.next_id {
758            Some(Entity::new(
759                self.current_id as u32,
760                self.generations[self.current_id],
761            ))
762        } else {
763            None
764        };
765        self.current_id += 1;
766        ret
767    }
768}
769
770#[cfg(test)]
771mod tests {
772    #![allow(non_snake_case)]
773
774    use std::collections::HashSet;
775
776    use crate::prelude::*;
777
778    #[derive(Debug, Clone, Copy, PartialEq, Eq, HasSchema, Default)]
779    #[repr(C)]
780    struct A(u32);
781
782    #[derive(Debug, Clone, Copy, PartialEq, Eq, HasSchema, Default)]
783    #[repr(C)]
784    struct B(u32);
785
786    #[test]
787    fn entities__create_kill() {
788        let mut entities = Entities::default();
789        let e1 = entities.create();
790        let e2 = entities.create();
791        let e3 = entities.create();
792        assert_eq!(e1.index(), 0);
793        assert_eq!(e2.index(), 1);
794        assert_eq!(e3.index(), 2);
795        assert_eq!(e1.generation(), 0);
796        assert!(entities.is_alive(e1));
797        assert!(entities.is_alive(e2));
798        assert!(entities.is_alive(e3));
799        entities.kill(e1);
800        assert!(!entities.is_alive(e1));
801        assert!(entities.is_alive(e2));
802        assert!(entities.is_alive(e3));
803        let e4 = entities.create();
804        assert!(!entities.is_alive(e1));
805        assert!(entities.is_alive(e2));
806        assert!(entities.is_alive(e3));
807        assert!(entities.is_alive(e4));
808
809        assert_eq!(*entities.killed(), vec![e1]);
810        entities.clear_killed();
811        assert_eq!(*entities.killed(), vec![]);
812    }
813
814    #[test]
815    fn entities__interleaved_create_kill() {
816        let mut entities = Entities::default();
817
818        let e1 = entities.create();
819        assert_eq!(e1.index(), 0);
820        let e2 = entities.create();
821        assert_eq!(e2.index(), 1);
822        entities.kill(e1);
823        entities.kill(e2);
824        assert!(!entities.is_alive(e1));
825        assert!(!entities.is_alive(e2));
826
827        let e3 = entities.create();
828        assert_eq!(e3.index(), 2);
829        let e4 = entities.create();
830        assert_eq!(e4.index(), 3);
831        entities.kill(e3);
832        entities.kill(e4);
833        assert!(!entities.is_alive(e3));
834        assert!(!entities.is_alive(e4));
835    }
836
837    #[test]
838    /// Exercise basic operations on entities to increase code coverage
839    fn entities__clone_debug_hash() {
840        let mut entities = Entities::default();
841        let e1 = entities.create();
842        // Clone
843        #[allow(clippy::clone_on_copy)]
844        let _ = e1.clone();
845        // Debug
846        assert_eq!(format!("{e1:?}"), "Entity(0, 0)");
847        // Hash
848        let mut h = HashSet::new();
849        h.insert(e1);
850    }
851
852    /// Test to cover the code where an entity is allocated in the next free section.
853    ///
854    /// Exercises a code path not tested according to code coverage.
855    #[test]
856    fn entities__force_generate_next_section() {
857        let mut entities = Entities::default();
858        // Create enough entities to fil up the first section of the bitset
859        for _ in 0..256 {
860            entities.create();
861        }
862        // Create another entity ( this will be the second section)
863        let e1 = entities.create();
864        // Kill the entity ( now we will have a deleted entity, but not in the first section )
865        entities.kill(e1);
866        // Create a new entity
867        entities.create();
868    }
869
870    #[test]
871    #[should_panic(expected = "Exceeded maximum amount")]
872    fn entities__force_max_entity_panic() {
873        let mut entities = Entities::default();
874        for _ in 0..(BITSET_SIZE + 1) {
875            entities.create();
876        }
877    }
878
879    #[test]
880    #[should_panic(expected = "Exceeded maximum amount")]
881    fn entities__force_max_entity_panic2() {
882        let mut entities = Entities::default();
883        let e = (0..BITSET_SIZE).fold(default(), |_, _| entities.create());
884        entities.kill(e);
885        entities.create();
886        entities.create();
887    }
888
889    #[test]
890    fn entities__iter_with_empty_bitset() {
891        let mut entities = Entities::default();
892
893        // Create a couple entities
894        entities.create();
895        entities.create();
896
897        // Join with an empty bitset
898        let bitset = BitSetVec::default();
899        assert_eq!(entities.iter_with_bitset(&bitset).count(), 0);
900    }
901
902    #[test]
903    fn entities__get_single__with_one_required__ok() {
904        let mut entities = Entities::default();
905        (0..3).map(|_| entities.create()).count();
906        let e = entities.create();
907        let a = A(4);
908
909        let mut store = ComponentStore::<A>::default();
910        store.insert(e, a);
911
912        assert_eq!(entities.get_single_with(&Ref::new(&store)), Ok((e, &a)));
913    }
914
915    #[test]
916    fn entities__get_single__with_one_required__none() {
917        let mut entities = Entities::default();
918        let store = ComponentStore::<A>::default();
919        (0..3).map(|_| entities.create()).count();
920
921        assert_eq!(
922            entities.get_single_with(&Ref::new(&store)),
923            Err(QuerySingleError::NoEntities)
924        );
925    }
926
927    #[test]
928    fn entities__get_single__with_one_required__too_many() {
929        let mut entities = Entities::default();
930        let mut store = ComponentStore::<A>::default();
931
932        for i in 0..3 {
933            store.insert(entities.create(), A(i));
934        }
935
936        assert_eq!(
937            entities.get_single_with(&Ref::new(&store)),
938            Err(QuerySingleError::MultipleEntities)
939        );
940    }
941
942    #[test]
943    fn entities__get_single__with_multiple_required() {
944        let mut entities = Entities::default();
945
946        let mut store_a = ComponentStore::<A>::default();
947        let mut store_b = ComponentStore::<B>::default();
948
949        let _e1 = entities.create();
950
951        let e2 = entities.create();
952        store_a.insert(e2, A(2));
953
954        let e3 = entities.create();
955        store_b.insert(e3, B(3));
956
957        let e4 = entities.create();
958        let a4 = A(4);
959        let b4 = B(4);
960        store_a.insert(e4, a4);
961        store_b.insert(e4, b4);
962
963        assert_eq!(
964            entities.get_single_with((&Ref::new(&store_a), &Ref::new(&store_b))),
965            Ok((e4, (&a4, &b4)))
966        );
967    }
968
969    #[test]
970    fn entities__get_single__with_one_optional() {
971        let mut entities = Entities::default();
972        let mut store = ComponentStore::<A>::default();
973
974        {
975            let e = entities.create();
976
977            assert_eq!(
978                entities.get_single_with(&Optional(&Ref::new(&store))),
979                Ok((e, None))
980            );
981
982            assert_eq!(
983                entities.get_single_with(&mut OptionalMut(&mut RefMut::new(&mut store))),
984                Ok((e, None))
985            );
986
987            entities.kill(e);
988        }
989
990        {
991            let e = entities.create();
992            let mut a = A(1);
993            store.insert(e, a);
994
995            assert_eq!(
996                entities.get_single_with(&Optional(&Ref::new(&store))),
997                Ok((e, Some(&a)))
998            );
999
1000            assert_eq!(
1001                entities.get_single_with(&mut OptionalMut(&mut RefMut::new(&mut store))),
1002                Ok((e, Some(&mut a)))
1003            );
1004
1005            entities.kill(e);
1006        }
1007    }
1008
1009    #[test]
1010    fn entities__get_single__with_required_and_optional() {
1011        let mut entities = Entities::default();
1012        let mut store_a = ComponentStore::<A>::default();
1013        let mut store_b = ComponentStore::<B>::default();
1014
1015        {
1016            let e = entities.create();
1017            let a = A(1);
1018            store_a.insert(e, a);
1019
1020            assert_eq!(
1021                entities.get_single_with((&Ref::new(&store_a), &Optional(&Ref::new(&store_b)))),
1022                Ok((e, (&a, None)))
1023            );
1024
1025            assert_eq!(
1026                entities.get_single_with((
1027                    &Ref::new(&store_a),
1028                    &mut OptionalMut(&mut RefMut::new(&mut store_b))
1029                )),
1030                Ok((e, (&a, None)))
1031            );
1032
1033            entities.kill(e);
1034        }
1035
1036        {
1037            let e = entities.create();
1038            let a = A(1);
1039            let mut b = B(1);
1040            store_a.insert(e, a);
1041            store_b.insert(e, b);
1042
1043            assert_eq!(
1044                entities.get_single_with((&Ref::new(&store_a), &Optional(&Ref::new(&store_b)))),
1045                Ok((e, (&a, Some(&b))))
1046            );
1047
1048            assert_eq!(
1049                entities.get_single_with((
1050                    &Ref::new(&store_a),
1051                    &mut OptionalMut(&mut RefMut::new(&mut store_b))
1052                )),
1053                Ok((e, (&a, Some(&mut b))))
1054            );
1055
1056            entities.kill(e);
1057        }
1058    }
1059}