1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use glam::{Mat4, Quat, Vec3};
/// A node transform stored as a 4x4 matrix (column-major order).
///
/// Wraps a `glam::Mat4` in a plain `[[f32; 4]; 4]` so it can cross FFI
/// boundaries; every operation goes through `glam` under the hood.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform {
matrix: [[f32; 4]; 4],
}
impl Transform {
/// Identity transform with no translation, rotation, or scale.
pub const IDENTITY: Self = Self {
matrix: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
};
/// Creates a transform from a column-major matrix array.
pub fn from_matrix(matrix: [[f32; 4]; 4]) -> Self {
Self { matrix }
}
/// Creates a transform from a `glam` matrix.
pub fn from_mat4(mat: Mat4) -> Self {
Self {
matrix: mat.to_cols_array_2d(),
}
}
/// Creates a transform containing only a translation.
pub fn from_translation(translation: Vec3) -> Self {
Self::from_mat4(Mat4::from_translation(translation))
}
/// Creates a transform from scale, rotation, and translation components.
pub fn from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Self {
Self::from_mat4(Mat4::from_scale_rotation_translation(
scale,
rotation,
translation,
))
}
/// Returns the underlying column-major matrix array.
pub fn matrix(&self) -> &[[f32; 4]; 4] {
&self.matrix
}
/// Converts this value into a `glam` matrix.
pub fn to_mat4(&self) -> Mat4 {
Mat4::from_cols_array_2d(&self.matrix)
}
/// Extracts the translation component.
pub fn translation(&self) -> Vec3 {
let (_scale, _rotation, translation) = self.to_scale_rotation_translation();
translation
}
/// Decomposes this transform into scale, rotation, and translation.
pub fn to_scale_rotation_translation(&self) -> (Vec3, Quat, Vec3) {
self.to_mat4().to_scale_rotation_translation()
}
/// Composes this transform with `rhs` using matrix multiplication.
pub fn multiply(self, rhs: Self) -> Self {
Self::from_mat4(self.to_mat4() * rhs.to_mat4())
}
}
impl From<Mat4> for Transform {
fn from(mat: Mat4) -> Self {
Self::from_mat4(mat)
}
}
impl From<Transform> for Mat4 {
fn from(t: Transform) -> Self {
t.to_mat4()
}
}