bevy_math/
common_traits.rs

1//! This module contains abstract mathematical traits shared by types used in `bevy_math`.
2
3use crate::{ops, Dir2, Dir3, Dir3A, Quat, Rot2, Vec2, Vec3, Vec3A, Vec4};
4use core::{
5    fmt::Debug,
6    ops::{Add, Div, Mul, Neg, Sub},
7};
8
9/// A type that supports the mathematical operations of a real vector space, irrespective of dimension.
10/// In particular, this means that the implementing type supports:
11/// - Scalar multiplication and division on the right by elements of `f32`
12/// - Negation
13/// - Addition and subtraction
14/// - Zero
15///
16/// Within the limitations of floating point arithmetic, all the following are required to hold:
17/// - (Associativity of addition) For all `u, v, w: Self`, `(u + v) + w == u + (v + w)`.
18/// - (Commutativity of addition) For all `u, v: Self`, `u + v == v + u`.
19/// - (Additive identity) For all `v: Self`, `v + Self::ZERO == v`.
20/// - (Additive inverse) For all `v: Self`, `v - v == v + (-v) == Self::ZERO`.
21/// - (Compatibility of multiplication) For all `a, b: f32`, `v: Self`, `v * (a * b) == (v * a) * b`.
22/// - (Multiplicative identity) For all `v: Self`, `v * 1.0 == v`.
23/// - (Distributivity for vector addition) For all `a: f32`, `u, v: Self`, `(u + v) * a == u * a + v * a`.
24/// - (Distributivity for scalar addition) For all `a, b: f32`, `v: Self`, `v * (a + b) == v * a + v * b`.
25///
26/// Note that, because implementing types use floating point arithmetic, they are not required to actually
27/// implement `PartialEq` or `Eq`.
28pub trait VectorSpace:
29    Mul<f32, Output = Self>
30    + Div<f32, Output = Self>
31    + Add<Self, Output = Self>
32    + Sub<Self, Output = Self>
33    + Neg
34    + Default
35    + Debug
36    + Clone
37    + Copy
38{
39    /// The zero vector, which is the identity of addition for the vector space type.
40    const ZERO: Self;
41
42    /// Perform vector space linear interpolation between this element and another, based
43    /// on the parameter `t`. When `t` is `0`, `self` is recovered. When `t` is `1`, `rhs`
44    /// is recovered.
45    ///
46    /// Note that the value of `t` is not clamped by this function, so extrapolating outside
47    /// of the interval `[0,1]` is allowed.
48    #[inline]
49    fn lerp(self, rhs: Self, t: f32) -> Self {
50        self * (1. - t) + rhs * t
51    }
52}
53
54impl VectorSpace for Vec4 {
55    const ZERO: Self = Vec4::ZERO;
56}
57
58impl VectorSpace for Vec3 {
59    const ZERO: Self = Vec3::ZERO;
60}
61
62impl VectorSpace for Vec3A {
63    const ZERO: Self = Vec3A::ZERO;
64}
65
66impl VectorSpace for Vec2 {
67    const ZERO: Self = Vec2::ZERO;
68}
69
70impl VectorSpace for f32 {
71    const ZERO: Self = 0.0;
72}
73
74/// A type that supports the operations of a normed vector space; i.e. a norm operation in addition
75/// to those of [`VectorSpace`]. Specifically, the implementor must guarantee that the following
76/// relationships hold, within the limitations of floating point arithmetic:
77/// - (Nonnegativity) For all `v: Self`, `v.norm() >= 0.0`.
78/// - (Positive definiteness) For all `v: Self`, `v.norm() == 0.0` implies `v == Self::ZERO`.
79/// - (Absolute homogeneity) For all `c: f32`, `v: Self`, `(v * c).norm() == v.norm() * c.abs()`.
80/// - (Triangle inequality) For all `v, w: Self`, `(v + w).norm() <= v.norm() + w.norm()`.
81///
82/// Note that, because implementing types use floating point arithmetic, they are not required to actually
83/// implement `PartialEq` or `Eq`.
84pub trait NormedVectorSpace: VectorSpace {
85    /// The size of this element. The return value should always be nonnegative.
86    fn norm(self) -> f32;
87
88    /// The squared norm of this element. Computing this is often faster than computing
89    /// [`NormedVectorSpace::norm`].
90    #[inline]
91    fn norm_squared(self) -> f32 {
92        self.norm() * self.norm()
93    }
94
95    /// The distance between this element and another, as determined by the norm.
96    #[inline]
97    fn distance(self, rhs: Self) -> f32 {
98        (rhs - self).norm()
99    }
100
101    /// The squared distance between this element and another, as determined by the norm. Note that
102    /// this is often faster to compute in practice than [`NormedVectorSpace::distance`].
103    #[inline]
104    fn distance_squared(self, rhs: Self) -> f32 {
105        (rhs - self).norm_squared()
106    }
107}
108
109impl NormedVectorSpace for Vec4 {
110    #[inline]
111    fn norm(self) -> f32 {
112        self.length()
113    }
114
115    #[inline]
116    fn norm_squared(self) -> f32 {
117        self.length_squared()
118    }
119}
120
121impl NormedVectorSpace for Vec3 {
122    #[inline]
123    fn norm(self) -> f32 {
124        self.length()
125    }
126
127    #[inline]
128    fn norm_squared(self) -> f32 {
129        self.length_squared()
130    }
131}
132
133impl NormedVectorSpace for Vec3A {
134    #[inline]
135    fn norm(self) -> f32 {
136        self.length()
137    }
138
139    #[inline]
140    fn norm_squared(self) -> f32 {
141        self.length_squared()
142    }
143}
144
145impl NormedVectorSpace for Vec2 {
146    #[inline]
147    fn norm(self) -> f32 {
148        self.length()
149    }
150
151    #[inline]
152    fn norm_squared(self) -> f32 {
153        self.length_squared()
154    }
155}
156
157impl NormedVectorSpace for f32 {
158    #[inline]
159    fn norm(self) -> f32 {
160        self.abs()
161    }
162
163    #[inline]
164    fn norm_squared(self) -> f32 {
165        self * self
166    }
167}
168
169/// A type with a natural interpolation that provides strong subdivision guarantees.
170///
171/// Although the only required method is `interpolate_stable`, many things are expected of it:
172///
173/// 1. The notion of interpolation should follow naturally from the semantics of the type, so
174///    that inferring the interpolation mode from the type alone is sensible.
175///
176/// 2. The interpolation recovers something equivalent to the starting value at `t = 0.0`
177///    and likewise with the ending value at `t = 1.0`. They do not have to be data-identical, but
178///    they should be semantically identical. For example, [`Quat::slerp`] doesn't always yield its
179///    second rotation input exactly at `t = 1.0`, but it always returns an equivalent rotation.
180///
181/// 3. Importantly, the interpolation must be *subdivision-stable*: for any interpolation curve
182///    between two (unnamed) values and any parameter-value pairs `(t0, p)` and `(t1, q)`, the
183///    interpolation curve between `p` and `q` must be the *linear* reparametrization of the original
184///    interpolation curve restricted to the interval `[t0, t1]`.
185///
186/// The last of these conditions is very strong and indicates something like constant speed. It
187/// is called "subdivision stability" because it guarantees that breaking up the interpolation
188/// into segments and joining them back together has no effect.
189///
190/// Here is a diagram depicting it:
191/// ```text
192/// top curve = u.interpolate_stable(v, t)
193///
194///              t0 => p   t1 => q    
195///   |-------------|---------|-------------|
196/// 0 => u         /           \          1 => v
197///              /               \
198///            /                   \
199///          /        linear         \
200///        /     reparametrization     \
201///      /   t = t0 * (1 - s) + t1 * s   \
202///    /                                   \
203///   |-------------------------------------|
204/// 0 => p                                1 => q
205///
206/// bottom curve = p.interpolate_stable(q, s)
207/// ```
208///
209/// Note that some common forms of interpolation do not satisfy this criterion. For example,
210/// [`Quat::lerp`] and [`Rot2::nlerp`] are not subdivision-stable.
211///
212/// Furthermore, this is not to be used as a general trait for abstract interpolation.
213/// Consumers rely on the strong guarantees in order for behavior based on this trait to be
214/// well-behaved.
215///
216/// [`Quat::slerp`]: crate::Quat::slerp
217/// [`Quat::lerp`]: crate::Quat::lerp
218/// [`Rot2::nlerp`]: crate::Rot2::nlerp
219pub trait StableInterpolate: Clone {
220    /// Interpolate between this value and the `other` given value using the parameter `t`. At
221    /// `t = 0.0`, a value equivalent to `self` is recovered, while `t = 1.0` recovers a value
222    /// equivalent to `other`, with intermediate values interpolating between the two.
223    /// See the [trait-level documentation] for details.
224    ///
225    /// [trait-level documentation]: StableInterpolate
226    fn interpolate_stable(&self, other: &Self, t: f32) -> Self;
227
228    /// A version of [`interpolate_stable`] that assigns the result to `self` for convenience.
229    ///
230    /// [`interpolate_stable`]: StableInterpolate::interpolate_stable
231    fn interpolate_stable_assign(&mut self, other: &Self, t: f32) {
232        *self = self.interpolate_stable(other, t);
233    }
234
235    /// Smoothly nudge this value towards the `target` at a given decay rate. The `decay_rate`
236    /// parameter controls how fast the distance between `self` and `target` decays relative to
237    /// the units of `delta`; the intended usage is for `decay_rate` to generally remain fixed,
238    /// while `delta` is something like `delta_time` from an updating system. This produces a
239    /// smooth following of the target that is independent of framerate.
240    ///
241    /// More specifically, when this is called repeatedly, the result is that the distance between
242    /// `self` and a fixed `target` attenuates exponentially, with the rate of this exponential
243    /// decay given by `decay_rate`.
244    ///
245    /// For example, at `decay_rate = 0.0`, this has no effect.
246    /// At `decay_rate = f32::INFINITY`, `self` immediately snaps to `target`.
247    /// In general, higher rates mean that `self` moves more quickly towards `target`.
248    ///
249    /// # Example
250    /// ```
251    /// # use bevy_math::{Vec3, StableInterpolate};
252    /// # let delta_time: f32 = 1.0 / 60.0;
253    /// let mut object_position: Vec3 = Vec3::ZERO;
254    /// let target_position: Vec3 = Vec3::new(2.0, 3.0, 5.0);
255    /// // Decay rate of ln(10) => after 1 second, remaining distance is 1/10th
256    /// let decay_rate = f32::ln(10.0);
257    /// // Calling this repeatedly will move `object_position` towards `target_position`:
258    /// object_position.smooth_nudge(&target_position, decay_rate, delta_time);
259    /// ```
260    fn smooth_nudge(&mut self, target: &Self, decay_rate: f32, delta: f32) {
261        self.interpolate_stable_assign(target, 1.0 - ops::exp(-decay_rate * delta));
262    }
263}
264
265// Conservatively, we presently only apply this for normed vector spaces, where the notion
266// of being constant-speed is literally true. The technical axioms are satisfied for any
267// VectorSpace type, but the "natural from the semantics" part is less clear in general.
268impl<V> StableInterpolate for V
269where
270    V: NormedVectorSpace,
271{
272    #[inline]
273    fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
274        self.lerp(*other, t)
275    }
276}
277
278impl StableInterpolate for Rot2 {
279    #[inline]
280    fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
281        self.slerp(*other, t)
282    }
283}
284
285impl StableInterpolate for Quat {
286    #[inline]
287    fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
288        self.slerp(*other, t)
289    }
290}
291
292impl StableInterpolate for Dir2 {
293    #[inline]
294    fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
295        self.slerp(*other, t)
296    }
297}
298
299impl StableInterpolate for Dir3 {
300    #[inline]
301    fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
302        self.slerp(*other, t)
303    }
304}
305
306impl StableInterpolate for Dir3A {
307    #[inline]
308    fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
309        self.slerp(*other, t)
310    }
311}
312
313// If you're confused about how #[doc(fake_variadic)] works,
314// then the `all_tuples` macro is nicely documented (it can be found in the `bevy_utils` crate).
315// tl;dr: `#[doc(fake_variadic)]` goes on the impl of tuple length one.
316// the others have to be hidden using `#[doc(hidden)]`.
317macro_rules! impl_stable_interpolate_tuple {
318    (($T:ident, $n:tt)) => {
319        impl_stable_interpolate_tuple! {
320            @impl
321            #[cfg_attr(any(docsrs, docsrs_dep), doc(fake_variadic))]
322            #[cfg_attr(
323                any(docsrs, docsrs_dep),
324                doc = "This trait is implemented for tuples up to 11 items long."
325            )]
326            ($T, $n)
327        }
328    };
329    ($(($T:ident, $n:tt)),*) => {
330        impl_stable_interpolate_tuple! {
331            @impl
332            #[cfg_attr(any(docsrs, docsrs_dep), doc(hidden))]
333            $(($T, $n)),*
334        }
335    };
336    (@impl $(#[$($meta:meta)*])* $(($T:ident, $n:tt)),*) => {
337        $(#[$($meta)*])*
338        impl<$($T: StableInterpolate),*> StableInterpolate for ($($T,)*) {
339            fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
340                (
341                    $(
342                        <$T as StableInterpolate>::interpolate_stable(&self.$n, &other.$n, t),
343                    )*
344                )
345            }
346        }
347    };
348}
349
350// (See `macro_metavar_expr`, which might make this better.)
351// This currently implements `StableInterpolate` for tuples of up to 11 elements.
352impl_stable_interpolate_tuple!((T, 0));
353impl_stable_interpolate_tuple!((T0, 0), (T1, 1));
354impl_stable_interpolate_tuple!((T0, 0), (T1, 1), (T2, 2));
355impl_stable_interpolate_tuple!((T0, 0), (T1, 1), (T2, 2), (T3, 3));
356impl_stable_interpolate_tuple!((T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4));
357impl_stable_interpolate_tuple!((T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4), (T5, 5));
358impl_stable_interpolate_tuple!(
359    (T0, 0),
360    (T1, 1),
361    (T2, 2),
362    (T3, 3),
363    (T4, 4),
364    (T5, 5),
365    (T6, 6)
366);
367impl_stable_interpolate_tuple!(
368    (T0, 0),
369    (T1, 1),
370    (T2, 2),
371    (T3, 3),
372    (T4, 4),
373    (T5, 5),
374    (T6, 6),
375    (T7, 7)
376);
377impl_stable_interpolate_tuple!(
378    (T0, 0),
379    (T1, 1),
380    (T2, 2),
381    (T3, 3),
382    (T4, 4),
383    (T5, 5),
384    (T6, 6),
385    (T7, 7),
386    (T8, 8)
387);
388impl_stable_interpolate_tuple!(
389    (T0, 0),
390    (T1, 1),
391    (T2, 2),
392    (T3, 3),
393    (T4, 4),
394    (T5, 5),
395    (T6, 6),
396    (T7, 7),
397    (T8, 8),
398    (T9, 9)
399);
400impl_stable_interpolate_tuple!(
401    (T0, 0),
402    (T1, 1),
403    (T2, 2),
404    (T3, 3),
405    (T4, 4),
406    (T5, 5),
407    (T6, 6),
408    (T7, 7),
409    (T8, 8),
410    (T9, 9),
411    (T10, 10)
412);