ifc_lite_geometry/math/
mat4.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Row-major 4x4 matrices over `[f64; 16]` (`m[r * 4 + c]`), plus exact bridges
6//! to `nalgebra::Matrix4<f64>` and the f32 boundary casts.
7
8use super::v3::V3;
9use nalgebra::Matrix4;
10
11/// A row-major 4x4 matrix.
12pub type M4 = [f64; 16];
13/// A row-major 3x3 matrix.
14pub type M3 = [f64; 9];
15
16/// The determinant magnitude under which [`affine_inverse`] refuses a matrix;
17/// the unit and rationale live with the catalogue in [`super::tol`].
18pub use super::tol::SINGULAR_DET_EPS;
19
20/// The identity.
21pub const IDENTITY: M4 = [
22    1.0, 0.0, 0.0, 0.0, //
23    0.0, 1.0, 0.0, 0.0, //
24    0.0, 0.0, 1.0, 0.0, //
25    0.0, 0.0, 0.0, 1.0, //
26];
27
28/// `a . b`. Each entry accumulates from `0.0` over `k = 0..4`, so an all-zero
29/// dot product is `+0.0`; this is the spelling export, processing, wasm and
30/// the server already share.
31#[inline]
32pub fn mul(a: &M4, b: &M4) -> M4 {
33    let mut out = [0.0f64; 16];
34    for r in 0..4 {
35        for c in 0..4 {
36            let mut s = 0.0;
37            for k in 0..4 {
38                s += a[r * 4 + k] * b[k * 4 + c];
39            }
40            out[r * 4 + c] = s;
41        }
42    }
43    out
44}
45
46/// Column-major frame composition `a * b`, with every zero entry `+0.0`.
47///
48/// Retained receipts compare frames bit for bit, so the controller and both
49/// retained runtimes build an operand's world frame here (#7955). An entry
50/// whose four products are all signed zeros (`0 * -x`, `-x * 0`) has no
51/// meaningful sign: an accumulation seeded with `-0.0` (`Iterator::sum`) kept
52/// it as `-0.0` where this one gives `+0.0` (dental_clinic #831).
53pub fn compose_frame(a: &M4, b: &M4) -> M4 {
54    mul(b, a).map(|value| if value == 0.0 { 0.0 } else { value })
55}
56
57/// `m` applied to the point `p` (translation included; the affine last row is
58/// not read).
59#[inline]
60pub fn transform_point(m: &M4, p: V3) -> V3 {
61    [
62        m[0] * p[0] + m[1] * p[1] + m[2] * p[2] + m[3],
63        m[4] * p[0] + m[5] * p[1] + m[6] * p[2] + m[7],
64        m[8] * p[0] + m[9] * p[1] + m[10] * p[2] + m[11],
65    ]
66}
67
68/// The linear part of `m` applied to `v` (no translation).
69///
70/// On a **column-major** array this computes `Mᵀ·v`: the ROWS of the row-major
71/// reading are the COLUMNS of the matrix. That identity is how the site-local
72/// frame applies an inverse rotation with the same op order.
73#[inline]
74pub fn transform_vector(m: &M4, v: V3) -> V3 {
75    [
76        m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
77        m[4] * v[0] + m[5] * v[1] + m[6] * v[2],
78        m[8] * v[0] + m[9] * v[1] + m[10] * v[2],
79    ]
80}
81
82/// The 3x3 `r` applied to `v`.
83#[inline]
84pub fn apply3(r: &M3, v: V3) -> V3 {
85    [
86        r[0] * v[0] + r[1] * v[1] + r[2] * v[2],
87        r[3] * v[0] + r[4] * v[1] + r[5] * v[2],
88        r[6] * v[0] + r[7] * v[1] + r[8] * v[2],
89    ]
90}
91
92/// Swap rows and columns. Moves values only, so it is exact (and sign-of-zero
93/// preserving).
94#[inline]
95pub fn transpose(m: &M4) -> M4 {
96    [
97        m[0], m[4], m[8], m[12], //
98        m[1], m[5], m[9], m[13], //
99        m[2], m[6], m[10], m[14], //
100        m[3], m[7], m[11], m[15],
101    ]
102}
103
104/// A pure translation by `t`.
105#[inline]
106pub fn translation(t: V3) -> M4 {
107    [
108        1.0, 0.0, 0.0, t[0], //
109        0.0, 1.0, 0.0, t[1], //
110        0.0, 0.0, 1.0, t[2], //
111        0.0, 0.0, 0.0, 1.0,
112    ]
113}
114
115/// Inverse of an AFFINE row-major matrix (last row `[0,0,0,1]`, which is not
116/// read): the upper 3x3 by cofactors, the translation by `-R⁻¹·t`.
117///
118/// `None` when the 3x3 determinant is not finite or `abs(det) <
119/// SINGULAR_DET_EPS`, or when any entry of the inverse is not finite (a NaN or
120/// infinite translation), so a non-finite placement is refused rather than
121/// inverted to NaN.
122#[inline]
123pub fn affine_inverse(m: &M4) -> Option<M4> {
124    let a = m[0]; let b = m[1]; let c = m[2];
125    let d = m[4]; let e = m[5]; let f = m[6];
126    let g = m[8]; let h = m[9]; let i = m[10];
127    let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
128    if !det.is_finite() || det.abs() < SINGULAR_DET_EPS {
129        return None;
130    }
131    let inv_det = 1.0 / det;
132    // Inverse of the 3x3 (row-major) via the transposed cofactor matrix.
133    let r = [
134        (e * i - f * h) * inv_det,
135        (c * h - b * i) * inv_det,
136        (b * f - c * e) * inv_det,
137        (f * g - d * i) * inv_det,
138        (a * i - c * g) * inv_det,
139        (c * d - a * f) * inv_det,
140        (d * h - e * g) * inv_det,
141        (b * g - a * h) * inv_det,
142        (a * e - b * d) * inv_det,
143    ];
144    let (tx, ty, tz) = (m[3], m[7], m[11]);
145    // Translation of the inverse: -R⁻¹ · t.
146    let it = [
147        -(r[0] * tx + r[1] * ty + r[2] * tz),
148        -(r[3] * tx + r[4] * ty + r[5] * tz),
149        -(r[6] * tx + r[7] * ty + r[8] * tz),
150    ];
151    if !r.iter().chain(&it).all(|v| v.is_finite()) {
152        return None;
153    }
154    Some([
155        r[0], r[1], r[2], it[0], //
156        r[3], r[4], r[5], it[1], //
157        r[6], r[7], r[8], it[2], //
158        0.0, 0.0, 0.0, 1.0,
159    ])
160}
161
162/// Row-major f64 to the **column-major** `[f32; 16]` glTF and GPU uploads
163/// expect. The only f64 to f32 point besides [`to_f32`].
164#[inline]
165pub fn to_col_major_f32(m: &M4) -> [f32; 16] {
166    let mut out = [0.0f32; 16];
167    for r in 0..4 {
168        for c in 0..4 {
169            out[c * 4 + r] = m[r * 4 + c] as f32;
170        }
171    }
172    out
173}
174
175/// Elementwise f64 to f32, layout unchanged (row-major stays row-major).
176#[inline]
177pub fn to_f32(m: &M4) -> [f32; 16] {
178    std::array::from_fn(|i| m[i] as f32)
179}
180
181/// nalgebra to row-major (the `InstanceMeta` convention).
182#[inline]
183pub fn from_na(m: &Matrix4<f64>) -> M4 {
184    [
185        m[(0, 0)], m[(0, 1)], m[(0, 2)], m[(0, 3)],
186        m[(1, 0)], m[(1, 1)], m[(1, 2)], m[(1, 3)],
187        m[(2, 0)], m[(2, 1)], m[(2, 2)], m[(2, 3)],
188        m[(3, 0)], m[(3, 1)], m[(3, 2)], m[(3, 3)],
189    ]
190}
191
192/// Row-major to nalgebra. Exact inverse of [`from_na`].
193#[inline]
194pub fn to_na(m: &M4) -> Matrix4<f64> {
195    Matrix4::from_row_slice(m)
196}
197
198/// nalgebra's own **column-major** storage as an array: the layout of the
199/// decoder's placement-transform memo, and bit-for-bit what
200/// `Matrix4::from_column_slice` reads back.
201#[inline]
202pub fn col_major_array(m: &Matrix4<f64>) -> [f64; 16] {
203    *m.as_slice()
204        .first_chunk::<16>()
205        .expect("Matrix4<f64> as_slice is exactly 16 elements")
206}