avian2d/schedule/
mod.rs

1//! Sets up the default scheduling, system set configuration, and time resources for physics.
2//!
3//! See [`PhysicsSchedulePlugin`].
4
5mod time;
6use dynamics::solver::schedule::SubstepCount;
7pub use time::*;
8
9use core::time::Duration;
10
11// For doc links
12#[allow(unused_imports)]
13use crate::prelude::*;
14
15use bevy::{
16    ecs::{
17        component::Tick,
18        intern::Interned,
19        schedule::{ExecutorKind, LogLevel, ScheduleBuildSettings, ScheduleLabel},
20        system::SystemChangeTick,
21    },
22    prelude::*,
23    transform::TransformSystems,
24};
25
26/// Sets up the default scheduling, system set configuration, and time resources for physics.
27///
28/// # Schedules and Sets
29///
30/// This plugin initializes and configures the following schedules and system sets:
31///
32/// - [`PhysicsSystems`]: High-level system sets for the main phases of the physics engine.
33///   You can use these to schedule your own systems before or after physics is run without
34///   having to worry about implementation details.
35/// - [`PhysicsSchedule`]: Responsible for advancing the simulation in [`PhysicsSystems::StepSimulation`].
36/// - [`PhysicsStepSystems`]: System sets for the steps of the actual physics simulation loop.
37pub struct PhysicsSchedulePlugin {
38    schedule: Interned<dyn ScheduleLabel>,
39}
40
41impl PhysicsSchedulePlugin {
42    /// Creates a [`PhysicsSchedulePlugin`] using the given schedule for running the [`PhysicsSchedule`].
43    ///
44    /// The default schedule is `FixedPostUpdate`.
45    pub fn new(schedule: impl ScheduleLabel) -> Self {
46        Self {
47            schedule: schedule.intern(),
48        }
49    }
50}
51
52impl Default for PhysicsSchedulePlugin {
53    fn default() -> Self {
54        Self::new(FixedPostUpdate)
55    }
56}
57
58impl Plugin for PhysicsSchedulePlugin {
59    fn build(&self, app: &mut App) {
60        // Register types with generics.
61        app.register_type::<Time<Physics>>();
62
63        app.init_resource::<Time<Physics>>()
64            .insert_resource(Time::new_with(Substeps))
65            .init_resource::<SubstepCount>()
66            .init_resource::<LastPhysicsTick>();
67
68        // TODO: Where should this be initialized?
69        app.init_resource::<PhysicsLengthUnit>();
70
71        // Configure higher level system sets for the given schedule
72        let schedule = self.schedule;
73
74        app.configure_sets(
75            schedule,
76            (
77                PhysicsSystems::First,
78                PhysicsSystems::Prepare,
79                PhysicsSystems::StepSimulation,
80                PhysicsSystems::Writeback,
81                PhysicsSystems::Last,
82            )
83                .chain()
84                .before(TransformSystems::Propagate),
85        );
86
87        // Set up the physics schedule, the schedule that advances the physics simulation
88        app.edit_schedule(PhysicsSchedule, |schedule| {
89            schedule
90                .set_executor_kind(ExecutorKind::SingleThreaded)
91                .set_build_settings(ScheduleBuildSettings {
92                    ambiguity_detection: LogLevel::Error,
93                    ..default()
94                });
95
96            schedule.configure_sets(
97                (
98                    PhysicsStepSystems::First,
99                    PhysicsStepSystems::BroadPhase,
100                    PhysicsStepSystems::NarrowPhase,
101                    PhysicsStepSystems::Solver,
102                    PhysicsStepSystems::Sleeping,
103                    PhysicsStepSystems::SpatialQuery,
104                    PhysicsStepSystems::Finalize,
105                    PhysicsStepSystems::Last,
106                )
107                    .chain(),
108            );
109        });
110
111        app.add_systems(
112            schedule,
113            run_physics_schedule.in_set(PhysicsSystems::StepSimulation),
114        );
115
116        app.add_systems(
117            PhysicsSchedule,
118            update_last_physics_tick.after(PhysicsStepSystems::Last),
119        );
120    }
121}
122
123/// True if a system is running for the first time.
124struct IsFirstRun(bool);
125
126impl Default for IsFirstRun {
127    fn default() -> Self {
128        Self(true)
129    }
130}
131
132/// Responsible for advancing the physics simulation. This is run in [`PhysicsSystems::StepSimulation`].
133///
134/// See [`PhysicsStepSystems`] for the system sets that are run in this schedule.
135#[derive(Debug, Hash, PartialEq, Eq, Clone, ScheduleLabel)]
136pub struct PhysicsSchedule;
137
138/// High-level system sets for the main phases of the physics engine.
139/// You can use these to schedule your own systems before or after physics is run without
140/// having to worry about implementation details.
141///
142/// 1. `First`: Runs right before any of Avian's physics systems. Empty by default.
143/// 2. `Prepare`: Responsible for preparing data for the physics simulation, such as updating
144///    physics transforms or mass properties.
145/// 3. `StepSimulation`: Responsible for advancing the simulation by running the steps in [`PhysicsStepSystems`].
146/// 4. `Writeback`: Responsible for writing back the results of the physics simulation to other data,
147///    such as updating [`Transform`] based on the new [`Position`] and [`Rotation`].
148/// 5. `Last`: Runs right after all of Avian's physics systems. Empty by default.
149///
150/// # See Also
151///
152/// - [`PhysicsSchedule`]: Responsible for advancing the simulation in [`PhysicsSystems::StepSimulation`].
153/// - [`PhysicsStepSystems`]: System sets for the steps of the actual physics simulation loop, like
154///   the broad phase and the substepping loop.
155/// - [`SubstepSchedule`]: Responsible for running the substepping loop in [`PhysicsStepSystems::Solver`].
156#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
157pub enum PhysicsSystems {
158    /// Runs right before any of Avian's physics systems. Empty by default.
159    First,
160    /// Responsible for preparing data for the physics simulation, such as updating
161    /// physics transforms or mass properties.
162    Prepare,
163    /// Responsible for advancing the simulation by running the steps in [`PhysicsStepSystems`].
164    /// Systems in this set are run in the [`PhysicsSchedule`].
165    StepSimulation,
166    /// Responsible for writing back the results of the physics simulation to other data,
167    /// such as updating [`Transform`] based on the new [`Position`] and [`Rotation`].
168    Writeback,
169    /// Runs right after all of Avian's physics systems. Empty by default.
170    Last,
171}
172
173/// A deprecated alias for [`PhysicsSystems`].
174#[deprecated(since = "0.4.0", note = "Renamed to `PhysicsSystems`")]
175pub type PhysicsSet = PhysicsSystems;
176
177/// System sets for the main steps in the physics simulation loop. These are typically run in the [`PhysicsSchedule`].
178///
179/// 1. First
180/// 2. Broad phase
181/// 3. Narrow phase
182/// 4. Solver
183/// 5. Sleeping
184/// 6. Spatial queries
185/// 7. Last
186#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
187pub enum PhysicsStepSystems {
188    /// Runs at the start of the [`PhysicsSchedule`].
189    First,
190    /// Responsible for finding pairs of entities with overlapping [`ColliderAabb`]
191    /// and creating contact pairs for them in the [`ContactGraph`].
192    ///
193    /// See [`BroadPhasePlugin`].
194    BroadPhase,
195    /// Responsible for updating contacts in the [`ContactGraph`] and processing contact state changes.
196    ///
197    /// See [`NarrowPhasePlugin`].
198    NarrowPhase,
199    /// Responsible for running the solver and its substepping loop.
200    ///
201    /// See [`SolverPlugin`] and [`SubstepSchedule`].
202    Solver,
203    /// Responsible for controlling when bodies should be deactivated and marked as [`Sleeping`].
204    Sleeping,
205    /// Responsible for spatial queries like [raycasting](`RayCaster`) and shapecasting.
206    ///
207    /// See [`SpatialQueryPlugin`].
208    SpatialQuery,
209    /// Responsible for logic that runs after the core physics step and prepares for the next one.
210    Finalize,
211    /// Runs at the end of the [`PhysicsSchedule`].
212    Last,
213}
214
215/// A deprecated alias for [`PhysicsStepSystems`].
216#[deprecated(since = "0.4.0", note = "Renamed to `PhysicsStepSystems`")]
217pub type PhysicsStepSet = PhysicsStepSystems;
218
219/// A [`Tick`] corresponding to the end of the previous run of the [`PhysicsSchedule`].
220#[derive(Resource, Reflect, Default)]
221#[reflect(Resource, Default)]
222pub struct LastPhysicsTick(pub Tick);
223
224pub(crate) fn is_changed_after_tick<C: Component>(
225    component_ref: Ref<C>,
226    tick: Tick,
227    this_run: Tick,
228) -> bool {
229    let last_changed = component_ref.last_changed();
230    component_ref.is_changed() && last_changed.is_newer_than(tick, this_run)
231}
232
233/// Runs the [`PhysicsSchedule`].
234fn run_physics_schedule(world: &mut World, mut is_first_run: Local<IsFirstRun>) {
235    let _ = world.try_schedule_scope(PhysicsSchedule, |world, schedule| {
236        let is_paused = world.resource::<Time<Physics>>().is_paused();
237        let old_clock = world.resource::<Time>().as_generic();
238        let physics_clock = world.resource_mut::<Time<Physics>>();
239
240        // Get the scaled timestep delta time based on the timestep mode.
241        let timestep = old_clock
242            .delta()
243            .mul_f64(physics_clock.relative_speed_f64());
244
245        // Advance the physics clock by the timestep if not paused.
246        if !is_paused {
247            world.resource_mut::<Time<Physics>>().advance_by(timestep);
248
249            // Advance the substep clock already so that systems running
250            // before the substepping loop have the right delta.
251            let SubstepCount(substeps) = *world.resource::<SubstepCount>();
252            let sub_delta = timestep.div_f64(substeps as f64);
253            world.resource_mut::<Time<Substeps>>().advance_by(sub_delta);
254        }
255
256        // Set the generic `Time` resource to `Time<Physics>`.
257        *world.resource_mut::<Time>() = world.resource::<Time<Physics>>().as_generic();
258
259        // Advance the simulation.
260        if !world.resource::<Time>().delta().is_zero() {
261            trace!("running PhysicsSchedule");
262            schedule.run(world);
263        }
264
265        // If physics is paused, reset delta time to stop the simulation
266        // unless users manually advance `Time<Physics>`.
267        if is_paused {
268            world
269                .resource_mut::<Time<Physics>>()
270                .advance_by(Duration::ZERO);
271        }
272
273        // Set the generic `Time` resource back to the clock that was active before physics.
274        *world.resource_mut::<Time>() = old_clock;
275    });
276
277    is_first_run.0 = false;
278}
279
280fn update_last_physics_tick(
281    mut last_physics_tick: ResMut<LastPhysicsTick>,
282    system_change_tick: SystemChangeTick,
283) {
284    last_physics_tick.0 = system_change_tick.this_run();
285}