Skip to main content

brepkit_math/
mat.rs

1//! Matrix types for geometric transforms.
2//!
3//! [`Mat3`] is a 3x3 matrix and [`Mat4`] is a 4x4 affine transform matrix.
4
5use crate::madd::Madd;
6use std::ops::Mul;
7
8use crate::MathError;
9use crate::vec::Point3;
10
11// ---------------------------------------------------------------------------
12// Mat3
13// ---------------------------------------------------------------------------
14
15/// A 3x3 matrix stored in row-major order.
16#[derive(Debug, Clone, Copy, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct Mat3(pub [[f64; 3]; 3]);
19
20impl Mat3 {
21    /// The 3x3 identity matrix.
22    #[must_use]
23    pub const fn identity() -> Self {
24        Self([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
25    }
26
27    /// Transpose the matrix.
28    #[must_use]
29    pub const fn transpose(self) -> Self {
30        let m = &self.0;
31        Self([
32            [m[0][0], m[1][0], m[2][0]],
33            [m[0][1], m[1][1], m[2][1]],
34            [m[0][2], m[1][2], m[2][2]],
35        ])
36    }
37
38    /// Compute the determinant of the matrix.
39    #[must_use]
40    pub fn determinant(self) -> f64 {
41        let m = &self.0;
42        m[0][0].madd(
43            m[1][1].madd(m[2][2], -(m[1][2] * m[2][1])),
44            m[0][1].madd(
45                m[1][2].madd(m[2][0], -(m[1][0] * m[2][2])),
46                m[0][2] * m[1][0].madd(m[2][1], -(m[1][1] * m[2][0])),
47            ),
48        )
49    }
50}
51
52// ---------------------------------------------------------------------------
53// Mat4
54// ---------------------------------------------------------------------------
55
56/// A 4x4 matrix stored in row-major order, typically used for affine transforms.
57#[derive(Debug, Clone, Copy, PartialEq)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59pub struct Mat4(pub [[f64; 4]; 4]);
60
61impl Mat4 {
62    /// The 4x4 identity matrix.
63    #[must_use]
64    pub const fn identity() -> Self {
65        Self([
66            [1.0, 0.0, 0.0, 0.0],
67            [0.0, 1.0, 0.0, 0.0],
68            [0.0, 0.0, 1.0, 0.0],
69            [0.0, 0.0, 0.0, 1.0],
70        ])
71    }
72
73    /// Create a translation matrix.
74    #[must_use]
75    pub const fn translation(tx: f64, ty: f64, tz: f64) -> Self {
76        Self([
77            [1.0, 0.0, 0.0, tx],
78            [0.0, 1.0, 0.0, ty],
79            [0.0, 0.0, 1.0, tz],
80            [0.0, 0.0, 0.0, 1.0],
81        ])
82    }
83
84    /// Create a uniform or non-uniform scale matrix.
85    #[must_use]
86    pub const fn scale(sx: f64, sy: f64, sz: f64) -> Self {
87        Self([
88            [sx, 0.0, 0.0, 0.0],
89            [0.0, sy, 0.0, 0.0],
90            [0.0, 0.0, sz, 0.0],
91            [0.0, 0.0, 0.0, 1.0],
92        ])
93    }
94
95    /// Create a rotation matrix around the X axis by `angle` radians.
96    #[must_use]
97    pub fn rotation_x(angle: f64) -> Self {
98        let (s, c) = angle.sin_cos();
99        Self([
100            [1.0, 0.0, 0.0, 0.0],
101            [0.0, c, -s, 0.0],
102            [0.0, s, c, 0.0],
103            [0.0, 0.0, 0.0, 1.0],
104        ])
105    }
106
107    /// Create a rotation matrix around the Y axis by `angle` radians.
108    #[must_use]
109    pub fn rotation_y(angle: f64) -> Self {
110        let (s, c) = angle.sin_cos();
111        Self([
112            [c, 0.0, s, 0.0],
113            [0.0, 1.0, 0.0, 0.0],
114            [-s, 0.0, c, 0.0],
115            [0.0, 0.0, 0.0, 1.0],
116        ])
117    }
118
119    /// Create a rotation matrix around the Z axis by `angle` radians.
120    #[must_use]
121    pub fn rotation_z(angle: f64) -> Self {
122        let (s, c) = angle.sin_cos();
123        Self([
124            [c, -s, 0.0, 0.0],
125            [s, c, 0.0, 0.0],
126            [0.0, 0.0, 1.0, 0.0],
127            [0.0, 0.0, 0.0, 1.0],
128        ])
129    }
130
131    /// Transform a 3D point by this matrix (assumes w = 1).
132    #[must_use]
133    pub fn mul_point(self, p: Point3) -> Point3 {
134        let m = &self.0;
135        Point3::new(
136            m[0][0].madd(p.x(), m[0][1].madd(p.y(), m[0][2].madd(p.z(), m[0][3]))),
137            m[1][0].madd(p.x(), m[1][1].madd(p.y(), m[1][2].madd(p.z(), m[1][3]))),
138            m[2][0].madd(p.x(), m[2][1].madd(p.y(), m[2][2].madd(p.z(), m[2][3]))),
139        )
140    }
141
142    /// Transpose the matrix.
143    #[must_use]
144    pub const fn transpose(self) -> Self {
145        let m = &self.0;
146        Self([
147            [m[0][0], m[1][0], m[2][0], m[3][0]],
148            [m[0][1], m[1][1], m[2][1], m[3][1]],
149            [m[0][2], m[1][2], m[2][2], m[3][2]],
150            [m[0][3], m[1][3], m[2][3], m[3][3]],
151        ])
152    }
153
154    /// Compute the determinant using cofactor expansion along the first row.
155    #[must_use]
156    #[allow(clippy::similar_names)]
157    pub fn determinant(self) -> f64 {
158        let m = &self.0;
159
160        let s0 = m[0][0].madd(m[1][1], -(m[1][0] * m[0][1]));
161        let s1 = m[0][0].madd(m[1][2], -(m[1][0] * m[0][2]));
162        let s2 = m[0][0].madd(m[1][3], -(m[1][0] * m[0][3]));
163        let s3 = m[0][1].madd(m[1][2], -(m[1][1] * m[0][2]));
164        let s4 = m[0][1].madd(m[1][3], -(m[1][1] * m[0][3]));
165        let s5 = m[0][2].madd(m[1][3], -(m[1][2] * m[0][3]));
166
167        let c5 = m[2][2].madd(m[3][3], -(m[3][2] * m[2][3]));
168        let c4 = m[2][1].madd(m[3][3], -(m[3][1] * m[2][3]));
169        let c3 = m[2][1].madd(m[3][2], -(m[3][1] * m[2][2]));
170        let c2 = m[2][0].madd(m[3][3], -(m[3][0] * m[2][3]));
171        let c1 = m[2][0].madd(m[3][2], -(m[3][0] * m[2][2]));
172        let c0 = m[2][0].madd(m[3][1], -(m[3][0] * m[2][1]));
173
174        s0.madd(
175            c5,
176            (-s1).madd(c4, s2.madd(c3, s3.madd(c2, (-s4).madd(c1, s5 * c0)))),
177        )
178    }
179
180    /// Compute the inverse of the matrix using the adjugate method.
181    ///
182    /// # Errors
183    ///
184    /// Returns [`MathError::SingularMatrix`] if the determinant is approximately zero.
185    #[allow(clippy::similar_names)]
186    pub fn inverse(self) -> Result<Self, MathError> {
187        let m = &self.0;
188
189        // Reuse the 2x2 minor pattern from determinant().
190        let s0 = m[0][0].madd(m[1][1], -(m[1][0] * m[0][1]));
191        let s1 = m[0][0].madd(m[1][2], -(m[1][0] * m[0][2]));
192        let s2 = m[0][0].madd(m[1][3], -(m[1][0] * m[0][3]));
193        let s3 = m[0][1].madd(m[1][2], -(m[1][1] * m[0][2]));
194        let s4 = m[0][1].madd(m[1][3], -(m[1][1] * m[0][3]));
195        let s5 = m[0][2].madd(m[1][3], -(m[1][2] * m[0][3]));
196
197        let c5 = m[2][2].madd(m[3][3], -(m[3][2] * m[2][3]));
198        let c4 = m[2][1].madd(m[3][3], -(m[3][1] * m[2][3]));
199        let c3 = m[2][1].madd(m[3][2], -(m[3][1] * m[2][2]));
200        let c2 = m[2][0].madd(m[3][3], -(m[3][0] * m[2][3]));
201        let c1 = m[2][0].madd(m[3][2], -(m[3][0] * m[2][2]));
202        let c0 = m[2][0].madd(m[3][1], -(m[3][0] * m[2][1]));
203
204        let det = s0.madd(
205            c5,
206            (-s1).madd(c4, s2.madd(c3, s3.madd(c2, (-s4).madd(c1, s5 * c0)))),
207        );
208
209        // Scale-relative singularity check.  The determinant is computed as a
210        // sum of products s_i * c_j of 2x2 minors, so its magnitude scales as
211        // max_minor^2.  Comparing against that avoids the false-singular
212        // problem that a hardcoded threshold (1e-15) causes when matrix entries
213        // are very small or very large.
214        let max_minor = s0
215            .abs()
216            .max(s1.abs())
217            .max(s2.abs())
218            .max(s3.abs())
219            .max(s4.abs())
220            .max(s5.abs())
221            .max(c0.abs())
222            .max(c1.abs())
223            .max(c2.abs())
224            .max(c3.abs())
225            .max(c4.abs())
226            .max(c5.abs());
227        if max_minor == 0.0 {
228            return Err(MathError::SingularMatrix);
229        }
230        if det.abs() < f64::EPSILON * max_minor * max_minor {
231            return Err(MathError::SingularMatrix);
232        }
233
234        let inv_det = 1.0 / det;
235
236        Ok(Self([
237            [
238                m[1][1].madd(c5, m[1][3].madd(c3, -(m[1][2] * c4))) * inv_det,
239                (-m[0][1]).madd(c5, m[0][2].madd(c4, -(m[0][3] * c3))) * inv_det,
240                m[3][1].madd(s5, m[3][3].madd(s3, -(m[3][2] * s4))) * inv_det,
241                (-m[2][1]).madd(s5, m[2][2].madd(s4, -(m[2][3] * s3))) * inv_det,
242            ],
243            [
244                (-m[1][0]).madd(c5, m[1][2].madd(c2, -(m[1][3] * c1))) * inv_det,
245                m[0][0].madd(c5, m[0][3].madd(c1, -(m[0][2] * c2))) * inv_det,
246                (-m[3][0]).madd(s5, m[3][2].madd(s2, -(m[3][3] * s1))) * inv_det,
247                m[2][0].madd(s5, m[2][3].madd(s1, -(m[2][2] * s2))) * inv_det,
248            ],
249            [
250                m[1][0].madd(c4, m[1][3].madd(c0, -(m[1][1] * c2))) * inv_det,
251                (-m[0][0]).madd(c4, m[0][1].madd(c2, -(m[0][3] * c0))) * inv_det,
252                m[3][0].madd(s4, m[3][3].madd(s0, -(m[3][1] * s2))) * inv_det,
253                (-m[2][0]).madd(s4, m[2][1].madd(s2, -(m[2][3] * s0))) * inv_det,
254            ],
255            [
256                (-m[1][0]).madd(c3, m[1][1].madd(c1, -(m[1][2] * c0))) * inv_det,
257                m[0][0].madd(c3, m[0][2].madd(c0, -(m[0][1] * c1))) * inv_det,
258                (-m[3][0]).madd(s3, m[3][1].madd(s1, -(m[3][2] * s0))) * inv_det,
259                m[2][0].madd(s3, m[2][2].madd(s0, -(m[2][1] * s1))) * inv_det,
260            ],
261        ]))
262    }
263}
264
265impl Mul for Mat4 {
266    type Output = Self;
267
268    fn mul(self, rhs: Self) -> Self {
269        let a = &self.0;
270        let b = &rhs.0;
271        let mut out = [[0.0_f64; 4]; 4];
272        for i in 0..4 {
273            for j in 0..4 {
274                out[i][j] = a[i][0].madd(
275                    b[0][j],
276                    a[i][1].madd(b[1][j], a[i][2].madd(b[2][j], a[i][3] * b[3][j])),
277                );
278            }
279        }
280        Self(out)
281    }
282}
283
284#[cfg(test)]
285#[allow(clippy::expect_used)]
286mod tests {
287    use super::*;
288
289    fn approx_eq_mat4(a: &Mat4, b: &Mat4, tol: f64) -> bool {
290        for i in 0..4 {
291            for j in 0..4 {
292                if (a.0[i][j] - b.0[i][j]).abs() > tol {
293                    return false;
294                }
295            }
296        }
297        true
298    }
299
300    #[test]
301    fn identity_inverse() {
302        let inv = Mat4::identity().inverse().expect("invertible");
303        assert!(approx_eq_mat4(&inv, &Mat4::identity(), 1e-14));
304    }
305
306    #[test]
307    fn translation_inverse() {
308        let m = Mat4::translation(1.0, 2.0, 3.0);
309        let inv = m.inverse().expect("invertible");
310        let product = m * inv;
311        assert!(approx_eq_mat4(&product, &Mat4::identity(), 1e-12));
312    }
313
314    #[test]
315    fn rotation_inverse() {
316        let m = Mat4::rotation_x(0.7) * Mat4::rotation_y(1.2) * Mat4::rotation_z(0.3);
317        let inv = m.inverse().expect("invertible");
318        let product = m * inv;
319        assert!(approx_eq_mat4(&product, &Mat4::identity(), 1e-12));
320    }
321
322    #[test]
323    fn scale_inverse() {
324        let m = Mat4::scale(2.0, 3.0, 4.0);
325        let inv = m.inverse().expect("invertible");
326        let product = m * inv;
327        assert!(approx_eq_mat4(&product, &Mat4::identity(), 1e-12));
328    }
329
330    #[test]
331    fn singular_matrix() {
332        let m = Mat4([[1.0, 0.0, 0.0, 0.0]; 4]);
333        assert!(m.inverse().is_err());
334    }
335
336    #[test]
337    fn combined_transform_inverse() {
338        let m = Mat4::translation(5.0, -3.0, 2.0)
339            * Mat4::rotation_z(std::f64::consts::FRAC_PI_4)
340            * Mat4::scale(2.0, 0.5, 1.0);
341        let inv = m.inverse().expect("invertible");
342        let product = m * inv;
343        assert!(approx_eq_mat4(&product, &Mat4::identity(), 1e-10));
344    }
345
346    use proptest::prelude::*;
347
348    proptest! {
349        #[test]
350        fn prop_inverse_roundtrip(
351            tx in -10.0f64..10.0,
352            ty in -10.0f64..10.0,
353            tz in -10.0f64..10.0,
354            angle in 0.0f64..std::f64::consts::TAU,
355        ) {
356            let m = Mat4::translation(tx, ty, tz) * Mat4::rotation_z(angle);
357            let inv = m.inverse().expect("invertible");
358            let product = m * inv;
359            prop_assert!(approx_eq_mat4(&product, &Mat4::identity(), 1e-10));
360        }
361
362        /// Verify that inverse works for matrices with small and large entry
363        /// magnitudes (the old hardcoded 1e-15 threshold would reject these).
364        #[test]
365        fn prop_inverse_scaled(
366            tx in -10.0f64..10.0,
367            ty in -10.0f64..10.0,
368            tz in -10.0f64..10.0,
369            angle in 0.0f64..std::f64::consts::TAU,
370            scale_exp in prop::sample::select(&[-8_i32, -6, -4, -2, 2, 4, 6][..]),
371        ) {
372            let scale = 10.0_f64.powi(scale_exp);
373            let m = Mat4::translation(tx * scale, ty * scale, tz * scale)
374                * Mat4::rotation_z(angle)
375                * Mat4::scale(scale, scale, scale);
376            let inv = m.inverse().expect("invertible");
377            let product = m * inv;
378            // Tolerance scales with condition number; 1e-6 is generous enough
379            // for the range of scales we test.
380            prop_assert!(approx_eq_mat4(&product, &Mat4::identity(), 1e-6));
381        }
382    }
383}