bevy_ecs/world/
spawn_batch.rs

1use crate::{
2    bundle::{Bundle, BundleSpawner},
3    entity::Entity,
4    world::World,
5};
6use std::iter::FusedIterator;
7
8/// An iterator that spawns a series of entities and returns the [ID](Entity) of
9/// each spawned entity.
10///
11/// If this iterator is not fully exhausted, any remaining entities will be spawned when this type is dropped.
12pub struct SpawnBatchIter<'w, I>
13where
14    I: Iterator,
15    I::Item: Bundle,
16{
17    inner: I,
18    spawner: BundleSpawner<'w>,
19}
20
21impl<'w, I> SpawnBatchIter<'w, I>
22where
23    I: Iterator,
24    I::Item: Bundle,
25{
26    #[inline]
27    pub(crate) fn new(world: &'w mut World, iter: I) -> Self {
28        // Ensure all entity allocations are accounted for so `self.entities` can realloc if
29        // necessary
30        world.flush();
31
32        let change_tick = world.change_tick();
33
34        let (lower, upper) = iter.size_hint();
35        let length = upper.unwrap_or(lower);
36        world.entities.reserve(length as u32);
37
38        let mut spawner = BundleSpawner::new::<I::Item>(world, change_tick);
39        spawner.reserve_storage(length);
40
41        Self {
42            inner: iter,
43            spawner,
44        }
45    }
46}
47
48impl<I> Drop for SpawnBatchIter<'_, I>
49where
50    I: Iterator,
51    I::Item: Bundle,
52{
53    fn drop(&mut self) {
54        // Iterate through self in order to spawn remaining bundles.
55        for _ in &mut *self {}
56        // Apply any commands from those operations.
57        // SAFETY: `self.spawner` will be dropped immediately after this call.
58        unsafe { self.spawner.flush_commands() };
59    }
60}
61
62impl<I> Iterator for SpawnBatchIter<'_, I>
63where
64    I: Iterator,
65    I::Item: Bundle,
66{
67    type Item = Entity;
68
69    fn next(&mut self) -> Option<Entity> {
70        let bundle = self.inner.next()?;
71        // SAFETY: bundle matches spawner type
72        unsafe { Some(self.spawner.spawn(bundle)) }
73    }
74
75    fn size_hint(&self) -> (usize, Option<usize>) {
76        self.inner.size_hint()
77    }
78}
79
80impl<I, T> ExactSizeIterator for SpawnBatchIter<'_, I>
81where
82    I: ExactSizeIterator<Item = T>,
83    T: Bundle,
84{
85    fn len(&self) -> usize {
86        self.inner.len()
87    }
88}
89
90impl<I, T> FusedIterator for SpawnBatchIter<'_, I>
91where
92    I: FusedIterator<Item = T>,
93    T: Bundle,
94{
95}