Skip to main content

bevy_app/
main_schedule.rs

1use crate::{App, Plugin};
2use alloc::{vec, vec::Vec};
3use bevy_ecs::{
4    resource::Resource,
5    schedule::{
6        InternedScheduleLabel, IntoScheduleConfigs, Schedule, ScheduleLabel,
7        SingleThreadedExecutor, SystemSet,
8    },
9    system::Local,
10    world::{Mut, World},
11};
12
13/// The schedule that contains the app logic that is evaluated each tick of [`App::update()`].
14///
15/// By default, it will run the following schedules in the given order:
16///
17/// On the first run of the schedule (and only on the first run), it will run:
18/// * [`StateTransition`] [^1]
19///      * This means that [`OnEnter(MyState::Foo)`] will be called *before* [`PreStartup`]
20///        if `MyState` was added to the app with `MyState::Foo` as the initial state,
21///        as well as [`OnEnter(MyComputedState)`] if it `compute`s to `Some(Self)` in `MyState::Foo`.
22///      * If you want to run systems before any state transitions, regardless of which state is the starting state,
23///        for example, for registering required components, you can add your own custom startup schedule
24///        before [`StateTransition`]. See [`MainScheduleOrder::insert_startup_before`] for more details.
25/// * [`PreStartup`]
26/// * [`Startup`]
27/// * [`PostStartup`]
28///
29/// Then it will run:
30/// * [`First`]
31/// * [`PreUpdate`]
32/// * [`StateTransition`] [^1]
33/// * [`RunFixedMainLoop`]
34///     * This will run [`FixedMain`] zero to many times, based on how much time has elapsed.
35/// * [`Update`]
36/// * [`SpawnScene`]
37/// * [`PostUpdate`]
38/// * [`Last`]
39///
40/// # Rendering
41///
42/// Note rendering is not executed in the main schedule by default.
43/// Instead, rendering is performed in a separate [`SubApp`]
44/// which exchanges data with the main app in between the main schedule runs.
45///
46/// See [`RenderPlugin`] and [`PipelinedRenderingPlugin`] for more details.
47///
48/// [^1]: [`StateTransition`] is inserted only if you have `bevy_state` feature enabled. It is enabled in `default` features.
49///
50/// [`StateTransition`]: https://docs.rs/bevy/latest/bevy/prelude/struct.StateTransition.html
51/// [`OnEnter(MyState::Foo)`]: https://docs.rs/bevy/latest/bevy/prelude/struct.OnEnter.html
52/// [`OnEnter(MyComputedState)`]: https://docs.rs/bevy/latest/bevy/prelude/struct.OnEnter.html
53/// [`RenderPlugin`]: https://docs.rs/bevy/latest/bevy/render/struct.RenderPlugin.html
54/// [`PipelinedRenderingPlugin`]: https://docs.rs/bevy/latest/bevy/render/pipelined_rendering/struct.PipelinedRenderingPlugin.html
55/// [`SubApp`]: crate::SubApp
56#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
57pub struct Main;
58
59/// The schedule that runs before [`Startup`].
60///
61/// See the [`Main`] schedule for some details about how schedules are run.
62#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
63pub struct PreStartup;
64
65/// The schedule that runs once when the app starts.
66///
67/// See the [`Main`] schedule for some details about how schedules are run.
68#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
69pub struct Startup;
70
71/// The schedule that runs once after [`Startup`].
72///
73/// See the [`Main`] schedule for some details about how schedules are run.
74#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
75pub struct PostStartup;
76
77/// Runs first in the schedule.
78///
79/// See the [`Main`] schedule for some details about how schedules are run.
80#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
81pub struct First;
82
83/// The schedule that contains logic that must run before [`Update`]. For example, a system that reads raw keyboard
84/// input OS events into a `Messages` resource. This enables systems in [`Update`] to consume the messages from the `Messages`
85/// resource without actually knowing about (or taking a direct scheduler dependency on) the "os-level keyboard event system".
86///
87/// [`PreUpdate`] exists to do "engine/plugin preparation work" that ensures the APIs consumed in [`Update`] are "ready".
88/// [`PreUpdate`] abstracts out "pre work implementation details".
89///
90/// See the [`Main`] schedule for some details about how schedules are run.
91#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
92pub struct PreUpdate;
93
94/// Runs the [`FixedMain`] schedule in a loop according until all relevant elapsed time has been "consumed".
95///
96/// If you need to order your variable timestep systems before or after
97/// the fixed update logic, use the [`RunFixedMainLoopSystems`] system set.
98///
99/// Note that in contrast to most other Bevy schedules, systems added directly to
100/// [`RunFixedMainLoop`] will *not* be parallelized between each other.
101///
102/// See the [`Main`] schedule for some details about how schedules are run.
103#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
104pub struct RunFixedMainLoop;
105
106/// Runs first in the [`FixedMain`] schedule.
107///
108/// See the [`FixedMain`] schedule for details on how fixed updates work.
109/// See the [`Main`] schedule for some details about how schedules are run.
110#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
111pub struct FixedFirst;
112
113/// The schedule that contains logic that must run before [`FixedUpdate`].
114///
115/// See the [`FixedMain`] schedule for details on how fixed updates work.
116/// See the [`Main`] schedule for some details about how schedules are run.
117#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
118pub struct FixedPreUpdate;
119
120/// The schedule that contains most gameplay logic, which runs at a fixed rate rather than every render frame.
121/// For logic that should run once per render frame, use the [`Update`] schedule instead.
122///
123/// Examples of systems that should run at a fixed rate include (but are not limited to):
124/// - Physics
125/// - AI
126/// - Networking
127/// - Game rules
128///
129/// See the [`Update`] schedule for examples of systems that *should not* use this schedule.
130/// See the [`FixedMain`] schedule for details on how fixed updates work.
131/// See the [`Main`] schedule for some details about how schedules are run.
132#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
133pub struct FixedUpdate;
134
135/// The schedule that runs after the [`FixedUpdate`] schedule, for reacting
136/// to changes made in the main update logic.
137///
138/// See the [`FixedMain`] schedule for details on how fixed updates work.
139/// See the [`Main`] schedule for some details about how schedules are run.
140#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
141pub struct FixedPostUpdate;
142
143/// The schedule that runs last in [`FixedMain`]
144///
145/// See the [`FixedMain`] schedule for details on how fixed updates work.
146/// See the [`Main`] schedule for some details about how schedules are run.
147#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
148pub struct FixedLast;
149
150/// The schedule that contains systems which only run after a fixed period of time has elapsed.
151///
152/// This is run by the [`RunFixedMainLoop`] schedule. If you need to order your variable timestep systems
153/// before or after the fixed update logic, use the [`RunFixedMainLoopSystems`] system set.
154///
155/// Frequency of execution is configured by inserting `Time<Fixed>` resource, 64 Hz by default.
156/// See [this example](https://github.com/bevyengine/bevy/blob/latest/examples/time/time.rs).
157///
158/// See the [`Main`] schedule for some details about how schedules are run.
159#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
160pub struct FixedMain;
161
162/// The schedule that contains any app logic that must run once per render frame.
163/// For most gameplay logic, consider using [`FixedUpdate`] instead.
164///
165/// Examples of systems that should run once per render frame include (but are not limited to):
166/// - UI
167/// - Input handling
168/// - Audio control
169///
170/// See the [`FixedUpdate`] schedule for examples of systems that *should not* use this schedule.
171/// See the [`Main`] schedule for some details about how schedules are run.
172#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
173pub struct Update;
174
175/// The schedule that contains scene spawning.
176///
177/// This runs after [`Update`] and before [`PostUpdate`]. See the [`Main`] schedule for more details about how schedules are run.
178#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
179pub struct SpawnScene;
180
181/// The schedule that contains logic that must run after [`Update`]. For example, synchronizing "local transforms" in a hierarchy
182/// to "global" absolute transforms. This enables the [`PostUpdate`] transform-sync system to react to "local transform" changes in
183/// [`Update`] without the [`Update`] systems needing to know about (or add scheduler dependencies for) the "global transform sync system".
184///
185/// [`PostUpdate`] exists to do "engine/plugin response work" to things that happened in [`Update`].
186/// [`PostUpdate`] abstracts out "implementation details" from users defining systems in [`Update`].
187///
188/// See the [`Main`] schedule for some details about how schedules are run.
189#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
190pub struct PostUpdate;
191
192/// Runs last in the schedule.
193///
194/// See the [`Main`] schedule for some details about how schedules are run.
195#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
196pub struct Last;
197
198/// Animation system set. This exists in [`PostUpdate`].
199#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)]
200pub struct AnimationSystems;
201
202/// Set enum for the systems relating to scene spawning.
203#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
204pub enum SceneSpawnerSystems {
205    /// Bevy's original scene system.
206    WorldInstanceSpawn,
207    /// Bevy's next-generation scene system
208    SceneSpawn,
209}
210
211/// Defines the schedules to be run for the [`Main`] schedule, including
212/// their order.
213#[derive(Resource, Debug)]
214pub struct MainScheduleOrder {
215    /// The labels to run for the main phase of the [`Main`] schedule (in the order they will be run).
216    pub labels: Vec<InternedScheduleLabel>,
217    /// The labels to run for the startup phase of the [`Main`] schedule (in the order they will be run).
218    pub startup_labels: Vec<InternedScheduleLabel>,
219}
220
221impl Default for MainScheduleOrder {
222    fn default() -> Self {
223        Self {
224            labels: vec![
225                First.intern(),
226                PreUpdate.intern(),
227                RunFixedMainLoop.intern(),
228                Update.intern(),
229                SpawnScene.intern(),
230                PostUpdate.intern(),
231                Last.intern(),
232            ],
233            startup_labels: vec![PreStartup.intern(), Startup.intern(), PostStartup.intern()],
234        }
235    }
236}
237
238impl MainScheduleOrder {
239    /// Adds the given `schedule` after the `after` schedule in the main list of schedules.
240    pub fn insert_after(&mut self, after: impl ScheduleLabel, schedule: impl ScheduleLabel) {
241        let index = self
242            .labels
243            .iter()
244            .position(|current| (**current).eq(&after))
245            .unwrap_or_else(|| panic!("Expected {after:?} to exist"));
246        self.labels.insert(index + 1, schedule.intern());
247    }
248
249    /// Adds the given `schedule` before the `before` schedule in the main list of schedules.
250    pub fn insert_before(&mut self, before: impl ScheduleLabel, schedule: impl ScheduleLabel) {
251        let index = self
252            .labels
253            .iter()
254            .position(|current| (**current).eq(&before))
255            .unwrap_or_else(|| panic!("Expected {before:?} to exist"));
256        self.labels.insert(index, schedule.intern());
257    }
258
259    /// Adds the given `schedule` after the `after` schedule in the list of startup schedules.
260    pub fn insert_startup_after(
261        &mut self,
262        after: impl ScheduleLabel,
263        schedule: impl ScheduleLabel,
264    ) {
265        let index = self
266            .startup_labels
267            .iter()
268            .position(|current| (**current).eq(&after))
269            .unwrap_or_else(|| panic!("Expected {after:?} to exist"));
270        self.startup_labels.insert(index + 1, schedule.intern());
271    }
272
273    /// Adds the given `schedule` before the `before` schedule in the list of startup schedules.
274    pub fn insert_startup_before(
275        &mut self,
276        before: impl ScheduleLabel,
277        schedule: impl ScheduleLabel,
278    ) {
279        let index = self
280            .startup_labels
281            .iter()
282            .position(|current| (**current).eq(&before))
283            .unwrap_or_else(|| panic!("Expected {before:?} to exist"));
284        self.startup_labels.insert(index, schedule.intern());
285    }
286}
287
288impl Main {
289    /// A system that runs the "main schedule"
290    pub fn run_main(world: &mut World, mut run_at_least_once: Local<bool>) {
291        if !*run_at_least_once {
292            world.resource_scope(|world, order: Mut<MainScheduleOrder>| {
293                for &label in &order.startup_labels {
294                    let _ = world.try_run_schedule(label);
295                }
296            });
297            *run_at_least_once = true;
298        }
299
300        world.resource_scope(|world, order: Mut<MainScheduleOrder>| {
301            for &label in &order.labels {
302                let _ = world.try_run_schedule(label);
303            }
304        });
305    }
306}
307
308/// Initializes the [`Main`] schedule, sub schedules, and resources for a given [`App`].
309pub struct MainSchedulePlugin;
310
311impl Plugin for MainSchedulePlugin {
312    fn build(&self, app: &mut App) {
313        // simple "facilitator" schedules benefit from simpler single threaded scheduling
314        let mut main_schedule = Schedule::new(Main);
315        main_schedule.set_executor(SingleThreadedExecutor::new());
316        let mut fixed_main_schedule = Schedule::new(FixedMain);
317        fixed_main_schedule.set_executor(SingleThreadedExecutor::new());
318        let mut fixed_main_loop_schedule = Schedule::new(RunFixedMainLoop);
319        fixed_main_loop_schedule.set_executor(SingleThreadedExecutor::new());
320
321        app.add_schedule(main_schedule)
322            .add_schedule(fixed_main_schedule)
323            .add_schedule(fixed_main_loop_schedule)
324            .init_resource::<MainScheduleOrder>()
325            .init_resource::<FixedMainScheduleOrder>()
326            .add_systems(Main, Main::run_main)
327            .add_systems(FixedMain, FixedMain::run_fixed_main)
328            .configure_sets(
329                RunFixedMainLoop,
330                (
331                    RunFixedMainLoopSystems::BeforeFixedMainLoop,
332                    RunFixedMainLoopSystems::FixedMainLoop,
333                    RunFixedMainLoopSystems::AfterFixedMainLoop,
334                )
335                    .chain(),
336            );
337
338        #[cfg(feature = "bevy_debug_stepping")]
339        {
340            use bevy_ecs::schedule::{IntoScheduleConfigs, Stepping};
341            app.add_systems(Main, Stepping::begin_frame.before(Main::run_main));
342        }
343    }
344}
345
346/// Defines the schedules to be run for the [`FixedMain`] schedule, including
347/// their order.
348#[derive(Resource, Debug)]
349pub struct FixedMainScheduleOrder {
350    /// The labels to run for the [`FixedMain`] schedule (in the order they will be run).
351    pub labels: Vec<InternedScheduleLabel>,
352}
353
354impl Default for FixedMainScheduleOrder {
355    fn default() -> Self {
356        Self {
357            labels: vec![
358                FixedFirst.intern(),
359                FixedPreUpdate.intern(),
360                FixedUpdate.intern(),
361                FixedPostUpdate.intern(),
362                FixedLast.intern(),
363            ],
364        }
365    }
366}
367
368impl FixedMainScheduleOrder {
369    /// Adds the given `schedule` after the `after` schedule
370    pub fn insert_after(&mut self, after: impl ScheduleLabel, schedule: impl ScheduleLabel) {
371        let index = self
372            .labels
373            .iter()
374            .position(|current| (**current).eq(&after))
375            .unwrap_or_else(|| panic!("Expected {after:?} to exist"));
376        self.labels.insert(index + 1, schedule.intern());
377    }
378
379    /// Adds the given `schedule` before the `before` schedule
380    pub fn insert_before(&mut self, before: impl ScheduleLabel, schedule: impl ScheduleLabel) {
381        let index = self
382            .labels
383            .iter()
384            .position(|current| (**current).eq(&before))
385            .unwrap_or_else(|| panic!("Expected {before:?} to exist"));
386        self.labels.insert(index, schedule.intern());
387    }
388}
389
390impl FixedMain {
391    /// A system that runs the fixed timestep's "main schedule"
392    pub fn run_fixed_main(world: &mut World) {
393        world.resource_scope(|world, order: Mut<FixedMainScheduleOrder>| {
394            for &label in &order.labels {
395                let _ = world.try_run_schedule(label);
396            }
397        });
398    }
399}
400
401/// Set enum for the systems that want to run inside [`RunFixedMainLoop`],
402/// but before or after the fixed update logic. Systems in this set
403/// will run exactly once per frame, regardless of the number of fixed updates.
404/// They will also run under a variable timestep.
405///
406/// This is useful for handling things that need to run every frame, but
407/// also need to be read by the fixed update logic. See the individual variants
408/// for examples of what kind of systems should be placed in each.
409///
410/// Note that in contrast to most other Bevy schedules, systems added directly to
411/// [`RunFixedMainLoop`] will *not* be parallelized between each other.
412#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, SystemSet)]
413pub enum RunFixedMainLoopSystems {
414    /// Runs before the fixed update logic.
415    ///
416    /// A good example of a system that fits here
417    /// is camera movement, which needs to be updated in a variable timestep,
418    /// as you want the camera to move with as much precision and updates as
419    /// the frame rate allows. A physics system that needs to read the camera
420    /// position and orientation, however, should run in the fixed update logic,
421    /// as it needs to be deterministic and run at a fixed rate for better stability.
422    /// Note that we are not placing the camera movement system in `Update`, as that
423    /// would mean that the physics system already ran at that point.
424    ///
425    /// # Example
426    /// ```
427    /// # use bevy_app::prelude::*;
428    /// # use bevy_ecs::prelude::*;
429    /// App::new()
430    ///   .add_systems(
431    ///     RunFixedMainLoop,
432    ///     update_camera_rotation.in_set(RunFixedMainLoopSystems::BeforeFixedMainLoop))
433    ///   .add_systems(FixedUpdate, update_physics);
434    ///
435    /// # fn update_camera_rotation() {}
436    /// # fn update_physics() {}
437    /// ```
438    BeforeFixedMainLoop,
439    /// Contains the fixed update logic.
440    /// Runs [`FixedMain`] zero or more times based on delta of
441    /// [`Time<Virtual>`] and [`Time::overstep`].
442    ///
443    /// Don't place systems here, use [`FixedUpdate`] and friends instead.
444    /// Use this system instead to order your systems to run specifically inbetween the fixed update logic and all
445    /// other systems that run in [`RunFixedMainLoopSystems::BeforeFixedMainLoop`] or [`RunFixedMainLoopSystems::AfterFixedMainLoop`].
446    ///
447    /// [`Time<Virtual>`]: https://docs.rs/bevy/latest/bevy/prelude/struct.Virtual.html
448    /// [`Time::overstep`]: https://docs.rs/bevy/latest/bevy/time/struct.Time.html#method.overstep
449    /// # Example
450    /// ```
451    /// # use bevy_app::prelude::*;
452    /// # use bevy_ecs::prelude::*;
453    /// App::new()
454    ///   .add_systems(FixedUpdate, update_physics)
455    ///   .add_systems(
456    ///     RunFixedMainLoop,
457    ///     (
458    ///       // This system will be called before all interpolation systems
459    ///       // that third-party plugins might add.
460    ///       prepare_for_interpolation
461    ///         .after(RunFixedMainLoopSystems::FixedMainLoop)
462    ///         .before(RunFixedMainLoopSystems::AfterFixedMainLoop),
463    ///     )
464    ///   );
465    ///
466    /// # fn prepare_for_interpolation() {}
467    /// # fn update_physics() {}
468    /// ```
469    FixedMainLoop,
470    /// Runs after the fixed update logic.
471    ///
472    /// A good example of a system that fits here
473    /// is a system that interpolates the transform of an entity between the last and current fixed update.
474    /// See the [fixed timestep example] for more details.
475    ///
476    /// [fixed timestep example]: https://github.com/bevyengine/bevy/blob/main/examples/movement/physics_in_fixed_timestep.rs
477    ///
478    /// # Example
479    /// ```
480    /// # use bevy_app::prelude::*;
481    /// # use bevy_ecs::prelude::*;
482    /// App::new()
483    ///   .add_systems(FixedUpdate, update_physics)
484    ///   .add_systems(
485    ///     RunFixedMainLoop,
486    ///     interpolate_transforms.in_set(RunFixedMainLoopSystems::AfterFixedMainLoop));
487    ///
488    /// # fn interpolate_transforms() {}
489    /// # fn update_physics() {}
490    /// ```
491    AfterFixedMainLoop,
492}