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(PostUpdate, TransformGizmoRenderStep)
329 .configure_sets(
330 RunFixedMainLoop,
331 (
332 RunFixedMainLoopSystems::BeforeFixedMainLoop,
333 RunFixedMainLoopSystems::FixedMainLoop,
334 RunFixedMainLoopSystems::AfterFixedMainLoop,
335 )
336 .chain(),
337 );
338
339 #[cfg(feature = "bevy_debug_stepping")]
340 {
341 use bevy_ecs::schedule::{IntoScheduleConfigs, Stepping};
342 app.add_systems(Main, Stepping::begin_frame.before(Main::run_main));
343 }
344 }
345}
346
347/// Defines the schedules to be run for the [`FixedMain`] schedule, including
348/// their order.
349#[derive(Resource, Debug)]
350pub struct FixedMainScheduleOrder {
351 /// The labels to run for the [`FixedMain`] schedule (in the order they will be run).
352 pub labels: Vec<InternedScheduleLabel>,
353}
354
355impl Default for FixedMainScheduleOrder {
356 fn default() -> Self {
357 Self {
358 labels: vec![
359 FixedFirst.intern(),
360 FixedPreUpdate.intern(),
361 FixedUpdate.intern(),
362 FixedPostUpdate.intern(),
363 FixedLast.intern(),
364 ],
365 }
366 }
367}
368
369impl FixedMainScheduleOrder {
370 /// Adds the given `schedule` after the `after` schedule
371 pub fn insert_after(&mut self, after: impl ScheduleLabel, schedule: impl ScheduleLabel) {
372 let index = self
373 .labels
374 .iter()
375 .position(|current| (**current).eq(&after))
376 .unwrap_or_else(|| panic!("Expected {after:?} to exist"));
377 self.labels.insert(index + 1, schedule.intern());
378 }
379
380 /// Adds the given `schedule` before the `before` schedule
381 pub fn insert_before(&mut self, before: impl ScheduleLabel, schedule: impl ScheduleLabel) {
382 let index = self
383 .labels
384 .iter()
385 .position(|current| (**current).eq(&before))
386 .unwrap_or_else(|| panic!("Expected {before:?} to exist"));
387 self.labels.insert(index, schedule.intern());
388 }
389}
390
391impl FixedMain {
392 /// A system that runs the fixed timestep's "main schedule"
393 pub fn run_fixed_main(world: &mut World) {
394 world.resource_scope(|world, order: Mut<FixedMainScheduleOrder>| {
395 for &label in &order.labels {
396 let _ = world.try_run_schedule(label);
397 }
398 });
399 }
400}
401
402/// Set enum for the systems that want to run inside [`RunFixedMainLoop`],
403/// but before or after the fixed update logic. Systems in this set
404/// will run exactly once per frame, regardless of the number of fixed updates.
405/// They will also run under a variable timestep.
406///
407/// This is useful for handling things that need to run every frame, but
408/// also need to be read by the fixed update logic. See the individual variants
409/// for examples of what kind of systems should be placed in each.
410///
411/// Note that in contrast to most other Bevy schedules, systems added directly to
412/// [`RunFixedMainLoop`] will *not* be parallelized between each other.
413#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, SystemSet)]
414pub enum RunFixedMainLoopSystems {
415 /// Runs before the fixed update logic.
416 ///
417 /// A good example of a system that fits here
418 /// is camera movement, which needs to be updated in a variable timestep,
419 /// as you want the camera to move with as much precision and updates as
420 /// the frame rate allows. A physics system that needs to read the camera
421 /// position and orientation, however, should run in the fixed update logic,
422 /// as it needs to be deterministic and run at a fixed rate for better stability.
423 /// Note that we are not placing the camera movement system in `Update`, as that
424 /// would mean that the physics system already ran at that point.
425 ///
426 /// # Example
427 /// ```
428 /// # use bevy_app::prelude::*;
429 /// # use bevy_ecs::prelude::*;
430 /// App::new()
431 /// .add_systems(
432 /// RunFixedMainLoop,
433 /// update_camera_rotation.in_set(RunFixedMainLoopSystems::BeforeFixedMainLoop))
434 /// .add_systems(FixedUpdate, update_physics);
435 ///
436 /// # fn update_camera_rotation() {}
437 /// # fn update_physics() {}
438 /// ```
439 BeforeFixedMainLoop,
440 /// Contains the fixed update logic.
441 /// Runs [`FixedMain`] zero or more times based on delta of
442 /// [`Time<Virtual>`] and [`Time::overstep`].
443 ///
444 /// Don't place systems here, use [`FixedUpdate`] and friends instead.
445 /// Use this system instead to order your systems to run specifically inbetween the fixed update logic and all
446 /// other systems that run in [`RunFixedMainLoopSystems::BeforeFixedMainLoop`] or [`RunFixedMainLoopSystems::AfterFixedMainLoop`].
447 ///
448 /// [`Time<Virtual>`]: https://docs.rs/bevy/latest/bevy/prelude/struct.Virtual.html
449 /// [`Time::overstep`]: https://docs.rs/bevy/latest/bevy/time/struct.Time.html#method.overstep
450 /// # Example
451 /// ```
452 /// # use bevy_app::prelude::*;
453 /// # use bevy_ecs::prelude::*;
454 /// App::new()
455 /// .add_systems(FixedUpdate, update_physics)
456 /// .add_systems(
457 /// RunFixedMainLoop,
458 /// (
459 /// // This system will be called before all interpolation systems
460 /// // that third-party plugins might add.
461 /// prepare_for_interpolation
462 /// .after(RunFixedMainLoopSystems::FixedMainLoop)
463 /// .before(RunFixedMainLoopSystems::AfterFixedMainLoop),
464 /// )
465 /// );
466 ///
467 /// # fn prepare_for_interpolation() {}
468 /// # fn update_physics() {}
469 /// ```
470 FixedMainLoop,
471 /// Runs after the fixed update logic.
472 ///
473 /// A good example of a system that fits here
474 /// is a system that interpolates the transform of an entity between the last and current fixed update.
475 /// See the [fixed timestep example] for more details.
476 ///
477 /// [fixed timestep example]: https://github.com/bevyengine/bevy/blob/main/examples/movement/physics_in_fixed_timestep.rs
478 ///
479 /// # Example
480 /// ```
481 /// # use bevy_app::prelude::*;
482 /// # use bevy_ecs::prelude::*;
483 /// App::new()
484 /// .add_systems(FixedUpdate, update_physics)
485 /// .add_systems(
486 /// RunFixedMainLoop,
487 /// interpolate_transforms.in_set(RunFixedMainLoopSystems::AfterFixedMainLoop));
488 ///
489 /// # fn interpolate_transforms() {}
490 /// # fn update_physics() {}
491 /// ```
492 AfterFixedMainLoop,
493}
494
495/// A System set that runs all systems needed to render the transform gizmo to the screen, used in the `bevy_gizmos_render` crate
496/// This is defined here since it is used by many other
497/// bevy crates to specify system orderings.
498/// This is used for Bevy's Transform Gizmo and any other gizmo that render similar to it.
499#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)]
500pub struct TransformGizmoRenderStep;