Skip to main content

rusting_core/
transform.rs

1use nalgebra::{Matrix3, Matrix4, Rotation3, Vector3};
2
3/// Describes where an object is, how it is rotated,
4/// and how large it is.
5///
6/// All arrays use this order:
7/// [x, y, z]
8#[derive(bevy_ecs::component::Component, Copy, Clone, Debug, PartialEq)]
9pub struct Transform {
10    /// Object position in the world:
11    /// [left/right, down/up, backward/forward]
12    pub position: [f32; 3],
13
14    /// Rotation around the X, Y, and Z axes.
15    ///
16    /// IMPORTANT: These values are in radians, not degrees.
17    ///
18    /// rotation[0] = rotation around X
19    /// rotation[1] = rotation around Y
20    /// rotation[2] = rotation around Z
21    pub rotation: [f32; 3],
22
23    /// Object size along each local axis:
24    ///
25    /// scale[0] = size along X
26    /// scale[1] = size along Y
27    /// scale[2] = size along Z
28    ///
29    /// [1.0, 1.0, 1.0] means normal size.
30    /// [2.0, 2.0, 2.0] means twice as large.
31    pub scale: [f32; 3],
32}
33
34impl Default for Transform {
35    fn default() -> Self {
36        Self {
37            // Start at the center of the world.
38            position: [0.0, 0.0, 0.0],
39
40            // No rotation.
41            rotation: [0.0, 0.0, 0.0],
42
43            // Normal size.
44            scale: [1.0, 1.0, 1.0],
45        }
46    }
47}
48
49impl Transform {
50    /// Creates a transform at the given position.
51    ///
52    /// Rotation defaults to zero.
53    /// Scale defaults to one.
54    pub fn new(position: [f32; 3]) -> Self {
55        Self {
56            position,
57            ..Default::default()
58        }
59    }
60
61    pub fn with_position(mut self, x: f32, y: f32, z: f32) -> Self {
62        self.position = [x, y, z];
63        self
64    }
65
66    /// Sets rotation in radians.
67    pub fn with_rotation(mut self, x: f32, y: f32, z: f32) -> Self {
68        self.rotation = [x, y, z];
69        self
70    }
71
72    pub fn with_scale(mut self, x: f32, y: f32, z: f32) -> Self {
73        self.scale = [x, y, z];
74        self
75    }
76
77    /// Combines position, rotation, and scale into one 4×4 matrix.
78    pub fn to_matrix(&self) -> [[f32; 4]; 4] {
79        // Creates this translation matrix:
80        //
81        // ┌                     ┐
82        // │ 1  0  0  position.x │
83        // │ 0  1  0  position.y │
84        // │ 0  0  1  position.z │
85        // │ 0  0  0      1      │
86        // └                     ┘
87        //
88        // It moves the object to its world position.
89        let translation =
90            Matrix4::new_translation(&Vector3::from(self.position));
91
92        // Creates a 3D rotation from:
93        //
94        // rotation[0] = angle around X
95        // rotation[1] = angle around Y
96        // rotation[2] = angle around Z
97        //
98        // to_homogeneous() turns the 3×3 rotation matrix
99        // into a 4×4 matrix.
100        let rotation = Rotation3::from_euler_angles(
101            self.rotation[0],
102            self.rotation[1],
103            self.rotation[2],
104        )
105        .to_homogeneous();
106
107        // Creates this scale matrix:
108        //
109        // ┌                            ┐
110        // │ scale.x    0        0    0 │
111        // │    0    scale.y     0    0 │
112        // │    0       0     scale.z 0 │
113        // │    0       0        0    1 │
114        // └                            ┘
115        let scale = Matrix4::new_nonuniform_scaling(&Vector3::from(self.scale));
116
117        // Transformations are applied from right to left:
118        //
119        // 1. Scale the object
120        // 2. Rotate the object
121        // 3. Move the object
122        let model_matrix = translation * rotation * scale;
123
124        // nalgebra converts the matrix into a column-major array:
125        //
126        // [
127        //     [Xx, Xy, Xz, 0.0], // transformed local X axis
128        //     [Yx, Yy, Yz, 0.0], // transformed local Y axis
129        //     [Zx, Zy, Zz, 0.0], // transformed local Z axis
130        //     [px, py, pz, 1.0], // world position
131        // ]
132        //
133        // Therefore:
134        //
135        // result[0] = object's local X axis
136        // result[1] = object's local Y axis
137        // result[2] = object's local Z axis
138        // result[3] = object's position
139        model_matrix.into()
140    }
141
142    /// Extracts position, rotation, and scale from a 4×4 matrix.
143    ///
144    /// nalgebra indexes matrices as:
145    ///
146    /// m[(row, column)]
147    ///
148    /// The mathematical matrix looks like:
149    ///
150    /// ┌                           ┐
151    /// │ m00  m01  m02  position.x │
152    /// │ m10  m11  m12  position.y │
153    /// │ m20  m21  m22  position.z │
154    /// │  0    0    0       1      │
155    /// └                           ┘
156    pub fn from_matrix(m: Matrix4<f32>) -> Self {
157        // Translation is stored in column 3:
158        //
159        // m[(0, 3)] = X position
160        // m[(1, 3)] = Y position
161        // m[(2, 3)] = Z position
162        let position = [m[(0, 3)], m[(1, 3)], m[(2, 3)]];
163
164        // The first three columns describe the object's
165        // transformed local axes.
166        //
167        // Column 0 = local X direction multiplied by X scale
168        // Column 1 = local Y direction multiplied by Y scale
169        // Column 2 = local Z direction multiplied by Z scale
170        //
171        // The length of each column gives us its scale.
172        let scale = [
173            // Length of column 0: X scale
174            Vector3::new(m[(0, 0)], m[(1, 0)], m[(2, 0)]).norm(),
175            // Length of column 1: Y scale
176            Vector3::new(m[(0, 1)], m[(1, 1)], m[(2, 1)]).norm(),
177            // Length of column 2: Z scale
178            Vector3::new(m[(0, 2)], m[(1, 2)], m[(2, 2)]).norm(),
179        ];
180
181        // Each axis currently contains both rotation and scale.
182        //
183        // Dividing each column by its scale removes the scale,
184        // leaving only the rotation.
185        //
186        // For example:
187        //
188        // m[(0, 0)] / scale[0]
189        //
190        // means:
191        // "world-X part of the local X axis, without X scale."
192        let rotation_matrix = Matrix3::new(
193            // Row 0: how local X, Y, and Z affect world X
194            m[(0, 0)] / scale[0],
195            m[(0, 1)] / scale[1],
196            m[(0, 2)] / scale[2],
197            // Row 1: how local X, Y, and Z affect world Y
198            m[(1, 0)] / scale[0],
199            m[(1, 1)] / scale[1],
200            m[(1, 2)] / scale[2],
201            // Row 2: how local X, Y, and Z affect world Z
202            m[(2, 0)] / scale[0],
203            m[(2, 1)] / scale[1],
204            m[(2, 2)] / scale[2],
205        );
206
207        // Convert the rotation matrix back into:
208        //
209        // rotation.0 = X angle
210        // rotation.1 = Y angle
211        // rotation.2 = Z angle
212        let rotation =
213            Rotation3::from_matrix_unchecked(rotation_matrix).euler_angles();
214
215        Self {
216            position,
217            rotation: [rotation.0, rotation.1, rotation.2],
218            scale,
219        }
220    }
221}