rapier2d_f64/dynamics/integration_parameters.rs
1#[cfg(all(doc, feature = "alloc"))]
2use super::RigidBodyActivation;
3use crate::math::Real;
4use simba::simd::SimdRealField;
5
6// NOTE: the 2x2 block solver (`block-solver` feature) runs in BOTH passes and solves the COMPLIANT
7// LCP `(K + C, b)`, `C = diag((1/ms_i - 1) k_ii)` — the coupled soft step — so it shares
8// the sequential sweep's fixed points; a rigid-LCP-then-cfm-scale variant left piles micro-jiggling.
9
10/// Friction models used for all contact constraints between two rigid-bodies.
11///
12/// This selection does not apply to multibodies that always rely on the [`FrictionModel::Coulomb`].
13#[cfg(feature = "dim3")]
14#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
15#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
16pub enum FrictionModel {
17 /// A simplified friction model significantly faster to solve than [`Self::Coulomb`]
18 /// but less accurate.
19 ///
20 /// Instead of solving one Coulomb friction constraint per contact in a contact manifold,
21 /// this approximation only solves one Coulomb friction constraint per group of 4 contacts
22 /// in a contact manifold, plus one "twist" constraint. The "twist" constraint is purely
23 /// rotational and aims to eliminate angular movement in the manifold’s tangent plane.
24 #[default]
25 Simplified,
26 /// The coulomb friction model.
27 ///
28 /// This results in one Coulomb friction constraint per contact point.
29 Coulomb,
30}
31
32#[derive(Copy, Clone, Debug, PartialEq)]
33#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
34// TODO: we should be able to combine this with MotorModel.
35/// Coefficients for a spring, typically used for configuring constraint softness for contacts and
36/// joints.
37pub struct SpringCoefficients<N> {
38 /// Sets the natural frequency (Hz) of the spring-like constraint.
39 ///
40 /// Higher values make the constraint stiffer and resolve constraint violations more quickly.
41 pub natural_frequency: N,
42 /// Sets the damping ratio for the spring-like constraint.
43 ///
44 /// Larger values make the joint more compliant (allowing more drift before stabilization).
45 pub damping_ratio: N,
46}
47
48impl<N: SimdRealField<Element = Real> + Copy> SpringCoefficients<N> {
49 /// Initializes spring coefficients from the spring natural frequency and damping ratio.
50 pub fn new(natural_frequency: N, damping_ratio: N) -> Self {
51 Self {
52 natural_frequency,
53 damping_ratio,
54 }
55 }
56
57 /// Default softness coefficients for contacts (30 Hz, ζ = 10).
58 /// The high ζ is load-bearing for large piles/stacks: softer contacts settle
59 /// deeper under load, and the extra penetration keeps them wedging and creeping instead of resting.
60 pub fn contact_defaults() -> Self {
61 Self {
62 natural_frequency: N::splat(30.0),
63 damping_ratio: N::splat(10.0),
64 }
65 }
66
67 /// Default softness coefficients for contacts touching a fixed body: twice the natural
68 /// frequency of [`Self::contact_defaults`], holding piled/pushed
69 /// bodies more firmly against walls and floors so they are less likely to squeeze through.
70 pub fn contact_static_defaults() -> Self {
71 Self {
72 natural_frequency: N::splat(60.0),
73 damping_ratio: N::splat(10.0),
74 }
75 }
76
77 /// Default softness coefficients for joints.
78 pub fn joint_defaults() -> Self {
79 Self {
80 natural_frequency: N::splat(1.0e6),
81 damping_ratio: N::splat(1.0),
82 }
83 }
84
85 /// The contact’s spring angular frequency for constraints regularization.
86 pub fn angular_frequency(&self) -> N {
87 self.natural_frequency * N::simd_two_pi()
88 }
89
90 /// The [`Self::erp`] coefficient, multiplied by the inverse timestep length.
91 pub fn erp_inv_dt(&self, dt: N) -> N {
92 let ang_freq = self.angular_frequency();
93 ang_freq / (dt * ang_freq + N::splat(2.0) * self.damping_ratio)
94 }
95
96 /// The effective Error Reduction Parameter applied for calculating regularization forces.
97 ///
98 /// This parameter is computed automatically from [`Self::natural_frequency`],
99 /// [`Self::damping_ratio`] and the substep length.
100 pub fn erp(&self, dt: N) -> N {
101 dt * self.erp_inv_dt(dt)
102 }
103
104 /// Compute CFM assuming a critically damped spring multiplied by the damping ratio.
105 ///
106 /// This coefficient softens the impulse applied at each solver iteration.
107 pub fn cfm_coeff(&self, dt: N) -> N {
108 let one = N::one();
109 let erp = self.erp(dt);
110 let erp_is_not_zero = erp.simd_ne(N::zero());
111 let inv_erp_minus_one = one / erp - one;
112
113 // let stiffness = 4.0 * damping_ratio * damping_ratio * projected_mass
114 // / (dt * dt * inv_erp_minus_one * inv_erp_minus_one);
115 // let damping = 4.0 * damping_ratio * damping_ratio * projected_mass
116 // / (dt * inv_erp_minus_one);
117 // let cfm = 1.0 / (dt * dt * stiffness + dt * damping);
118 // NOTE: This simplifies to cfm = cfm_coeff / projected_mass:
119 let result = inv_erp_minus_one * inv_erp_minus_one
120 / ((one + inv_erp_minus_one) * N::splat(4.0) * self.damping_ratio * self.damping_ratio);
121 result.select(erp_is_not_zero, N::zero())
122 }
123
124 /// The CFM factor to be used in the constraint resolution.
125 ///
126 /// This parameter is computed automatically from [`Self::natural_frequency`],
127 /// [`Self::damping_ratio`] and the substep length.
128 pub fn cfm_factor(&self, dt: N) -> N {
129 let one = N::one();
130 let cfm_coeff = self.cfm_coeff(dt);
131
132 // We use this coefficient inside the impulse resolution.
133 // Surprisingly, several simplifications happen there.
134 // Let `m` the projected mass of the constraint.
135 // Let `m’` the projected mass that includes CFM: `m’ = 1 / (1 / m + cfm_coeff / m) = m / (1 + cfm_coeff)`
136 // We have:
137 // new_impulse = old_impulse - m’ (delta_vel - cfm * old_impulse)
138 // = old_impulse - m / (1 + cfm_coeff) * (delta_vel - cfm_coeff / m * old_impulse)
139 // = old_impulse * (1 - cfm_coeff / (1 + cfm_coeff)) - m / (1 + cfm_coeff) * delta_vel
140 // = old_impulse / (1 + cfm_coeff) - m * delta_vel / (1 + cfm_coeff)
141 // = 1 / (1 + cfm_coeff) * (old_impulse - m * delta_vel)
142 // So, setting cfm_factor = 1 / (1 + cfm_coeff).
143 // We obtain:
144 // new_impulse = cfm_factor * (old_impulse - m * delta_vel)
145 //
146 // The value returned by this function is this cfm_factor that can be used directly
147 // in the constraint solver.
148 one / (one + cfm_coeff)
149 }
150}
151
152/// Configuration parameters that control the physics simulation quality and behavior.
153///
154/// These parameters affect how the physics engine advances time, resolves collisions, and
155/// maintains stability. The defaults work well for most games, but you may want to adjust
156/// them based on your specific needs.
157///
158/// # Key parameters for beginners
159///
160/// - **`dt`**: Timestep duration (default: 1/60 second). Most games run physics at 60Hz.
161/// - **`num_solver_iterations`**: More iterations = more accurate but slower (default: 4)
162/// - **`length_unit`**: Scale factor if your world units aren't meters (e.g., 100 for pixel-based games)
163///
164/// # Example
165///
166/// ```
167/// # use rapier3d::prelude::*;
168/// // Standard 60 FPS physics with default settings
169/// let mut integration_params = IntegrationParameters::default();
170///
171/// // For a more accurate (but slower) simulation:
172/// integration_params.num_solver_iterations = 8;
173///
174/// // For pixel-based 2D games where 100 pixels = 1 meter:
175/// integration_params.length_unit = 100.0;
176/// ```
177///
178/// Most other parameters are advanced settings for fine-tuning stability and performance.
179#[derive(Copy, Clone, Debug, PartialEq)]
180#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
181pub struct IntegrationParameters {
182 /// The timestep length - how much simulated time passes per physics step (default: `1.0 / 60.0`).
183 ///
184 /// Set this to `1.0 / your_target_fps`. For example:
185 /// - 60 FPS: `1.0 / 60.0` ≈ 0.0167 seconds
186 /// - 120 FPS: `1.0 / 120.0` ≈ 0.0083 seconds
187 ///
188 /// Smaller timesteps are more accurate but require more CPU time per second of simulated time.
189 pub dt: Real,
190 /// Minimum timestep size when using CCD with multiple substeps (default: `1.0 / 60.0 / 100.0`).
191 ///
192 /// When CCD with multiple substeps is enabled, the timestep is subdivided
193 /// into smaller pieces. This timestep subdivision won't generate timestep
194 /// lengths smaller than `min_ccd_dt`.
195 ///
196 /// Setting this to a large value will reduce the opportunity to performing
197 /// CCD substepping, resulting in potentially more time dropped by the
198 /// motion-clamping mechanism. Setting this to an very small value may lead
199 /// to numerical instabilities.
200 pub min_ccd_dt: Real,
201
202 /// Softness coefficients for contact constraints.
203 pub contact_softness: SpringCoefficients<Real>,
204
205 /// Softness coefficients for contact constraints where one side is a fixed body.
206 ///
207 /// Stiffer than [`Self::contact_softness`] by default so bodies are
208 /// held firmly against static walls/floors; set equal to [`Self::contact_softness`] to disable.
209 pub static_contact_softness: SpringCoefficients<Real>,
210
211 /// The coefficient in `[0, 1]` applied to warmstart impulses, i.e., impulses that are used as the
212 /// initial solution (instead of 0) at the next simulation step.
213 ///
214 /// This should generally be set to 1.
215 ///
216 /// (default `1.0`).
217 pub warmstart_coefficient: Real,
218
219 /// The scale factor for your world if you're not using meters (default: `1.0`).
220 ///
221 /// Rapier is tuned for human-scale objects measured in meters. If your game uses different
222 /// units, set this to how many of your units equal 1 meter in the real world.
223 ///
224 /// **Examples:**
225 /// - Your game uses meters: `length_unit = 1.0` (default)
226 /// - Your game uses centimeters: `length_unit = 100.0` (100 cm = 1 m)
227 /// - Pixel-based 2D game where typical objects are 100 pixels tall: `length_unit = 100.0`
228 /// - Your game uses feet: `length_unit = 3.28` (approximately)
229 ///
230 /// This automatically scales various internal tolerances and thresholds to work correctly
231 /// with your chosen units.
232 pub length_unit: Real,
233
234 /// Geometric slop distance (default: `0.005`), e.g. the standoff kept
235 /// by the CCD clamp. NOT a deadzone on the position-correction bias: penetrations are corrected
236 /// all the way to zero; a deadzone would keep loaded piles wedging and creeping.
237 ///
238 /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
239 pub normalized_allowed_linear_error: Real,
240 /// Maximum speed at which contact penetration is pushed out by the biased solve
241 /// (default: `3.0`).
242 ///
243 /// Capping this recovery velocity keeps deep penetrations from being resolved explosively.
244 /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
245 pub normalized_max_corrective_velocity: Real,
246 /// The maximal distance separating two objects that will generate predictive contacts (default: `0.002m`).
247 ///
248 /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
249 pub normalized_prediction_distance: Real,
250 /// Maximum linear velocity a body may have after each solver substep (default: `400.0` m/s).
251 /// Bounding per-step travel keeps CCD and speculative contacts
252 /// reliable (a body cannot be flung or crushed to an arbitrary speed); set to `Real::MAX` to disable.
253 ///
254 /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
255 pub normalized_max_linear_velocity: Real,
256 /// The number of solver iterations run by the constraints solver for calculating forces (default: `4`).
257 ///
258 /// Higher values produce more accurate and stable simulations at the cost of performance.
259 /// - `4` (default): Good balance for most games
260 /// - `8-12`: Use for demanding scenarios (stacks of objects, complex machinery)
261 /// - `1-2`: Use if performance is critical and accuracy can be sacrificed
262 pub num_solver_iterations: usize,
263 /// Number of internal Project Gauss Seidel (PGS) iterations run at each solver iteration (default: `1`).
264 pub num_internal_pgs_iterations: usize,
265 /// The number of stabilization iterations run at each solver iterations (default: `1`).
266 pub num_internal_stabilization_iterations: usize,
267 /// Maximum number of CCD substeps performed by the solver (default: `1`).
268 ///
269 /// Also the global CCD on/off switch: `0` disables **all** CCD for the world (including the
270 /// automatic CCD of fast dynamic bodies vs fixed colliders).
271 pub max_ccd_substeps: usize,
272 /// If enabled, contact manifolds of a collider pair sharing (nearly) the same normal are merged
273 /// into one "cluster" manifold before constraint generation (default: `true`, 3D only), so at
274 /// most 4 contact points are solved per contact plane — a large solver win on composite shapes
275 /// (meshes, heightfields, compounds, voxels) that emit one manifold per subshape. When clustering
276 /// applies, read solver contacts/impulses from [`crate::geometry::ContactPair::solver_clusters`],
277 /// not [`crate::geometry::ContactPair::manifolds`].
278 pub contact_clustering: bool,
279 /// If enabled, a contact pair whose relative pose moved less than [`Self::contact_recycle_distance`]
280 /// since its last full narrow-phase update skips contact determination and keeps its existing points
281 /// (default: `true`) — a large speed-up for quasi-static scenes. Trade-offs:
282 /// contact features and user-facing contact data (`dist`, is-new bits) may be stale by up to that
283 /// distance, and per-step joint-based contact filtering is skipped until the pair moves.
284 /// [`crate::pipeline::ActiveHooks`] pairs are never recycled.
285 pub contact_recycling: bool,
286 /// Maximum relative-pose drift (translation plus rotation-arc) below which a contact pair may
287 /// be recycled instead of fully updated (default: `0.05`, i.e. ten times the linear slop,
288 /// multiplied by [`Self::length_unit`]). Only used when [`Self::contact_recycling`] is enabled.
289 pub normalized_contact_recycle_distance: Real,
290 /// If `false`, friction is only solved during the unbiased (relax) pass of each substep instead
291 /// of both passes (default: `false`, the "no friction when applying bias" rule).
292 /// This makes contact kernels much cheaper and is load-bearing for tall stacks: friction
293 /// reacting to bias velocities pumps their coherent lean mode until they topple. If
294 /// [`Self::num_internal_stabilization_iterations`] is zero there is no unbiased pass and this flag is ignored.
295 pub friction_in_bias_pass: bool,
296 /// If enabled, impulse-joint constraints are warm-started like contacts: impulses accumulated
297 /// by the previous step are re-applied (scaled by [`Self::warmstart_coefficient`]) at the start
298 /// of each substep instead of restarting from zero (default: `false`). This
299 /// noticeably improves convergence of stiff joint assemblies. Multibody joints are unaffected.
300 pub warmstart_joints: bool,
301 /// The type of friction constraints used in the simulation.
302 #[cfg(feature = "dim3")]
303 pub friction_model: FrictionModel,
304}
305
306impl IntegrationParameters {
307 /// The inverse of the time-stepping length, i.e. the steps per seconds (Hz).
308 ///
309 /// This is zero if `self.dt` is zero.
310 #[inline]
311 pub fn inv_dt(&self) -> Real {
312 if self.dt == 0.0 { 0.0 } else { 1.0 / self.dt }
313 }
314
315 /// Sets the time-stepping length.
316 #[inline]
317 #[deprecated = "You can just set the `IntegrationParams::dt` value directly"]
318 pub fn set_dt(&mut self, dt: Real) {
319 assert!(dt >= 0.0, "The time-stepping length cannot be negative.");
320 self.dt = dt;
321 }
322
323 /// Sets the inverse time-stepping length (i.e. the frequency).
324 ///
325 /// This automatically recompute `self.dt`.
326 #[inline]
327 pub fn set_inv_dt(&mut self, inv_dt: Real) {
328 if inv_dt == 0.0 {
329 self.dt = 0.0
330 } else {
331 self.dt = 1.0 / inv_dt
332 }
333 }
334
335 /// Amount of penetration the engine won't attempt to correct (default: `0.001` multiplied by
336 /// [`Self::length_unit`]).
337 pub fn allowed_linear_error(&self) -> Real {
338 self.normalized_allowed_linear_error * self.length_unit
339 }
340
341 /// Maximum amount of penetration the solver will attempt to resolve in one timestep.
342 ///
343 /// This is equal to [`Self::normalized_max_corrective_velocity`] multiplied by
344 /// [`Self::length_unit`].
345 pub fn max_corrective_velocity(&self) -> Real {
346 if self.normalized_max_corrective_velocity != Real::MAX {
347 self.normalized_max_corrective_velocity * self.length_unit
348 } else {
349 Real::MAX
350 }
351 }
352
353 /// The maximal distance separating two objects that will generate predictive contacts
354 /// (default: `0.002m` multiped by [`Self::length_unit`]).
355 pub fn prediction_distance(&self) -> Real {
356 self.normalized_prediction_distance * self.length_unit
357 }
358
359 /// Maximum linear velocity a body may have after each solver substep.
360 ///
361 /// This is equal to [`Self::normalized_max_linear_velocity`] multiplied by
362 /// [`Self::length_unit`], or `Real::MAX` when the linear speed cap is disabled.
363 pub fn max_linear_velocity(&self) -> Real {
364 if self.normalized_max_linear_velocity != Real::MAX {
365 self.normalized_max_linear_velocity * self.length_unit
366 } else {
367 Real::MAX
368 }
369 }
370
371 /// Maximum relative-pose drift below which a contact pair can be recycled instead of fully
372 /// updated: [`Self::normalized_contact_recycle_distance`] multiplied by [`Self::length_unit`].
373 /// Only used when [`Self::contact_recycling`] is enabled.
374 pub fn contact_recycle_distance(&self) -> Real {
375 self.normalized_contact_recycle_distance * self.length_unit
376 }
377}
378
379impl Default for IntegrationParameters {
380 fn default() -> Self {
381 Self {
382 dt: 1.0 / 60.0,
383 min_ccd_dt: 1.0 / 60.0 / 100.0,
384 contact_softness: SpringCoefficients::contact_defaults(),
385 static_contact_softness: SpringCoefficients::contact_static_defaults(),
386 warmstart_coefficient: 1.0,
387 num_internal_pgs_iterations: 1,
388 num_internal_stabilization_iterations: 1,
389 num_solver_iterations: 4,
390 normalized_allowed_linear_error: 0.005,
391 normalized_max_corrective_velocity: 3.0,
392 // Four times the linear slop. A larger speculative
393 // margin generates contacts earlier, which (together with oriented/one-sided static
394 // geometry) keeps fast/piled bodies from tunneling through thin walls.
395 normalized_prediction_distance: 0.02,
396 normalized_max_linear_velocity: 400.0,
397 max_ccd_substeps: 1,
398 contact_clustering: true,
399 contact_recycling: true,
400 normalized_contact_recycle_distance: 0.05,
401 friction_in_bias_pass: false,
402 warmstart_joints: false,
403 length_unit: 1.0,
404 #[cfg(feature = "dim3")]
405 friction_model: FrictionModel::default(),
406 }
407 }
408}