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 mut 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 // A mirrored matrix (negative determinant) cannot be a rotation
182 // times positive scales, so the mirror goes into the X scale.
183 if m.fixed_view::<3, 3>(0, 0).determinant() < 0.0 {
184 scale[0] = -scale[0];
185 }
186
187 // A zero scale has no direction to recover; dividing by 1 instead
188 // keeps the rotation finite (the zero column stays zero).
189 let divisor = scale.map(|s| if s == 0.0 { 1.0 } else { s });
190
191 // Each axis currently contains both rotation and scale.
192 //
193 // Dividing each column by its scale removes the scale,
194 // leaving only the rotation.
195 //
196 // For example:
197 //
198 // m[(0, 0)] / scale[0]
199 //
200 // means:
201 // "world-X part of the local X axis, without X scale."
202 let rotation_matrix = Matrix3::new(
203 // Row 0: how local X, Y, and Z affect world X
204 m[(0, 0)] / divisor[0],
205 m[(0, 1)] / divisor[1],
206 m[(0, 2)] / divisor[2],
207 // Row 1: how local X, Y, and Z affect world Y
208 m[(1, 0)] / divisor[0],
209 m[(1, 1)] / divisor[1],
210 m[(1, 2)] / divisor[2],
211 // Row 2: how local X, Y, and Z affect world Z
212 m[(2, 0)] / divisor[0],
213 m[(2, 1)] / divisor[1],
214 m[(2, 2)] / divisor[2],
215 );
216
217 // Convert the rotation matrix back into:
218 //
219 // rotation.0 = X angle
220 // rotation.1 = Y angle
221 // rotation.2 = Z angle
222 let rotation =
223 Rotation3::from_matrix_unchecked(rotation_matrix).euler_angles();
224
225 Self {
226 position,
227 rotation: [rotation.0, rotation.1, rotation.2],
228 scale,
229 }
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 fn matrix(t: &Transform) -> Matrix4<f32> {
238 Matrix4::from(t.to_matrix())
239 }
240
241 fn close(a: Matrix4<f32>, b: Matrix4<f32>) -> bool {
242 (a - b).abs().max() < 1e-5
243 }
244
245 #[test]
246 fn transforms_compose_and_decompose_back_to_the_same_matrix() {
247 let cases = [
248 Transform::default(),
249 Transform::new([1.0, -2.0, 3.0]),
250 Transform::new([4.0, 5.0, 6.0])
251 .with_rotation(0.3, -1.1, 2.0)
252 .with_scale(2.0, 0.5, 3.0),
253 // Gimbal lock: the angles come back different, the matrix not.
254 Transform::default().with_rotation(
255 0.4,
256 std::f32::consts::FRAC_PI_2,
257 0.2,
258 ),
259 // Mirrored along one axis.
260 Transform::default()
261 .with_rotation(0.0, 0.7, 0.0)
262 .with_scale(-1.0, 2.0, 1.0),
263 ];
264 for case in cases {
265 let back = Transform::from_matrix(matrix(&case));
266 assert!(
267 close(matrix(&back), matrix(&case)),
268 "{case:?} -> {back:?}"
269 );
270 assert!(back.scale[1] > 0.0 && back.scale[2] > 0.0, "{back:?}");
271 }
272 let plain =
273 Transform::new([1.0, 2.0, 3.0]).with_rotation(0.1, 0.2, 0.3);
274 let back = Transform::from_matrix(matrix(&plain));
275 for (a, b) in back.rotation.iter().zip(plain.rotation) {
276 assert!((a - b).abs() < 1e-5, "{back:?}");
277 }
278
279 // A flattened object keeps finite numbers.
280 let flat = Transform::default()
281 .with_rotation(0.0, 0.5, 0.0)
282 .with_scale(1.0, 0.0, 1.0);
283 let back = Transform::from_matrix(matrix(&flat));
284 assert!(back.rotation.iter().all(|a| a.is_finite()), "{back:?}");
285 assert_eq!(back.scale[1], 0.0);
286
287 // Parent times child: scale, then rotate, then move, child first.
288 let parent = Transform::new([10.0, 0.0, 0.0])
289 .with_rotation(0.0, std::f32::consts::FRAC_PI_2, 0.0)
290 .with_scale(2.0, 2.0, 2.0);
291 let child = Transform::new([1.0, 0.0, 0.0]);
292 let world = matrix(&parent) * matrix(&child);
293 let origin = world.transform_point(&nalgebra::Point3::origin());
294 // The child's +X offset of 1 is doubled and turned to -Z.
295 assert!(
296 (origin - nalgebra::Point3::new(10.0, 0.0, -2.0)).norm() < 1e-5,
297 "{origin}"
298 );
299 let composed = Transform::from_matrix(world);
300 assert!(close(matrix(&composed), world));
301 }
302}