avian3d/dynamics/solver/schedule.rs
1//! Sets up the default scheduling, system set configuration, and time resources
2//! for the physics solver and substepping loop.
3//!
4//! See [`SolverSchedulePlugin`].
5
6use crate::prelude::*;
7use bevy::{
8 ecs::schedule::{LogLevel, ScheduleBuildSettings, ScheduleLabel, SingleThreadedExecutor},
9 prelude::*,
10};
11use dynamics::integrator::IntegrationSystems;
12
13/// Sets up the default scheduling, system set configuration, and time resources for the physics solver.
14#[derive(Debug, Default)]
15pub struct SolverSchedulePlugin;
16
17impl Plugin for SolverSchedulePlugin {
18 fn build(&self, app: &mut App) {
19 // Register types with generics.
20 app.register_type::<Time<Substeps>>();
21
22 // Initialize resources.
23 app.insert_resource(Time::new_with(Substeps))
24 .init_resource::<SubstepCount>();
25
26 // Get the `PhysicsSchedule`, and panic if it doesn't exist.
27 let physics = app
28 .get_schedule_mut(PhysicsSchedule)
29 .expect("add PhysicsSchedule first");
30
31 // See `SolverSystems` for what each system set is responsible for.
32 physics.configure_sets(
33 (
34 SolverSystems::PrepareSolverBodies,
35 SolverSystems::PrepareJoints,
36 SolverSystems::PrepareContactConstraints,
37 SolverSystems::PreSubstep,
38 SolverSystems::Substep,
39 SolverSystems::PostSubstep,
40 SolverSystems::Restitution,
41 SolverSystems::ContinuousCollision,
42 SolverSystems::Finalize,
43 SolverSystems::StoreContactImpulses,
44 )
45 .chain()
46 .in_set(PhysicsStepSystems::Solver),
47 );
48
49 // Run the substepping loop.
50 physics.add_systems(run_substep_schedule.in_set(SolverSystems::Substep));
51
52 // Set up the substep schedule, the schedule that runs systems in the inner substepping loop.
53 app.edit_schedule(SubstepSchedule, |schedule| {
54 schedule
55 .set_executor(SingleThreadedExecutor::new())
56 .set_build_settings(ScheduleBuildSettings {
57 ambiguity_detection: LogLevel::Error,
58 ..default()
59 })
60 .configure_sets(
61 (
62 IntegrationSystems::Velocity,
63 SubstepSolverSystems::WarmStart,
64 SubstepSolverSystems::SolveConstraints,
65 IntegrationSystems::Position,
66 SubstepSolverSystems::Relax,
67 SubstepSolverSystems::Damping,
68 )
69 .chain(),
70 );
71 });
72 }
73}
74
75/// The substepping schedule that runs in [`SolverSystems::Substep`].
76/// The number of substeps per physics step is configured through the [`SubstepCount`] resource.
77#[derive(Debug, Hash, PartialEq, Eq, Clone, ScheduleLabel)]
78pub struct SubstepSchedule;
79
80/// System sets for the constraint solver.
81///
82/// # Steps
83///
84/// Below is the core solver loop.
85///
86/// 1. Prepare solver bodies ([`SolverSystems::PrepareSolverBodies`])
87/// 2. Prepare joints ([`SolverSystems::PrepareJoints`])
88/// 3. Prepare contact constraints ([`SolverSystems::PrepareContactConstraints`])
89/// 4. Substepping loop (runs the [`SubstepSchedule`] [`SubstepCount`] times; see [`SolverSystems::Substep`])
90/// 5. Apply restitution ([`SolverSystems::Restitution`])
91/// 6. Perform Continuous Collision Detection (CCD) for fast dynamic bodies ([`SolverSystems::ContinuousCollision`])
92/// 7. Write back solver body data to rigid bodies. ([`SolverSystems::Finalize`])
93/// 8. Store contact impulses for next frame's warm starting ([`SolverSystems::StoreContactImpulses`])
94#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
95pub enum SolverSystems {
96 /// Prepares [solver bodies] for the substepping loop.
97 ///
98 /// [solver bodies]: crate::dynamics::solver::solver_body::SolverBody
99 PrepareSolverBodies,
100 /// Prepares joint constraints for the substepping loop.
101 PrepareJoints,
102 /// Prepares contact constraints for the substepping loop.
103 PrepareContactConstraints,
104 /// A system set for systems running just before the substepping loop.
105 PreSubstep,
106 /// A system set for the substepping loop.
107 Substep,
108 /// A system set for systems running just after the substepping loop.
109 PostSubstep,
110 /// Applies [restitution](Restitution) for bodies after solving overlap.
111 Restitution,
112 /// Performs [Continuous Collision Detection (CCD)](dynamics::ccd) for fast dynamic bodies.
113 ContinuousCollision,
114 /// Writes back solver body data to rigid bodies.
115 Finalize,
116 /// Copies contact impulses from [`ContactConstraints`] to the contacts in the [`ContactGraph`].
117 /// They will be used for [warm starting](SubstepSolverSystems::WarmStart) the next frame or substep.
118 ///
119 /// [`ContactConstraints`]: super::ContactConstraints
120 StoreContactImpulses,
121}
122
123/// A deprecated alias for [`SolverSystems`].
124#[deprecated(since = "0.4.0", note = "Renamed to `SolverSystems`")]
125pub type SolverSet = SolverSystems;
126
127/// System sets for the substepped part of the constraint solver.
128///
129/// # Steps
130///
131/// 1. Integrate velocity ([`IntegrationSystems::Velocity`])
132/// 2. Warm start ([`SubstepSolverSystems::WarmStart`])
133/// 3. Solve constraints with bias ([`SubstepSolverSystems::SolveConstraints`])
134/// 4. Integrate positions ([`IntegrationSystems::Position`])
135/// 5. Solve constraints without bias to relax velocities ([`SubstepSolverSystems::Relax`])
136/// 6. Apply velocity-based constraint damping ([`SubstepSolverSystems::Damping`])
137#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
138pub enum SubstepSolverSystems {
139 /// Warm starts the solver by applying the impulses from the previous frame or substep.
140 ///
141 /// This significantly improves convergence, but by itself can lead to overshooting.
142 /// Overshooting is reduced by [relaxing](SubstepSolverSystems::Relax) the biased velocities
143 /// by running the solver a second time *without* bias.
144 WarmStart,
145 /// Solves velocity constraints using a position bias that boosts the response
146 /// to account for the constraint error.
147 SolveConstraints,
148 /// Solves velocity constraints without a position bias to relax the biased velocities
149 /// and impulses. This reduces overshooting caused by [warm starting](SubstepSolverSystems::WarmStart).
150 Relax,
151 /// Applies velocity-based constraint damping, such as [`JointDamping`].
152 Damping,
153}
154
155/// A deprecated alias for [`SubstepSolverSystems`].
156#[deprecated(since = "0.4.0", note = "Renamed to `SubstepSolverSystems`")]
157pub type SubstepSolverSet = SubstepSolverSystems;
158
159/// The number of substeps used in the simulation.
160///
161/// A higher number of substeps reduces the value of [`Time`],
162/// which results in a more accurate simulation, but also reduces performance. The default
163/// substep count is currently 6.
164///
165/// If you use a very high substep count and encounter stability issues, consider enabling the `f64`
166/// feature as shown in the [getting started guide](crate#getting-started) to avoid floating point
167/// precision problems.
168///
169/// # Example
170///
171/// You can change the number of substeps by inserting the [`SubstepCount`] resource:
172///
173/// ```no_run
174#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
175#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
176/// use bevy::prelude::*;
177///
178/// fn main() {
179/// App::new()
180/// .add_plugins((DefaultPlugins, PhysicsPlugins::default()))
181/// .insert_resource(SubstepCount(12))
182/// .run();
183/// }
184/// ```
185#[derive(Debug, Reflect, Resource, Clone, Copy, PartialEq, Eq)]
186#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
187#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
188#[reflect(Debug, Resource, PartialEq)]
189pub struct SubstepCount(pub u32);
190
191impl Default for SubstepCount {
192 fn default() -> Self {
193 Self(6)
194 }
195}
196
197/// Runs the [`SubstepSchedule`].
198fn run_substep_schedule(world: &mut World) {
199 let delta = world.resource::<Time<Physics>>().delta();
200 let SubstepCount(substeps) = *world.resource::<SubstepCount>();
201 let sub_delta = delta.div_f64(substeps as f64);
202
203 let mut sub_delta_time = world.resource_mut::<Time<Substeps>>();
204 sub_delta_time.advance_by(sub_delta);
205
206 let _ = world.try_schedule_scope(SubstepSchedule, |world, schedule| {
207 for i in 0..substeps {
208 trace!("running SubstepSchedule: {i}");
209 *world.resource_mut::<Time>() = world.resource::<Time<Substeps>>().as_generic();
210 schedule.run(world);
211 }
212 });
213
214 // Set generic `Time` resource back to `Time<Physics>`.
215 // Later, it's set back to the default clock after the `PhysicsSchedule`.
216 *world.resource_mut::<Time>() = world.resource::<Time<Physics>>().as_generic();
217}