Skip to main content

lib_jsl_geometry/algorithms/
rotations.rs

1//! Rotations in two and three dimensions: matrices, axis-angle, Euler sequences, and composable
2//! rotation types.
3//!
4//! [`Rotation3`] stores a unit [`Quaternion`], so composition is cheap and stays normalised, and
5//! converts to and from rotation matrices, axis-angle and any of the twelve Euler sequences.
6//! Matrices are row-major `[[f64; 3]; 3]` acting on column vectors. Euler sequences are
7//! *intrinsic*: `Rotation3::from_euler(XYZ, [a, b, c])` rotates by `a` about X, then by `b` about
8//! the new Y, then by `c` about the newest Z, i.e. `R = Rx(a) Ry(b) Rz(c)`.
9//!
10//! See the book entry [Rotations, Euler angles and quaternions](https://jwkunz.github.io/lib_jsl/book/geometry/rotations.html).
11
12use super::quaternions::Quaternion;
13use std::f64::consts::PI;
14use std::ops::Mul;
15
16/// A 3×3 matrix in row-major order.
17pub type Matrix3 = [[f64; 3]; 3];
18
19pub const IDENTITY3: Matrix3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
20
21/// Matrix product `a * b`.
22pub fn mat3_mul(a: &Matrix3, b: &Matrix3) -> Matrix3 {
23    let mut out = [[0.0; 3]; 3];
24    for (i, row) in out.iter_mut().enumerate() {
25        for (j, v) in row.iter_mut().enumerate() {
26            *v = (0..3).map(|k| a[i][k] * b[k][j]).sum();
27        }
28    }
29    out
30}
31
32pub fn mat3_transpose(m: &Matrix3) -> Matrix3 {
33    std::array::from_fn(|i| std::array::from_fn(|j| m[j][i]))
34}
35
36pub fn mat3_determinant(m: &Matrix3) -> f64 {
37    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
38        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
39}
40
41/// Matrix-vector product.
42pub fn mat3_apply(m: &Matrix3, v: [f64; 3]) -> [f64; 3] {
43    std::array::from_fn(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2])
44}
45
46/// Whether `m` is orthogonal with determinant +1 within `tol`.
47pub fn is_rotation_matrix(m: &Matrix3, tol: f64) -> bool {
48    let p = mat3_mul(m, &mat3_transpose(m));
49    (0..3).all(|i| (0..3).all(|j| (p[i][j] - IDENTITY3[i][j]).abs() <= tol)) && (mat3_determinant(m) - 1.0).abs() <= tol
50}
51
52/// The rotation matrix closest (in Frobenius norm) to `m`, by Newton iteration for the polar
53/// factor. Useful to clean up a matrix that has drifted after many multiplications. Returns `None`
54/// if `m` is singular or has a negative determinant (is not near a proper rotation).
55pub fn nearest_rotation_matrix(m: &Matrix3) -> Option<Matrix3> {
56    if mat3_determinant(m) <= 0.0 {
57        return None;
58    }
59    let mut r = *m;
60    for _ in 0..50 {
61        let det = mat3_determinant(&r);
62        // inverse transpose = cofactor matrix / det
63        let cof: Matrix3 = std::array::from_fn(|i| {
64            std::array::from_fn(|j| {
65                let (i1, i2, j1, j2) = ((i + 1) % 3, (i + 2) % 3, (j + 1) % 3, (j + 2) % 3);
66                (r[i1][j1] * r[i2][j2] - r[i1][j2] * r[i2][j1]) / det
67            })
68        });
69        let next: Matrix3 = std::array::from_fn(|i| std::array::from_fn(|j| 0.5 * (r[i][j] + cof[i][j])));
70        let delta: f64 = (0..3).flat_map(|i| (0..3).map(move |j| (i, j))).map(|(i, j)| (next[i][j] - r[i][j]).abs()).sum();
71        r = next;
72        if delta < 1e-15 {
73            break;
74        }
75    }
76    Some(r)
77}
78
79/// Rotation about the X axis by `angle` radians.
80pub fn rotation_matrix_x(angle: f64) -> Matrix3 {
81    let (s, c) = angle.sin_cos();
82    [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
83}
84
85/// Rotation about the Y axis by `angle` radians.
86pub fn rotation_matrix_y(angle: f64) -> Matrix3 {
87    let (s, c) = angle.sin_cos();
88    [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
89}
90
91/// Rotation about the Z axis by `angle` radians.
92pub fn rotation_matrix_z(angle: f64) -> Matrix3 {
93    let (s, c) = angle.sin_cos();
94    [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
95}
96
97/// Rodrigues' formula: the matrix of a rotation by `angle` about `axis` (normalised internally;
98/// a zero axis gives the identity).
99pub fn rotation_matrix_axis_angle(axis: [f64; 3], angle: f64) -> Matrix3 {
100    let n = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
101    if n == 0.0 {
102        return IDENTITY3;
103    }
104    let (x, y, z) = (axis[0] / n, axis[1] / n, axis[2] / n);
105    let (s, c) = angle.sin_cos();
106    let t = 1.0 - c;
107    [
108        [t * x * x + c, t * x * y - s * z, t * x * z + s * y],
109        [t * x * y + s * z, t * y * y + c, t * y * z - s * x],
110        [t * x * z - s * y, t * y * z + s * x, t * z * z + c],
111    ]
112}
113
114/// A coordinate axis.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116
117pub enum Axis {
118    X,
119    Y,
120    Z,
121}
122
123impl Axis {
124    fn index(self) -> usize {
125        self as usize
126    }
127    fn matrix(self, angle: f64) -> Matrix3 {
128        match self {
129            Axis::X => rotation_matrix_x(angle),
130            Axis::Y => rotation_matrix_y(angle),
131            Axis::Z => rotation_matrix_z(angle),
132        }
133    }
134}
135
136/// An intrinsic Euler-angle sequence: three axes where consecutive axes differ. Sequences whose
137/// first and last axes coincide (XYX, ...) are "proper" Euler angles; the others (XYZ, ...) are
138/// Tait-Bryan angles.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140
141pub struct EulerSequence(pub [Axis; 3]);
142
143impl EulerSequence {
144    pub const XYZ: EulerSequence = EulerSequence([Axis::X, Axis::Y, Axis::Z]);
145    pub const XZY: EulerSequence = EulerSequence([Axis::X, Axis::Z, Axis::Y]);
146    pub const YXZ: EulerSequence = EulerSequence([Axis::Y, Axis::X, Axis::Z]);
147    pub const YZX: EulerSequence = EulerSequence([Axis::Y, Axis::Z, Axis::X]);
148    pub const ZXY: EulerSequence = EulerSequence([Axis::Z, Axis::X, Axis::Y]);
149    pub const ZYX: EulerSequence = EulerSequence([Axis::Z, Axis::Y, Axis::X]);
150    pub const XYX: EulerSequence = EulerSequence([Axis::X, Axis::Y, Axis::X]);
151    pub const XZX: EulerSequence = EulerSequence([Axis::X, Axis::Z, Axis::X]);
152    pub const YXY: EulerSequence = EulerSequence([Axis::Y, Axis::X, Axis::Y]);
153    pub const YZY: EulerSequence = EulerSequence([Axis::Y, Axis::Z, Axis::Y]);
154    pub const ZXZ: EulerSequence = EulerSequence([Axis::Z, Axis::X, Axis::Z]);
155    pub const ZYZ: EulerSequence = EulerSequence([Axis::Z, Axis::Y, Axis::Z]);
156
157    /// Whether consecutive axes differ (the only valid sequences).
158    pub fn is_valid(&self) -> bool {
159        self.0[0] != self.0[1] && self.0[1] != self.0[2]
160    }
161
162    /// The matrix `R = R_a0(α) R_a1(β) R_a2(γ)` for `angles = [α, β, γ]`.
163    pub fn to_matrix(&self, angles: [f64; 3]) -> Matrix3 {
164        let m = mat3_mul(&self.0[0].matrix(angles[0]), &self.0[1].matrix(angles[1]));
165        mat3_mul(&m, &self.0[2].matrix(angles[2]))
166    }
167
168    /// Angles `[α, β, γ]` reproducing the rotation matrix `m` (inverse of [`EulerSequence::to_matrix`]).
169    /// The decomposition is not unique; the result has the middle angle in `[0, π]` for proper
170    /// sequences and in `[-π/2, π/2]` for Tait-Bryan ones, and the outer angles in `(-π, π]`.
171    /// At gimbal lock (the middle angle within `1e-10` of a singular value) the third angle is
172    /// folded into the first and returned as zero. `None` for an invalid sequence.
173    pub fn from_matrix(&self, m: &Matrix3) -> Option<[f64; 3]> {
174        if !self.is_valid() {
175            return None;
176        }
177        let [a0, a1, a2] = self.0.map(Axis::index);
178        let odd = if (a0 + 1) % 3 == a1 { 0 } else { 1 };
179        let i = a0;
180        let j = (a0 + 1 + odd) % 3;
181        let k = (a0 + 2 - odd) % 3;
182        let mut res = [0.0; 3];
183        if a0 == a2 {
184            res[0] = m[j][i].atan2(m[k][i]);
185            let s2 = m[j][i].hypot(m[k][i]);
186            if (odd == 1 && res[0] < 0.0) || (odd == 0 && res[0] > 0.0) {
187                res[0] += if res[0] > 0.0 { -PI } else { PI };
188                res[1] = -s2.atan2(m[i][i]);
189            } else {
190                res[1] = s2.atan2(m[i][i]);
191            }
192            let (s1, c1) = res[0].sin_cos();
193            res[2] = (c1 * m[j][k] - s1 * m[k][k]).atan2(c1 * m[j][j] - s1 * m[k][j]);
194        } else {
195            res[0] = m[j][k].atan2(m[k][k]);
196            let c2 = m[i][i].hypot(m[i][j]);
197            if (odd == 1 && res[0] < 0.0) || (odd == 0 && res[0] > 0.0) {
198                res[0] += if res[0] > 0.0 { -PI } else { PI };
199                res[1] = (-m[i][k]).atan2(-c2);
200            } else {
201                res[1] = (-m[i][k]).atan2(c2);
202            }
203            let (s1, c1) = res[0].sin_cos();
204            res[2] = (s1 * m[k][i] - c1 * m[j][i]).atan2(c1 * m[j][j] - s1 * m[k][j]);
205        }
206        if odd == 0 {
207            res = res.map(|a| -a);
208        }
209        // Bring the middle angle into its documented range with the equivalent decomposition
210        // (α + π, π − β, γ + π) for Tait-Bryan sequences or (α + π, −β, γ + π) for proper ones,
211        // then wrap the outer angles into (−π, π].
212        if a0 == a2 {
213            if res[1] < 0.0 {
214                res = [res[0] + PI, -res[1], res[2] + PI];
215            }
216        } else if res[1].abs() > PI / 2.0 {
217            res = [res[0] + PI, PI.copysign(res[1]) - res[1], res[2] + PI];
218        }
219        // At gimbal lock only α ± γ is determined, and how it was split between them came from
220        // rounding noise: fold it into α, with whichever sign reproduces the matrix, and set γ = 0.
221        let lock = if a0 == a2 { res[1].min(PI - res[1]) } else { PI / 2.0 - res[1].abs() };
222        if lock < 1e-10 {
223            let fit = |alpha: f64| {
224                let r = self.to_matrix([alpha, res[1], 0.0]);
225                (0..9).map(|k| (r[k / 3][k % 3] - m[k / 3][k % 3]).abs()).fold(0.0, f64::max)
226            };
227            let (plus, minus) = (res[0] + res[2], res[0] - res[2]);
228            res = [if fit(plus) <= fit(minus) { plus } else { minus }, res[1], 0.0];
229        }
230        for k in [0, 2] {
231            res[k] = PI - (PI - res[k]).rem_euclid(2.0 * PI);
232        }
233        Some(res)
234    }
235}
236
237/// A rotation in the plane about the origin.
238#[derive(Debug, Clone, Copy, PartialEq)]
239
240pub struct Rotation2 {
241    pub angle: f64,
242}
243
244impl Rotation2 {
245    pub fn new(angle: f64) -> Self {
246        Rotation2 { angle }
247    }
248    pub fn identity() -> Self {
249        Rotation2 { angle: 0.0 }
250    }
251    /// Counter-clockwise rotation taking direction `from` to direction `to`.
252    pub fn from_two_vectors(from: [f64; 2], to: [f64; 2]) -> Self {
253        let cross = from[0] * to[1] - from[1] * to[0];
254        let dot = from[0] * to[0] + from[1] * to[1];
255        Rotation2 { angle: cross.atan2(dot) }
256    }
257    pub fn matrix(&self) -> [[f64; 2]; 2] {
258        let (s, c) = self.angle.sin_cos();
259        [[c, -s], [s, c]]
260    }
261    pub fn rotate(&self, p: [f64; 2]) -> [f64; 2] {
262        let (s, c) = self.angle.sin_cos();
263        [c * p[0] - s * p[1], s * p[0] + c * p[1]]
264    }
265    /// Rotates `p` about `pivot` instead of the origin.
266    pub fn rotate_about(&self, p: [f64; 2], pivot: [f64; 2]) -> [f64; 2] {
267        let r = self.rotate([p[0] - pivot[0], p[1] - pivot[1]]);
268        [r[0] + pivot[0], r[1] + pivot[1]]
269    }
270    pub fn inverse(&self) -> Self {
271        Rotation2 { angle: -self.angle }
272    }
273    /// The angle wrapped into `(-π, π]`.
274    pub fn normalized(&self) -> Self {
275        let mut a = self.angle.rem_euclid(2.0 * PI);
276        if a > PI {
277            a -= 2.0 * PI;
278        }
279        Rotation2 { angle: a }
280    }
281}
282
283#[allow(clippy::suspicious_arithmetic_impl)] // composing planar rotations adds their angles
284impl Mul for Rotation2 {
285    type Output = Rotation2;
286    /// `a * b` rotates by `b` first, then by `a`.
287    fn mul(self, o: Rotation2) -> Rotation2 {
288        Rotation2 { angle: self.angle + o.angle }
289    }
290}
291
292/// A rotation in three dimensions, stored as a unit quaternion.
293#[derive(Debug, Clone, Copy, PartialEq)]
294
295pub struct Rotation3 {
296    q: Quaternion,
297}
298
299impl Rotation3 {
300    pub fn identity() -> Self {
301        Rotation3 { q: Quaternion::identity() }
302    }
303    /// Wraps a quaternion, normalising it.
304    pub fn from_quaternion(q: Quaternion) -> Self {
305        Rotation3 { q: q.normalized() }
306    }
307    pub fn from_axis_angle(axis: [f64; 3], angle: f64) -> Self {
308        Rotation3 { q: Quaternion::from_axis_angle(axis, angle) }
309    }
310    /// From a rotation matrix; use [`nearest_rotation_matrix`] first if it may be noisy.
311    pub fn from_matrix(m: &Matrix3) -> Self {
312        Rotation3 { q: Quaternion::from_rotation_matrix(m).normalized() }
313    }
314    pub fn from_euler(sequence: EulerSequence, angles: [f64; 3]) -> Self {
315        Self::from_matrix(&sequence.to_matrix(angles))
316    }
317    /// The shortest rotation taking direction `from` to direction `to`.
318    pub fn from_two_vectors(from: [f64; 3], to: [f64; 3]) -> Self {
319        Rotation3 { q: Quaternion::from_two_vectors(from, to) }
320    }
321    pub fn quaternion(&self) -> Quaternion {
322        self.q
323    }
324    pub fn matrix(&self) -> Matrix3 {
325        self.q.to_rotation_matrix()
326    }
327    /// Unit axis and angle in `[0, π]`.
328    pub fn axis_angle(&self) -> ([f64; 3], f64) {
329        self.q.to_axis_angle()
330    }
331    pub fn to_euler(&self, sequence: EulerSequence) -> Option<[f64; 3]> {
332        sequence.from_matrix(&self.matrix())
333    }
334    pub fn inverse(&self) -> Self {
335        Rotation3 { q: self.q.conjugate() }
336    }
337    /// Applies the rotation to a vector.
338    pub fn rotate(&self, v: [f64; 3]) -> [f64; 3] {
339        self.q.rotate_vector(v)
340    }
341    /// Rotates a point about `pivot` instead of the origin.
342    pub fn rotate_about(&self, p: [f64; 3], pivot: [f64; 3]) -> [f64; 3] {
343        let r = self.rotate([p[0] - pivot[0], p[1] - pivot[1], p[2] - pivot[2]]);
344        [r[0] + pivot[0], r[1] + pivot[1], r[2] + pivot[2]]
345    }
346    /// The angle of the rotation that takes `self` to `other`.
347    pub fn angle_to(&self, other: &Rotation3) -> f64 {
348        self.q.angle_to(&other.q)
349    }
350    pub fn slerp(&self, other: &Rotation3, t: f64) -> Self {
351        Rotation3 { q: self.q.slerp(&other.q, t) }
352    }
353
354    // ANCHOR: rotvec
355    /// From a rotation vector (SciPy's `from_rotvec`): the axis scaled by the angle in radians.
356    pub fn from_rotvec(v: [f64; 3]) -> Self {
357        let angle = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
358        // q = (cos(θ/2), sin(θ/2)/θ · v), with the series for sin(θ/2)/θ near zero.
359        let scale = if angle < 1e-3 {
360            let a2 = angle * angle;
361            0.5 - a2 / 48.0 + a2 * a2 / 3840.0
362        } else {
363            (angle / 2.0).sin() / angle
364        };
365        Rotation3 { q: Quaternion::new((angle / 2.0).cos(), scale * v[0], scale * v[1], scale * v[2]).normalized() }
366    }
367
368    /// The rotation vector (SciPy's `as_rotvec`): axis times angle, the angle in `[0, π]`.
369    pub fn as_rotvec(&self) -> [f64; 3] {
370        let q = if self.q.w < 0.0 { -self.q } else { self.q };
371        let s = (q.x * q.x + q.y * q.y + q.z * q.z).sqrt();
372        let angle = 2.0 * s.atan2(q.w);
373        // θ / sin(θ/2), with its series near zero.
374        let scale = if angle < 1e-3 {
375            let a2 = angle * angle;
376            2.0 + a2 / 12.0 + 7.0 * a2 * a2 / 2880.0
377        } else {
378            angle / (angle / 2.0).sin()
379        };
380        [scale * q.x, scale * q.y, scale * q.z]
381    }
382
383    /// From modified Rodrigues parameters `p = n tan(θ/4)` (SciPy's `from_mrp`).
384    pub fn from_mrp(p: [f64; 3]) -> Self {
385        let p2 = p[0] * p[0] + p[1] * p[1] + p[2] * p[2];
386        let d = 1.0 + p2;
387        Rotation3 { q: Quaternion::new((1.0 - p2) / d, 2.0 * p[0] / d, 2.0 * p[1] / d, 2.0 * p[2] / d).normalized() }
388    }
389
390    /// The modified Rodrigues parameters `n tan(θ/4)`, `θ ∈ [0, π]` (SciPy's `as_mrp`).
391    pub fn as_mrp(&self) -> [f64; 3] {
392        let q = if self.q.w < 0.0 { -self.q } else { self.q };
393        let d = 1.0 + q.w;
394        [q.x / d, q.y / d, q.z / d]
395    }
396    // ANCHOR_END: rotvec
397
398    /// A rotation from three numbers uniform on `[0, 1)` (Shoemake's method): with uniform inputs
399    /// the rotations are uniformly distributed (Haar measure), as SciPy's `Rotation.random`.
400    pub fn from_uniform(u1: f64, u2: f64, u3: f64) -> Self {
401        let (a, b) = ((1.0 - u1).sqrt(), u1.sqrt());
402        let tau = std::f64::consts::TAU;
403        let (s2, c2) = (tau * u2).sin_cos();
404        let (s3, c3) = (tau * u3).sin_cos();
405        Rotation3 { q: Quaternion::new(b * c3, a * s2, a * c2, b * s3).normalized() }
406    }
407
408    /// `n` uniformly distributed random rotations, drawing uniforms on `[0, 1)` from `next`.
409    pub fn random(n: usize, mut next: impl FnMut() -> f64) -> Vec<Rotation3> {
410        (0..n).map(|_| Rotation3::from_uniform(next(), next(), next())).collect()
411    }
412}
413
414impl Mul for Rotation3 {
415    type Output = Rotation3;
416    /// `a * b` applies `b` first, then `a`.
417    fn mul(self, o: Rotation3) -> Rotation3 {
418        Rotation3 { q: (self.q * o.q).normalized() }
419    }
420}
421
422impl From<Quaternion> for Rotation3 {
423    fn from(q: Quaternion) -> Self {
424        Rotation3::from_quaternion(q)
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431    use std::f64::consts::FRAC_PI_2;
432
433    fn close(a: &Matrix3, b: &Matrix3, tol: f64) -> bool {
434        (0..3).all(|i| (0..3).all(|j| (a[i][j] - b[i][j]).abs() < tol))
435    }
436
437    #[test]
438    fn axis_matrices_and_rodrigues_agree() {
439        assert!(close(&rotation_matrix_axis_angle([1.0, 0.0, 0.0], 0.7), &rotation_matrix_x(0.7), 1e-14));
440        assert!(close(&rotation_matrix_axis_angle([0.0, 2.0, 0.0], -1.3), &rotation_matrix_y(-1.3), 1e-14));
441        assert!(close(&rotation_matrix_axis_angle([0.0, 0.0, 5.0], 2.9), &rotation_matrix_z(2.9), 1e-14));
442        assert!(is_rotation_matrix(&rotation_matrix_axis_angle([1.0, 2.0, 3.0], 1.1), 1e-12));
443        assert_eq!(rotation_matrix_axis_angle([0.0; 3], 1.0), IDENTITY3);
444        let q = Quaternion::from_axis_angle([1.0, 2.0, 3.0], 1.1);
445        assert!(close(&q.to_rotation_matrix(), &rotation_matrix_axis_angle([1.0, 2.0, 3.0], 1.1), 1e-12));
446    }
447
448    #[test]
449    fn every_euler_sequence_round_trips_through_the_matrix() {
450        let seqs = [
451            EulerSequence::XYZ, EulerSequence::XZY, EulerSequence::YXZ, EulerSequence::YZX, EulerSequence::ZXY, EulerSequence::ZYX,
452            EulerSequence::XYX, EulerSequence::XZX, EulerSequence::YXY, EulerSequence::YZY, EulerSequence::ZXZ, EulerSequence::ZYZ,
453        ];
454        for seq in seqs {
455            for angles in [[0.3, 0.5, -1.2], [-2.0, 1.2, 2.5], [3.0, -0.7, 0.1], [0.0, 0.0, 0.0], [1.0, 2.5, -3.0], [-2.5, -1.0, 2.0], [0.3, 2.0, 0.5], [-0.3, -1.0, -0.5]] {
456                let m = seq.to_matrix(angles);
457                let back = seq.from_matrix(&m).unwrap();
458                assert!(close(&seq.to_matrix(back), &m, 1e-9), "{seq:?} {angles:?} -> {back:?}");
459                // The documented ranges: outer angles in (−π, π], the middle one in [0, π] for
460                // proper sequences and [−π/2, π/2] for Tait-Bryan ones.
461                let proper = seq.0[0] == seq.0[2];
462                let middle_ok = if proper { (0.0..=PI).contains(&back[1]) } else { back[1].abs() <= FRAC_PI_2 };
463                assert!(middle_ok && back[0].abs() <= PI && back[2].abs() <= PI, "{seq:?} {angles:?} -> {back:?}");
464                // Within those ranges the decomposition is unique away from gimbal lock.
465                let canonical = if proper { (0.0..=PI).contains(&angles[1]) } else { angles[1].abs() <= FRAC_PI_2 };
466                if canonical && angles[1] != 0.0 {
467                    assert!((0..3).all(|k| (back[k] - angles[k]).abs() < 1e-9), "{seq:?} {angles:?} -> {back:?}");
468                }
469            }
470        }
471        assert!(EulerSequence([Axis::X, Axis::X, Axis::Z]).from_matrix(&IDENTITY3).is_none());
472    }
473
474    #[test]
475    fn euler_gimbal_lock_still_reproduces_the_matrix() {
476        let seq = EulerSequence::ZYX;
477        for pitch in [FRAC_PI_2, -FRAC_PI_2] {
478            let m = seq.to_matrix([0.4, pitch, 0.9]);
479            assert!(close(&seq.to_matrix(seq.from_matrix(&m).unwrap()), &m, 1e-9));
480        }
481        // The third angle is folded into the first.
482        for (seq, angles) in [(EulerSequence::XYZ, [0.0, FRAC_PI_2, FRAC_PI_2]), (EulerSequence::ZYX, [0.4, -FRAC_PI_2, 0.9]), (EulerSequence::ZXZ, [0.4, PI, 0.9])] {
483            let m = seq.to_matrix(angles);
484            let back = seq.from_matrix(&m).unwrap();
485            assert!(back[2] == 0.0 && close(&seq.to_matrix(back), &m, 1e-9), "{seq:?} {angles:?} -> {back:?}");
486        }
487        let m = EulerSequence::ZXZ.to_matrix([0.4, 0.0, 0.9]); // proper-Euler singularity at beta = 0
488        assert!(close(&EulerSequence::ZXZ.to_matrix(EulerSequence::ZXZ.from_matrix(&m).unwrap()), &m, 1e-9));
489    }
490
491    #[test]
492    fn rotation3_composes_inverts_and_converts() {
493        let a = Rotation3::from_axis_angle([1.0, 0.0, 0.0], 0.8);
494        let b = Rotation3::from_euler(EulerSequence::ZYX, [0.3, -0.4, 1.0]);
495        let v = [1.0, -2.0, 0.5];
496        let ab = a * b;
497        let want = a.rotate(b.rotate(v));
498        let got = ab.rotate(v);
499        assert!((0..3).all(|i| (want[i] - got[i]).abs() < 1e-12));
500        assert!((ab * ab.inverse()).angle_to(&Rotation3::identity()) < 1e-12);
501        assert!(close(&Rotation3::from_matrix(&b.matrix()).matrix(), &b.matrix(), 1e-12));
502        let e = b.to_euler(EulerSequence::ZYX).unwrap();
503        assert!(Rotation3::from_euler(EulerSequence::ZYX, e).angle_to(&b) < 1e-9);
504        let pivoted = Rotation3::from_axis_angle([0.0, 0.0, 1.0], FRAC_PI_2).rotate_about([2.0, 1.0, 0.0], [1.0, 1.0, 0.0]);
505        assert!((pivoted[0] - 1.0).abs() < 1e-12 && (pivoted[1] - 2.0).abs() < 1e-12);
506        assert!(Rotation3::identity().slerp(&a, 0.5).angle_to(&Rotation3::from_axis_angle([1.0, 0.0, 0.0], 0.4)) < 1e-12);
507    }
508
509    #[test]
510    fn rotation2_and_matrix_cleanup() {
511        let r = Rotation2::new(FRAC_PI_2);
512        let p = r.rotate([1.0, 0.0]);
513        assert!(p[0].abs() < 1e-15 && (p[1] - 1.0).abs() < 1e-15);
514        assert_eq!(r.matrix()[1][0], 1.0);
515        let about = r.rotate_about([2.0, 1.0], [1.0, 1.0]);
516        assert!((about[0] - 1.0).abs() < 1e-12 && (about[1] - 2.0).abs() < 1e-12);
517        assert!((Rotation2::from_two_vectors([1.0, 0.0], [0.0, -3.0]).angle + FRAC_PI_2).abs() < 1e-12);
518        assert!((Rotation2::new(7.0).normalized().angle - (7.0 - 2.0 * PI)).abs() < 1e-12);
519        assert!(((r * r.inverse()).angle).abs() < 1e-15);
520
521        let mut m = rotation_matrix_axis_angle([1.0, 1.0, 0.0], 0.6);
522        m[0][0] += 1e-3;
523        m[1][2] -= 2e-3;
524        assert!(!is_rotation_matrix(&m, 1e-6));
525        let fixed = nearest_rotation_matrix(&m).unwrap();
526        assert!(is_rotation_matrix(&fixed, 1e-12));
527        assert!(nearest_rotation_matrix(&[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]).is_none());
528    }
529}