ferravex_physics/
material.rs

1//! Checked contact-material authoring and symmetric pair mixing.
2//!
3//! Pair rules use the higher-priority enum variant independently for friction
4//! and restitution. Defaults remain geometric friction, average restitution and
5//! average rolling resistance. Mixing describes contact coefficients; the solver
6//! separately decides when to apply friction, bounce and rolling resistance.
7
8/// Why a checked scalar combination failed.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum CombineError {
11    /// The first coefficient is negative or non-finite.
12    InvalidFirst,
13    /// The second coefficient is negative or non-finite.
14    InvalidSecond,
15    /// The result is too large to represent as a finite `f32`.
16    Overflow,
17}
18
19impl std::fmt::Display for CombineError {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        f.write_str(match self {
22            Self::InvalidFirst => "first coefficient must be finite and nonnegative",
23            Self::InvalidSecond => "second coefficient must be finite and nonnegative",
24            Self::Overflow => "combined coefficient exceeds finite f32 range",
25        })
26    }
27}
28
29impl std::error::Error for CombineError {}
30
31/// Material authoring failed before any collider was changed.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum MaterialError {
34    /// Static friction must be finite and in `0..=1000`.
35    InvalidStaticFriction,
36    /// Sliding friction must be finite and in `0..=1000`.
37    InvalidSlidingFriction,
38    /// Sliding friction must not exceed static friction.
39    SlidingExceedsStatic,
40    /// Rolling resistance must be finite and in `0..=10` meters.
41    InvalidRollingResistance,
42    /// Restitution must be finite and in `0..=1`.
43    InvalidRestitution,
44}
45
46impl std::fmt::Display for MaterialError {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.write_str(match self {
49            Self::InvalidStaticFriction => "static friction must be finite and in 0..=1000",
50            Self::InvalidSlidingFriction => "sliding friction must be finite and in 0..=1000",
51            Self::SlidingExceedsStatic => "sliding friction must not exceed static friction",
52            Self::InvalidRollingResistance => {
53                "rolling resistance must be finite and in 0..=10 meters"
54            }
55            Self::InvalidRestitution => "restitution must be finite and in 0..=1",
56        })
57    }
58}
59
60impl std::error::Error for MaterialError {}
61
62/// A coefficient mixing rule, in increasing priority order:
63/// `Average < Geometric < Minimum < Maximum < Multiply`.
64///
65/// A material pair selects `a_rule.max(b_rule)`, regardless of collider order.
66/// Friction and restitution select their rules independently. With one zero
67/// coefficient, `Geometric`, `Minimum` and `Multiply` yield zero; `Average`
68/// yields half the other coefficient and `Maximum` yields the other coefficient.
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
70pub enum CombineRule {
71    /// Arithmetic mean: `(a + b) / 2`.
72    Average,
73    /// Geometric mean: `sqrt(a * b)`. Default for friction.
74    #[default]
75    Geometric,
76    /// Smaller coefficient.
77    Minimum,
78    /// Larger coefficient.
79    Maximum,
80    /// Product; friction may exceed either authored coefficient.
81    Multiply,
82}
83impl CombineRule {
84    /// Apply this rule without validating the coefficients or selecting priority.
85    ///
86    /// Average and geometric mean avoid intermediate overflow/underflow for
87    /// finite inputs. Ordinary calculations retain their existing `f32` rounding;
88    /// only extreme intermediates use `f64`. Multiplication can overflow to
89    /// infinity or round tiny products to zero. NaN, infinity and negative inputs
90    /// follow floating-point arithmetic; use [`Self::try_combine`] to reject them.
91    pub fn combine(self, a: f32, b: f32) -> f32 {
92        match self {
93            Self::Average => {
94                let sum = a + b;
95                if sum.is_infinite() && a.is_finite() && b.is_finite() {
96                    ((f64::from(a) + f64::from(b)) * 0.5) as f32
97                } else {
98                    sum * 0.5
99                }
100            }
101            Self::Geometric => {
102                let product = a * b;
103                if (product.is_infinite() || product.abs() < f32::MIN_POSITIVE)
104                    && a.is_finite()
105                    && b.is_finite()
106                {
107                    (f64::from(a) * f64::from(b)).sqrt() as f32
108                } else {
109                    product.sqrt()
110                }
111            }
112            Self::Minimum => a.min(b),
113            Self::Maximum => a.max(b),
114            Self::Multiply => a * b,
115        }
116    }
117
118    /// Combine finite, nonnegative coefficients without clamping.
119    ///
120    /// This scalar helper does not enforce material authoring bounds or select
121    /// the higher-priority rule. Both inputs are checked, including a coefficient
122    /// that `Minimum`/`Maximum` would otherwise ignore. The first invalid input
123    /// wins. A non-finite result is an overflow error; underflow to zero in
124    /// `Multiply` is allowed. Signed zero is accepted.
125    ///
126    /// ```
127    /// use ferravex_physics::CombineRule;
128    ///
129    /// assert_eq!(CombineRule::Geometric.try_combine(0.0, 0.8).unwrap(), 0.0);
130    /// assert_eq!(CombineRule::Average.try_combine(f32::MAX, f32::MAX).unwrap(), f32::MAX);
131    /// assert!(CombineRule::Multiply.try_combine(f32::MAX, 2.0).is_err());
132    /// assert!(CombineRule::Minimum.try_combine(0.0, f32::NAN).is_err());
133    /// ```
134    pub fn try_combine(self, a: f32, b: f32) -> Result<f32, CombineError> {
135        if !a.is_finite() || a < 0.0 {
136            return Err(CombineError::InvalidFirst);
137        }
138        if !b.is_finite() || b < 0.0 {
139            return Err(CombineError::InvalidSecond);
140        }
141        let combined = self.combine(a, b);
142        if !combined.is_finite() {
143            return Err(CombineError::Overflow);
144        }
145        Ok(combined)
146    }
147}
148
149/// Authored collider coefficients, or effective coefficients from a material pair.
150///
151/// Struct literals remain supported. Use [`Self::validate`] before applying an
152/// authored value, or [`Self::try_new`] for default-rule authoring. Pair outputs
153/// may exceed the authored friction limit when using `Multiply`; see
154/// [`Self::try_combine`]. These operations allocate no storage.
155#[derive(Clone, Copy, Debug, PartialEq)]
156pub struct PhysicsMaterial {
157    /// Authored static friction in `0..=1000`, at least sliding friction.
158    pub static_friction: f32,
159    /// Authored sliding friction in `0..=1000`.
160    pub sliding_friction: f32,
161    /// Contact torque impulse limit = normal impulse * this length (meters).
162    /// Authored range is `0..=10`. Resists rolling and spin; zero retains the
163    /// historical behavior. Pairs always use the arithmetic mean.
164    pub rolling_resistance: f32,
165    /// Authored restitution in `0..=1`.
166    pub restitution: f32,
167    /// Rule shared by static and sliding friction; the pair's higher rule wins.
168    pub friction_rule: CombineRule,
169    /// Independent restitution rule; the pair's higher rule wins.
170    pub restitution_rule: CombineRule,
171}
172impl Default for PhysicsMaterial {
173    fn default() -> Self {
174        Self {
175            static_friction: 0.6,
176            sliding_friction: 0.6,
177            rolling_resistance: 0.,
178            restitution: 0.,
179            friction_rule: CombineRule::Geometric,
180            restitution_rule: CombineRule::Average,
181        }
182    }
183}
184impl PhysicsMaterial {
185    /// Author checked coefficients with the default mixing rules and no rolling
186    /// resistance. Invalid values are rejected, never clamped or reordered.
187    ///
188    /// ```
189    /// use ferravex_physics::PhysicsMaterial;
190    ///
191    /// let rubber = PhysicsMaterial::try_new(0.9, 0.7, 0.8).unwrap();
192    /// assert!(rubber.valid());
193    /// assert!(PhysicsMaterial::try_new(0.2, 0.7, 0.8).is_err());
194    /// ```
195    pub fn try_new(
196        static_friction: f32,
197        sliding_friction: f32,
198        restitution: f32,
199    ) -> Result<Self, MaterialError> {
200        let material = Self {
201            static_friction,
202            sliding_friction,
203            restitution,
204            ..Self::default()
205        };
206        material.validate()?;
207        Ok(material)
208    }
209
210    /// Validate authored coefficients without changing them.
211    ///
212    /// Reports the first error in this order: static friction range, sliding
213    /// friction range, sliding/static ordering, rolling resistance, restitution.
214    /// All bounds are inclusive; signed zero and positive subnormals are valid.
215    /// Every non-finite value is rejected. Mixing rules do not affect validity.
216    ///
217    /// ```
218    /// use ferravex_physics::{CombineRule, PhysicsMaterial};
219    ///
220    /// let material = PhysicsMaterial {
221    ///     rolling_resistance: 0.05,
222    ///     restitution_rule: CombineRule::Maximum,
223    ///     ..PhysicsMaterial::default()
224    /// };
225    /// assert!(material.validate().is_ok());
226    /// let invalid = PhysicsMaterial { restitution: 1.01, ..material };
227    /// assert!(invalid.validate().is_err());
228    /// ```
229    pub fn validate(self) -> Result<(), MaterialError> {
230        if !self.static_friction.is_finite() || !(0.0..=1000.0).contains(&self.static_friction) {
231            return Err(MaterialError::InvalidStaticFriction);
232        }
233        if !self.sliding_friction.is_finite() || !(0.0..=1000.0).contains(&self.sliding_friction) {
234            return Err(MaterialError::InvalidSlidingFriction);
235        }
236        if self.sliding_friction > self.static_friction {
237            return Err(MaterialError::SlidingExceedsStatic);
238        }
239        if !self.rolling_resistance.is_finite() || !(0.0..=10.0).contains(&self.rolling_resistance)
240        {
241            return Err(MaterialError::InvalidRollingResistance);
242        }
243        if !self.restitution.is_finite() || !(0.0..=1.0).contains(&self.restitution) {
244            return Err(MaterialError::InvalidRestitution);
245        }
246        Ok(())
247    }
248
249    /// Whether this material meets the authored bounds of [`Self::validate`].
250    pub fn valid(self) -> bool {
251        self.validate().is_ok()
252    }
253
254    /// Inspect the effective contact material using the solver's pair rules.
255    ///
256    /// Validates `self`, then `other`, as authored materials. For each of friction
257    /// and restitution, the higher-priority [`CombineRule`] wins. Rolling
258    /// resistance always uses the arithmetic mean. Inputs are unchanged.
259    ///
260    /// The result is finite and nonnegative, with static friction at least
261    /// sliding friction and restitution in `0..=1`. Friction is **not clamped**:
262    /// `Multiply` can yield up to `1_000_000`, preserving solver behavior. Such a
263    /// result is contact data and can fail [`Self::validate`] if reused as an
264    /// authored collider material (or as an input to this helper).
265    ///
266    /// Zero friction on either collider makes default geometric mixing zero.
267    /// `Maximum` can override that behavior; zero is not an unconditional opt-out
268    /// of friction. Rolling resistance is independent of friction coefficients.
269    ///
270    /// ```
271    /// use ferravex_physics::{CombineRule, PhysicsMaterial};
272    ///
273    /// let ice = PhysicsMaterial::try_new(0.0, 0.0, 0.0).unwrap();
274    /// let rubber = PhysicsMaterial::try_new(0.9, 0.7, 0.8).unwrap();
275    /// let contact = ice.try_combine(rubber).unwrap();
276    /// assert_eq!(contact.sliding_friction, 0.0);
277    /// assert_eq!(contact.restitution, 0.4);
278    /// assert_eq!(contact, rubber.try_combine(ice).unwrap());
279    /// let grip = PhysicsMaterial { friction_rule: CombineRule::Maximum, ..rubber };
280    /// assert_eq!(ice.try_combine(grip).unwrap().sliding_friction, 0.7);
281    /// ```
282    pub fn try_combine(self, other: Self) -> Result<Self, MaterialError> {
283        self.validate()?;
284        other.validate()?;
285        Ok(self.pair(other))
286    }
287    pub(crate) fn pair(self, other: Self) -> Self {
288        let f = self.friction_rule.max(other.friction_rule);
289        let r = self.restitution_rule.max(other.restitution_rule);
290        Self {
291            static_friction: f.combine(self.static_friction, other.static_friction),
292            sliding_friction: f.combine(self.sliding_friction, other.sliding_friction),
293            rolling_resistance: (self.rolling_resistance + other.rolling_resistance) * 0.5,
294            restitution: r.combine(self.restitution, other.restitution),
295            friction_rule: f,
296            restitution_rule: r,
297        }
298    }
299}
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    const RULES: [CombineRule; 5] = [
305        CombineRule::Average,
306        CombineRule::Geometric,
307        CombineRule::Minimum,
308        CombineRule::Maximum,
309        CombineRule::Multiply,
310    ];
311
312    #[test]
313    fn pairs_are_symmetric_and_defaults_preserve_rules() {
314        let a = PhysicsMaterial {
315            static_friction: 1.,
316            sliding_friction: 0.5,
317            restitution: 0.6,
318            ..Default::default()
319        };
320        let b = PhysicsMaterial {
321            friction_rule: CombineRule::Maximum,
322            restitution: 0.2,
323            ..Default::default()
324        };
325        assert_eq!(a.pair(b), b.pair(a));
326        assert_eq!(a.pair(b).static_friction, 1.);
327        assert!((a.pair(b).restitution - 0.4).abs() < 1e-6);
328        assert!(
329            !PhysicsMaterial {
330                static_friction: 0.1,
331                sliding_friction: 0.5,
332                ..a
333            }
334            .valid()
335        );
336    }
337
338    #[test]
339    fn checked_authoring_preserves_defaults_and_reports_each_field() {
340        assert_eq!(
341            PhysicsMaterial::try_new(0.6, 0.6, 0.0),
342            Ok(PhysicsMaterial::default())
343        );
344        assert_eq!(
345            PhysicsMaterial::try_new(0.2, 0.7, 0.8),
346            Err(MaterialError::SlidingExceedsStatic)
347        );
348        for bad in [
349            f32::NAN,
350            f32::INFINITY,
351            f32::NEG_INFINITY,
352            -f32::from_bits(1),
353            f32::from_bits(1000.0_f32.to_bits() + 1),
354            f32::MAX,
355        ] {
356            let static_error = PhysicsMaterial::try_new(bad, 0.0, 0.0);
357            assert_eq!(static_error, Err(MaterialError::InvalidStaticFriction));
358            let sliding_error = PhysicsMaterial::try_new(1000.0, bad, 0.0);
359            assert_eq!(sliding_error, Err(MaterialError::InvalidSlidingFriction));
360        }
361        for (max, expected) in [
362            (10.0_f32, MaterialError::InvalidRollingResistance),
363            (1.0, MaterialError::InvalidRestitution),
364        ] {
365            for bad in [
366                f32::NAN,
367                f32::INFINITY,
368                f32::NEG_INFINITY,
369                -f32::from_bits(1),
370                f32::from_bits(max.to_bits() + 1),
371                f32::MAX,
372            ] {
373                let mut material = PhysicsMaterial::default();
374                if expected == MaterialError::InvalidRollingResistance {
375                    material.rolling_resistance = bad;
376                } else {
377                    material.restitution = bad;
378                }
379                assert_eq!(material.validate(), Err(expected));
380                assert!(!material.valid());
381            }
382        }
383    }
384
385    #[test]
386    fn validation_accepts_endpoints_signed_zero_and_subnormals() {
387        let max = PhysicsMaterial {
388            static_friction: 1000.0,
389            sliding_friction: 1000.0,
390            rolling_resistance: 10.0,
391            restitution: 1.0,
392            ..Default::default()
393        };
394        assert_eq!(max.validate(), Ok(()));
395        for value in [0.0, -0.0, f32::from_bits(1), f32::MIN_POSITIVE] {
396            let material = PhysicsMaterial {
397                static_friction: value,
398                sliding_friction: value,
399                rolling_resistance: value,
400                restitution: value,
401                ..Default::default()
402            };
403            assert!(material.valid());
404            assert_eq!(material.validate(), Ok(()));
405            let authored = PhysicsMaterial::try_new(value, value, value).unwrap();
406            assert_eq!(authored.static_friction.to_bits(), value.to_bits());
407        }
408    }
409
410    #[test]
411    fn validation_reports_first_error_and_combining_checks_both_inputs() {
412        let invalid_first = PhysicsMaterial {
413            static_friction: -1.0,
414            restitution: f32::NAN,
415            ..Default::default()
416        };
417        let invalid_second = PhysicsMaterial {
418            rolling_resistance: f32::INFINITY,
419            ..Default::default()
420        };
421        let valid = PhysicsMaterial::default();
422        assert_eq!(
423            invalid_first.try_combine(invalid_second),
424            Err(MaterialError::InvalidStaticFriction)
425        );
426        assert_eq!(
427            valid.try_combine(invalid_second),
428            Err(MaterialError::InvalidRollingResistance)
429        );
430        assert_eq!(
431            invalid_second.try_combine(valid),
432            Err(MaterialError::InvalidRollingResistance)
433        );
434        assert_eq!(valid, PhysicsMaterial::default());
435    }
436
437    #[test]
438    fn pair_priority_is_symmetric_and_independent_for_each_coefficient() {
439        for (fi, friction_a) in RULES.into_iter().enumerate() {
440            for (fj, friction_b) in RULES.into_iter().enumerate() {
441                for (ri, restitution_a) in RULES.into_iter().enumerate() {
442                    for (rj, restitution_b) in RULES.into_iter().enumerate() {
443                        let a = PhysicsMaterial {
444                            static_friction: 4.0,
445                            sliding_friction: 1.0,
446                            rolling_resistance: 0.25,
447                            restitution: 0.25,
448                            friction_rule: friction_a,
449                            restitution_rule: restitution_a,
450                        };
451                        let b = PhysicsMaterial {
452                            static_friction: 1.0,
453                            sliding_friction: 0.25,
454                            rolling_resistance: 0.75,
455                            restitution: 1.0,
456                            friction_rule: friction_b,
457                            restitution_rule: restitution_b,
458                        };
459                        let contact = a.try_combine(b).unwrap();
460                        assert_eq!(contact, b.try_combine(a).unwrap());
461                        assert_eq!(contact, a.pair(b));
462                        assert_eq!(contact.friction_rule, RULES[fi.max(fj)]);
463                        assert_eq!(contact.restitution_rule, RULES[ri.max(rj)]);
464                        assert_eq!(contact.rolling_resistance, 0.5);
465                        assert!(contact.static_friction >= contact.sliding_friction);
466                        assert!((0.0..=1.0).contains(&contact.restitution));
467                    }
468                }
469            }
470        }
471    }
472
473    #[test]
474    fn zero_friction_obeys_selected_rule_and_does_not_disable_rolling() {
475        for (rule, expected) in RULES.into_iter().zip([0.5, 0.0, 0.0, 1.0, 0.0]) {
476            let zero = PhysicsMaterial {
477                static_friction: 0.0,
478                sliding_friction: 0.0,
479                restitution: 0.0,
480                friction_rule: rule,
481                restitution_rule: rule,
482                ..Default::default()
483            };
484            let other = PhysicsMaterial {
485                static_friction: 1.0,
486                sliding_friction: 1.0,
487                rolling_resistance: 1.0,
488                restitution: 1.0,
489                ..zero
490            };
491            let contact = zero.try_combine(other).unwrap();
492            assert_eq!(contact.static_friction, expected);
493            assert_eq!(contact.sliding_friction, expected);
494            assert_eq!(contact.restitution, expected);
495            assert_eq!(contact.rolling_resistance, 0.5);
496        }
497        let ice = PhysicsMaterial::try_new(0.0, 0.0, 0.0).unwrap();
498        let defaults = ice.try_combine(PhysicsMaterial::default()).unwrap();
499        assert_eq!(defaults.static_friction, 0.0);
500        assert_eq!(defaults.sliding_friction, 0.0);
501    }
502
503    #[test]
504    fn multiplied_contact_friction_preserves_unclamped_solver_range() {
505        let authored = PhysicsMaterial {
506            static_friction: 1000.0,
507            sliding_friction: 500.0,
508            rolling_resistance: 10.0,
509            restitution: 1.0,
510            friction_rule: CombineRule::Multiply,
511            restitution_rule: CombineRule::Multiply,
512        };
513        let contact = authored.try_combine(authored).unwrap();
514        assert_eq!(contact.static_friction, 1_000_000.0);
515        assert_eq!(contact.sliding_friction, 250_000.0);
516        assert_eq!(contact.restitution, 1.0);
517        assert_eq!(contact.rolling_resistance, 10.0);
518        assert_eq!(contact, authored.pair(authored));
519        assert_eq!(
520            contact.validate(),
521            Err(MaterialError::InvalidStaticFriction)
522        );
523    }
524
525    #[test]
526    fn checked_scalar_rules_reject_invalid_inputs_even_when_not_selected() {
527        for rule in RULES {
528            for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] {
529                assert_eq!(rule.try_combine(bad, 0.0), Err(CombineError::InvalidFirst));
530                assert_eq!(rule.try_combine(0.0, bad), Err(CombineError::InvalidSecond));
531                assert_eq!(rule.try_combine(bad, bad), Err(CombineError::InvalidFirst));
532            }
533            assert_eq!(rule.try_combine(-0.0, 0.0), Ok(0.0));
534        }
535    }
536
537    #[test]
538    fn scalar_rules_have_documented_results_and_preserve_ordinary_rounding() {
539        for (rule, expected) in RULES.into_iter().zip([5.0, 4.0, 2.0, 8.0, 16.0]) {
540            assert_eq!(rule.try_combine(2.0, 8.0), Ok(expected));
541        }
542        for a in [0.0_f32, 0.1, 0.2, 0.5, 0.6, 1.0, 4.0, 1000.0] {
543            for b in [0.0_f32, 0.1, 0.2, 0.5, 0.6, 1.0, 4.0, 1000.0] {
544                let legacy = [(a + b) * 0.5, (a * b).sqrt(), a.min(b), a.max(b), a * b];
545                for (rule, expected) in RULES.into_iter().zip(legacy) {
546                    assert_eq!(rule.combine(a, b).to_bits(), expected.to_bits());
547                }
548            }
549        }
550    }
551
552    #[test]
553    fn extreme_means_remain_finite_and_geometric_mean_does_not_underflow() {
554        for rule in [CombineRule::Average, CombineRule::Geometric] {
555            assert_eq!(rule.try_combine(f32::MAX, f32::MAX), Ok(f32::MAX));
556        }
557        for value in [f32::from_bits(1), f32::MIN_POSITIVE, 1e-20] {
558            assert_eq!(CombineRule::Geometric.try_combine(value, value), Ok(value));
559            let material = PhysicsMaterial::try_new(value, value, 0.0).unwrap();
560            assert_eq!(
561                material.try_combine(material).unwrap().static_friction,
562                value
563            );
564        }
565        let small = f32::from_bits(1);
566        let expected = (f64::from(small) * f64::from(f32::MAX)).sqrt() as f32;
567        let actual = CombineRule::Geometric.try_combine(small, f32::MAX).unwrap();
568        assert!((actual - expected).abs() <= expected * f32::EPSILON);
569        assert_eq!(
570            CombineRule::Multiply.try_combine(f32::MAX, 2.0),
571            Err(CombineError::Overflow)
572        );
573        assert_eq!(CombineRule::Multiply.try_combine(small, small), Ok(0.0));
574    }
575
576    #[test]
577    fn error_messages_identify_the_constraint() {
578        let errors: [(&dyn std::error::Error, &str); 3] = [
579            (&MaterialError::InvalidRestitution, "0..=1"),
580            (&MaterialError::SlidingExceedsStatic, "static friction"),
581            (&CombineError::InvalidSecond, "second coefficient"),
582        ];
583        for (error, constraint) in errors {
584            assert!(error.to_string().contains(constraint));
585        }
586    }
587}