bones_ecs/
stage.rs

1//! Implementation of stage abstraction for running collections of systems over a [`World`].
2
3use std::collections::VecDeque;
4use std::marker::PhantomData;
5
6use crate::prelude::*;
7
8/// An ordered collection of [`SystemStage`]s.
9pub struct SystemStages {
10    /// The stages in the collection, in the order that they will be run.
11    stages: Vec<Box<dyn SystemStage>>,
12}
13
14impl Default for SystemStages {
15    fn default() -> Self {
16        Self::with_core_stages()
17    }
18}
19
20impl SystemStages {
21    /// Create a [`SystemStages`] collection, initialized with a stage for each [`CoreStage`].
22    pub fn with_core_stages() -> Self {
23        Self {
24            stages: vec![
25                Box::new(
26                    StartupSystemStage::<CoreStageStartupResourceSystemsRan>::new(
27                        CoreStage::StartupResource,
28                    ),
29                ),
30                Box::new(StartupSystemStage::<CoreStageStartupSystemsRan>::new(
31                    CoreStage::Startup,
32                )),
33                Box::new(SimpleSystemStage::new(CoreStage::First)),
34                Box::new(SimpleSystemStage::new(CoreStage::PreUpdate)),
35                Box::new(SimpleSystemStage::new(CoreStage::Update)),
36                Box::new(SimpleSystemStage::new(CoreStage::PostUpdate)),
37                Box::new(SimpleSystemStage::new(CoreStage::Last)),
38            ],
39        }
40    }
41
42    /// Add a [`System`] to the stage with the given label.
43    pub fn add_system_to_stage<Args, S>(&mut self, label: impl StageLabel, system: S) -> &mut Self
44    where
45        S: IntoSystem<Args, (), (), Sys = StaticSystem<(), ()>>,
46    {
47        let name = label.name();
48        let id = label.id();
49        let mut stage = None;
50
51        for st in &mut self.stages {
52            if st.id() == id {
53                stage = Some(st);
54            }
55        }
56
57        let Some(stage) = stage else {
58            panic!("Stage with label `{}` ( {} ) doesn't exist.", name, id);
59        };
60
61        stage.add_system(system.system());
62
63        self
64    }
65
66    /// Insert a new stage, before another existing stage
67    #[track_caller]
68    pub fn insert_stage_before<L: StageLabel, S: SystemStage + 'static>(
69        &mut self,
70        label: L,
71        stage: S,
72    ) -> &mut Self {
73        let stage_idx = self
74            .stages
75            .iter()
76            .position(|x| x.id() == label.id())
77            .unwrap_or_else(|| panic!("Could not find stage with label `{}`", label.name()));
78        self.stages.insert(stage_idx, Box::new(stage));
79
80        self
81    }
82
83    /// Insert a new stage, after another existing stage
84    #[track_caller]
85    pub fn insert_stage_after<L: StageLabel, S: SystemStage + 'static>(
86        &mut self,
87        label: L,
88        stage: S,
89    ) -> &mut Self {
90        let stage_idx = self
91            .stages
92            .iter()
93            .position(|x| x.id() == label.id())
94            .unwrap_or_else(|| panic!("Could not find stage with label `{}`", label.name()));
95        self.stages.insert(stage_idx + 1, Box::new(stage));
96
97        self
98    }
99
100    /// Execute the systems on the given `world`.
101    pub fn run(&mut self, world: &mut World) {
102        for stage in &mut self.stages {
103            stage.run(world);
104        }
105        // Cleanup killed entities
106        world.maintain();
107    }
108
109    /// Add a system to the [`CoreStage::Startup`] stage which specially runs
110    /// only once, before all other core stages. Inserting [`CoreStageStartupSystemsRan`]
111    /// into the world prevents systems in the startup stage from running.
112    #[deprecated = "use `.add_system_to_stage(CoreStage::Startup, your_system)` instead"]
113    pub fn add_startup_system<Args, S>(&mut self, system: S) -> &mut Self
114    where
115        S: IntoSystem<Args, (), (), Sys = StaticSystem<(), ()>>,
116    {
117        self.add_system_to_stage(CoreStage::Startup, system.system());
118        self
119    }
120
121    /// Convenience method. Adds a system that will run each frame until it succeeds (returns Some).
122    /// Uses Option to allow for easy usage of `?`. System is added to
123    /// [`CoreStage::First`].
124    ///
125    /// See also the wrapper function used inside [`single_success_system`].
126    #[deprecated = "use `.add_system_to_stage(First, single_success_system(your_system)"]
127    pub fn add_single_success_system<Args, S>(&mut self, system: S) -> &mut Self
128    where
129        S: IntoSystem<Args, (), Option<()>, Sys = StaticSystem<(), Option<()>>>,
130    {
131        self.add_system_to_stage(First, single_success_system(system));
132        self
133    }
134
135    /// Adds a system to [`CoreStage::Startup`] that inserts the default value
136    /// of a resource into the [`World`] if it doesn't already exist.
137    pub fn init_startup_resource<R: HasSchema + FromWorld>(&mut self) -> &mut Self {
138        self.add_system_to_stage(StartupResource, |world: &World| {
139            world.init_resource::<R>();
140        });
141        self
142    }
143
144    /// Adds a system to [`CoreStage::StartupResource`] that inserts the given
145    /// resource into the [`World`] if it doesn't already exist. The resource
146    /// type is required to have a [`HasSchema`] clone implementation to
147    /// re-insert the resource into the world after the first startup.
148    ///
149    /// # Clone Requirement Details
150    /// If the type being added implements [`HasSchema`] with the derive like
151    /// so:
152    /// ```ignore
153    /// #[derive(HasSchema, Default)]
154    /// #[schema(no_clone)] // This bypasses HasSchema clone requirements.
155    /// struct ResourceBeingInserted;
156    /// ```
157    /// Then the system being added to the [`StartupResource`] system stage will
158    /// panic when inserting a second time. The startup resource stage only runs
159    /// once so it is therefore safe to use a type like the example above as
160    /// long as you don't plan on removing from the [`World`] the
161    /// [`StartupSystemStage`] tag which in this case is
162    /// [`CoreStageStartupResourceSystemsRan`].
163    pub fn add_startup_resource<R: HasSchema>(&mut self, resource: R) -> &mut Self {
164        let mut once = Some(SchemaBox::new(resource));
165
166        self.add_system_to_stage(StartupResource, move |world: &World| {
167            if !world.resources.contains::<R>() {
168                let schema_box = if R::schema().clone_fn.is_some() {
169                    once.clone()
170                } else {
171                    once.take()
172                };
173
174                if let Some(schema_box) = schema_box {
175                    world
176                        .resources
177                        .untyped()
178                        .get(R::schema())
179                        .insert(schema_box)
180                        .unwrap();
181                } else {
182                    panic!(
183                        "The schema for this type does not allow cloning it.\nSchema: {:#?}; \
184                    You may need to add the resource to the `ResetWorld::reset_resources` \
185                    to avoid cloning on startup.",
186                        R::schema()
187                    )
188                };
189            }
190        });
191        self
192    }
193}
194
195impl std::fmt::Debug for SystemStages {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        f.debug_struct("SystemStages")
198            // TODO: Add list of stages to the debug render for `SystemStages`.
199            // We can at least list the names of each stage for `SystemStages` debug
200            // implementation.
201            .finish()
202    }
203}
204
205/// Trait for system stages.
206pub trait SystemStage: Sync + Send {
207    /// The unique identifier for the stage.
208    fn id(&self) -> Ulid;
209    /// The human-readable name for the stage, used for error messages when something goes wrong.
210    fn name(&self) -> String;
211    /// Execute the systems on the given `world`.
212    fn run(&mut self, world: &World);
213
214    /// Add a system to this stage.
215    fn add_system(&mut self, system: StaticSystem<(), ()>);
216    /// Remove all systems from this stage.
217    fn remove_all_systems(&mut self);
218}
219
220/// A collection of systems that will be run in order.
221pub struct SimpleSystemStage {
222    /// The unique identifier for the stage.
223    pub id: Ulid,
224    /// The human-readable name for the stage, used for error messages when something goes wrong.
225    pub name: String,
226    /// The list of systems in the stage.
227    ///
228    /// Each system will be run in the order that they are in in this list.
229    pub systems: Vec<StaticSystem<(), ()>>,
230}
231
232impl SimpleSystemStage {
233    /// Create a new, empty stage, for the given label.
234    pub fn new<L: StageLabel>(label: L) -> Self {
235        Self {
236            id: label.id(),
237            name: label.name(),
238            systems: Default::default(),
239        }
240    }
241}
242
243impl SystemStage for SimpleSystemStage {
244    fn id(&self) -> Ulid {
245        self.id
246    }
247
248    fn name(&self) -> String {
249        self.name.clone()
250    }
251
252    fn run(&mut self, world: &World) {
253        // Run the systems
254        for system in &mut self.systems {
255            system.run(world, ());
256        }
257
258        // Drain the command queue
259        let queue = world.resources.get_mut::<CommandQueue>();
260        if let Some(mut command_queue) = queue {
261            for mut system in command_queue.queue.drain(..) {
262                system.run(world, ());
263            }
264        }
265    }
266
267    fn add_system(&mut self, system: StaticSystem<(), ()>) {
268        self.systems.push(system);
269    }
270
271    fn remove_all_systems(&mut self) {
272        self.systems.clear();
273    }
274}
275
276/// Resource for tracking whether or not the game has run the startup systems in
277/// [`CoreStage::Startup`].
278#[derive(HasSchema, Clone, Default, Debug)]
279pub struct CoreStageStartupSystemsRan;
280
281/// Resource for tracking whether or not the game has run the startup systems in
282/// [`CoreStage::StartupResource`].
283#[derive(HasSchema, Clone, Default, Debug)]
284pub struct CoreStageStartupResourceSystemsRan;
285
286/// [`SystemStage`] for running systems once on startup.
287pub struct StartupSystemStage<T: HasSchema + Default + Clone> {
288    /// The unique identifier for the stage.
289    pub id: Ulid,
290    /// The human-readable name for the stage, used for error messages when something goes wrong.
291    pub name: String,
292    /// The list of systems in the stage.
293    ///
294    /// Each system will be run in the order that they are in in this list.
295    pub systems: Vec<StaticSystem<(), ()>>,
296    _phantom_data: PhantomData<T>,
297}
298impl<T: HasSchema + Clone + Default> StartupSystemStage<T> {
299    /// Create a new, empty stage, for the given label.
300    pub fn new<L: StageLabel>(label: L) -> Self {
301        Self {
302            id: label.id(),
303            name: label.name(),
304            systems: Default::default(),
305            _phantom_data: PhantomData,
306        }
307    }
308}
309impl<T: HasSchema + Clone + Default> SystemStage for StartupSystemStage<T> {
310    fn id(&self) -> Ulid {
311        self.id
312    }
313
314    fn name(&self) -> String {
315        self.name.clone()
316    }
317
318    fn run(&mut self, world: &World) {
319        if world.get_resource_mut::<T>().is_none() {
320            // Run the systems
321            for system in &mut self.systems {
322                system.run(world, ());
323            }
324            world.insert_resource(T::default());
325        }
326
327        // Drain the command queue
328        let queue = world.resources.get_mut::<CommandQueue>();
329        if let Some(mut command_queue) = queue {
330            for mut system in command_queue.queue.drain(..) {
331                system.run(world, ());
332            }
333        }
334    }
335
336    fn add_system(&mut self, system: StaticSystem<(), ()>) {
337        self.systems.push(system);
338    }
339
340    fn remove_all_systems(&mut self) {
341        self.systems.clear();
342    }
343}
344
345/// Wrapper system for single success systems.
346///
347/// Runs the given system each frame until it succeeds (returns Some). Uses
348/// `Option<()>` instead of a `bool` to allow for easy usage of `?`.
349///
350/// System success is tracked with the [`SingleSuccessSystems`] resource which
351/// can be removed if you wish to let all single success systems run again.
352pub fn single_success_system<Args, S>(system: S) -> StaticSystem<(), ()>
353where
354    S: IntoSystem<Args, (), Option<()>, Sys = StaticSystem<(), Option<()>>>,
355{
356    use std::sync::atomic::{AtomicU64, Ordering};
357    static SINGLE_SUCCESS_SYSTEM_ID_GEN: AtomicU64 = AtomicU64::new(0);
358
359    let id = SINGLE_SUCCESS_SYSTEM_ID_GEN.fetch_add(1, Ordering::SeqCst);
360    let mut system = system.system();
361    (move |world: &World| {
362        if !world.init_resource::<SingleSuccessSystems>().contains(&id)
363            && system.run(world, ()).is_some()
364        {
365            world.init_resource::<SingleSuccessSystems>().insert(id);
366        }
367    })
368    .system()
369}
370
371/// Resource tracking which single success systems have completed using a
372/// [`HashSet`] of unique [`u64`]s for the succeeded.
373#[derive(HasSchema, Clone, Default, Deref, DerefMut)]
374pub struct SingleSuccessSystems(pub HashSet<u64>);
375
376/// Trait for things that may be used to identify a system stage.
377pub trait StageLabel {
378    /// Returns the human-readable name of the label, used in error messages.
379    fn name(&self) -> String;
380    /// Returns a unique identifier for the stage.
381    fn id(&self) -> Ulid;
382}
383
384/// A [`StageLabel`] for the 5 core stages.
385#[derive(Copy, Clone, Debug, PartialEq, Eq)]
386pub enum CoreStage {
387    /// The startup resource insertion stage
388    StartupResource,
389    /// The startup stage
390    Startup,
391    /// The first stage
392    First,
393    /// The second stage
394    PreUpdate,
395    /// The third stage
396    Update,
397    /// The fourth stage
398    PostUpdate,
399    /// The fifth stage
400    Last,
401}
402
403impl StageLabel for CoreStage {
404    fn name(&self) -> String {
405        format!("{:?}", self)
406    }
407
408    fn id(&self) -> Ulid {
409        match self {
410            CoreStage::StartupResource => Ulid(2162940536129995539438442124983465554),
411            CoreStage::Startup => Ulid(2149923225027836290977818907354065512),
412            CoreStage::First => Ulid(2021715391084198804812356024998495966),
413            CoreStage::PreUpdate => Ulid(2021715401330719559452824437611089988),
414            CoreStage::Update => Ulid(2021715410160177201728645950400543948),
415            CoreStage::PostUpdate => Ulid(2021715423103233646561968734173322317),
416            CoreStage::Last => Ulid(2021715433398666914977687392909851554),
417        }
418    }
419}
420
421/// A resource containing the [`Commands`] command queue.
422///
423/// You can use [`Commands`] as a [`SystemParam`] as a shortcut to [`ResMut<CommandQueue>`].
424#[derive(HasSchema, Default)]
425pub struct CommandQueue {
426    /// The system queue that will be run at the end of the stage
427    pub queue: VecDeque<StaticSystem<(), ()>>,
428}
429
430impl Clone for CommandQueue {
431    fn clone(&self) -> Self {
432        if self.queue.is_empty() {
433            Self {
434                queue: VecDeque::with_capacity(self.queue.capacity()),
435            }
436        } else {
437            panic!(
438                "Cannot clone CommandQueue. This probably happened because you are \
439                trying to clone a World while a system stage is still executing."
440            )
441        }
442    }
443}
444
445impl CommandQueue {
446    /// Add a system to be run at the end of the stage.
447    pub fn add<Args, S>(&mut self, system: S)
448    where
449        S: IntoSystem<Args, (), (), Sys = StaticSystem<(), ()>>,
450    {
451        self.queue.push_back(system.system());
452    }
453}
454
455/// A [`SystemParam`] that can be used to schedule systems that will be run at the end of the
456/// current [`SystemStage`].
457///
458/// This is a shortcut for [`ResMut<CommandQueue>`].
459#[derive(Deref, DerefMut)]
460pub struct Commands<'a>(RefMut<'a, CommandQueue>);
461
462impl<'a> SystemParam for Commands<'a> {
463    type State = AtomicResource<CommandQueue>;
464    type Param<'s> = Commands<'s>;
465
466    fn get_state(world: &World) -> Self::State {
467        let cell = world.resources.get_cell::<CommandQueue>();
468        cell.init(world);
469        cell
470    }
471
472    fn borrow<'s>(_world: &'s World, state: &'s mut Self::State) -> Self::Param<'s> {
473        Commands(state.borrow_mut().unwrap())
474    }
475}