1use super::quaternions::Quaternion;
13use std::f64::consts::PI;
14use std::ops::Mul;
15
16pub 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
21pub 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
41pub 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
46pub 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
52pub 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 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
79pub 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
85pub 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
91pub 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
97pub 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#[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#[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 pub fn is_valid(&self) -> bool {
159 self.0[0] != self.0[1] && self.0[1] != self.0[2]
160 }
161
162 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 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 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 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#[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 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 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 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)] impl Mul for Rotation2 {
285 type Output = Rotation2;
286 fn mul(self, o: Rotation2) -> Rotation2 {
288 Rotation2 { angle: self.angle + o.angle }
289 }
290}
291
292#[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 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 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 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 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 pub fn rotate(&self, v: [f64; 3]) -> [f64; 3] {
339 self.q.rotate_vector(v)
340 }
341 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 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 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 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 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 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 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 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 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 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 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 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 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 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]); 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}