Skip to main content

oa/core/
transform.rs

1//! Semantic local spatial transform value.
2//!
3//! [`Transform`] owns affine placement — translation, rotation, scale, and
4//! optional row-basis shear. It is the universal placement primitive composed
5//! by cameras, scene nodes, lights, joints, and any other type that exists in
6//! 3D space.
7//!
8//! All stateless operations live as free functions in this module (`FnTransform`
9//! in the C++ donor collapses into module functions per the Rust porting rule).
10//!
11//! Donor: `oacpp/source/cpp/include/oa/core/transform.h` and
12//! `oacpp/source/cpp/include/oa/core/fnTransform.h`.
13//! Adaptation: C++ static-method namespace → module functions; `setMatrix` /
14//! `getMatrix` become `set_matrix` / `get_matrix`; six-D rotation helpers are
15//! module-level free functions.
16
17use crate::{
18	Error, Result,
19	vlm::{INVERSE_TOLERANCE, Mat4, Quat, RotationOrder, Vec3},
20};
21
22// ── Transform ─────────────────────────────────────────────────────────────────
23
24/// Semantic local spatial transform value.
25///
26/// Stores translation + unit-quaternion rotation + per-axis scale + optional
27/// dimensionless row-basis shear (XY, XZ, YZ). All constructed values are
28/// finite; operations that would produce a non-finite result leave the value
29/// unchanged and return an error.
30///
31/// Donor: `oa::Transform`.
32#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct Transform {
34	translation: Vec3,
35	rotation: Quat,
36	scale: Vec3,
37	/// Dimensionless row-basis shear factors: XY, XZ, and YZ.
38	shear: Vec3,
39}
40
41impl Default for Transform {
42	/// Identity transform: zero translation, identity rotation, unit scale, no shear.
43	fn default() -> Self {
44		Self {
45			translation: Vec3::default(),
46			rotation: Quat::identity(),
47			scale: Vec3 {
48				x: 1.0,
49				y: 1.0,
50				z: 1.0,
51			},
52			shear: Vec3::default(),
53		}
54	}
55}
56
57impl Transform {
58	/// Construct from explicit components.
59	///
60	/// `rotation` is normalized on construction. `scale` must be non-zero on
61	/// each axis for the transform to be invertible, but construction does not
62	/// enforce this.
63	pub fn new(translation: Vec3, rotation: Quat, scale: Vec3, shear: Vec3) -> Self {
64		Self {
65			translation,
66			rotation: rotation.try_normalized().unwrap_or(Quat::identity()),
67			scale,
68			shear,
69		}
70	}
71
72	// ── Setters ───────────────────────────────────────────────────────────────
73
74	/// Set the translation component.
75	pub fn set_position(&mut self, position: Vec3) {
76		self.translation = position;
77	}
78
79	/// Set the rotation component. The quaternion is normalized.
80	pub fn set_rotation(&mut self, rotation: Quat) {
81		self.rotation = rotation.try_normalized().unwrap_or(Quat::identity());
82	}
83
84	/// Set the per-axis scale.
85	pub fn set_scale(&mut self, scale: Vec3) {
86		self.scale = scale;
87	}
88
89	/// Set the row-basis shear (XY, XZ, YZ).
90	pub fn set_shear(&mut self, shear: Vec3) {
91		self.shear = shear;
92	}
93
94	// ── Getters ───────────────────────────────────────────────────────────────
95
96	/// Return the translation.
97	pub const fn position(&self) -> Vec3 {
98		self.translation
99	}
100
101	/// Return the rotation quaternion (always normalized).
102	pub const fn rotation(&self) -> Quat {
103		self.rotation
104	}
105
106	/// Return the per-axis scale.
107	pub const fn scale(&self) -> Vec3 {
108		self.scale
109	}
110
111	/// Return the row-basis shear (XY, XZ, YZ).
112	pub const fn shear(&self) -> Vec3 {
113		self.shear
114	}
115
116	// ── Derived directions (OA: camera-forward = -Z) ──────────────────────────
117
118	/// Return the local forward vector (-Z in world space).
119	pub fn forward(&self) -> Vec3 {
120		let neg_z = Vec3 {
121			x: 0.0,
122			y: 0.0,
123			z: -1.0,
124		};
125		self.rotation.try_rotate(neg_z).unwrap_or(neg_z)
126	}
127
128	/// Return the local right vector (+X in world space).
129	pub fn right(&self) -> Vec3 {
130		let pos_x = Vec3 {
131			x: 1.0,
132			y: 0.0,
133			z: 0.0,
134		};
135		self.rotation.try_rotate(pos_x).unwrap_or(pos_x)
136	}
137
138	/// Return the local up vector (+Y in world space).
139	pub fn up(&self) -> Vec3 {
140		let pos_y = Vec3 {
141			x: 0.0,
142			y: 1.0,
143			z: 0.0,
144		};
145		self.rotation.try_rotate(pos_y).unwrap_or(pos_y)
146	}
147
148	// ── Rotation helpers ──────────────────────────────────────────────────────
149
150	/// Orient the transform to look toward `target` with the given `world_up`.
151	///
152	/// When `target` equals the current position or `world_up` is degenerate the
153	/// rotation is left unchanged.
154	pub fn look_at(&mut self, target: Vec3, world_up: Vec3) {
155		if let Some(q) = quat_look_at(self.translation, target, world_up) {
156			self.rotation = q;
157		}
158	}
159
160	/// Set rotation from Euler angles in degrees using `order`.
161	///
162	/// Leaves the rotation unchanged on non-finite or degenerate input.
163	pub fn set_rotation_degrees(&mut self, degrees: Vec3, order: RotationOrder) {
164		if let Some(q) = Quat::try_from_euler_degrees(degrees, order) {
165			self.rotation = q;
166		}
167	}
168
169	/// Return the current rotation as Euler angles in degrees using `order`.
170	///
171	/// Returns `Vec3::default()` when the quaternion is degenerate.
172	pub fn rotation_degrees(&self, order: RotationOrder) -> Vec3 {
173		self
174			.rotation
175			.try_to_euler_degrees(order)
176			.unwrap_or_default()
177	}
178
179	/// Translate in local space: `right` × local-right + `up` × local-up +
180	/// `forward` × local-forward.
181	pub fn pan_local(&mut self, right: f32, up: f32, forward: f32) {
182		let r = self.right();
183		let u = self.up();
184		let f = self.forward();
185		self.translation.x += r.x * right + u.x * up + f.x * forward;
186		self.translation.y += r.y * right + u.y * up + f.y * forward;
187		self.translation.z += r.z * right + u.z * up + f.z * forward;
188	}
189
190	// ── Matrix conversion ─────────────────────────────────────────────────────
191
192	/// Compute the row-vector TRS+shear matrix.
193	///
194	/// The matrix is: S × Shear × R × T (row-major, row-vector convention).
195	/// Returns [`Mat4::identity`] for a default transform.
196	pub fn get_matrix(&self) -> Mat4 {
197		trs_shear_to_mat4(self.translation, self.rotation, self.scale, self.shear)
198	}
199
200	/// Decompose a finite non-singular affine matrix into this transform.
201	///
202	/// Leaves the transform unchanged on failure.
203	///
204	/// # Errors
205	///
206	/// Returns an error when `matrix` is non-finite, singular, or the
207	/// decomposed quaternion is degenerate.
208	pub fn set_matrix(&mut self, matrix: Mat4) -> Result<()> {
209		if !matrix.is_finite() {
210			return Err(Error::invalid_argument(
211				"core::Transform::set_matrix requires a finite matrix",
212			));
213		}
214		let d = matrix
215			.try_decompose_affine(INVERSE_TOLERANCE)
216			.ok_or_else(|| {
217				Error::invalid_argument("core::Transform::set_matrix requires a non-singular affine matrix")
218			})?;
219		let rotation = d.rotation.try_normalized().ok_or_else(|| {
220			Error::invalid_argument(
221				"core::Transform::set_matrix produced a degenerate rotation quaternion",
222			)
223		})?;
224		self.translation = d.translation;
225		self.rotation = rotation;
226		self.scale = d.scale;
227		self.shear = d.shear;
228		Ok(())
229	}
230
231	// ── Validation ────────────────────────────────────────────────────────────
232
233	/// Return `true` when all components are finite and the rotation is
234	/// normalizable.
235	pub fn is_finite(&self) -> bool {
236		self.translation.is_finite()
237			&& self.rotation.is_finite()
238			&& self.scale.is_finite()
239			&& self.shear.is_finite()
240			&& self.rotation.try_normalized().is_some()
241	}
242
243	/// Validate that all components are finite and well-formed.
244	///
245	/// # Errors
246	///
247	/// Returns an error for non-finite components or a degenerate rotation.
248	pub fn validate(&self) -> Result<()> {
249		if !self.is_finite() {
250			return Err(Error::invalid_argument(
251				"core::Transform components must be finite and the rotation must be normalizable",
252			));
253		}
254		Ok(())
255	}
256}
257
258// ── Six-D rotation helpers ─────────────────────────────────────────────────────
259
260/// Pack a unit quaternion into a 6-component continuous rotation representation.
261///
262/// The first two columns of the rotation matrix (rows in row-vector convention)
263/// are stored as `[r0x, r0y, r0z, r1x, r1y, r1z]`. The third column is
264/// recovered by the cross product at decode time.
265///
266/// Donor: `oa::FnTransform::quaternionToSixD`.
267pub fn quaternion_to_six_d(q: Quat) -> [f32; 6] {
268	// Derive the rotation matrix's first two basis vectors from the quaternion.
269	let r = Vec3 {
270		x: 1.0,
271		y: 0.0,
272		z: 0.0,
273	};
274	let u = Vec3 {
275		x: 0.0,
276		y: 1.0,
277		z: 0.0,
278	};
279	let col0 = q.try_rotate(r).unwrap_or(r);
280	let col1 = q.try_rotate(u).unwrap_or(u);
281	[col0.x, col0.y, col0.z, col1.x, col1.y, col1.z]
282}
283
284/// Recover a unit quaternion from a 6-component rotation representation.
285///
286/// Donor: `oa::FnTransform::quaternionFromSixD`.
287pub fn quaternion_from_six_d(d: [f32; 6]) -> Quat {
288	// Reconstruct a3 orthonormal basis and extract the quaternion.
289	let a0 = Vec3 {
290		x: d[0],
291		y: d[1],
292		z: d[2],
293	};
294	let a1 = Vec3 {
295		x: d[3],
296		y: d[4],
297		z: d[5],
298	};
299	let Some(b0) = a0.try_normalized() else {
300		return Quat::identity();
301	};
302	// Gram-Schmidt: make b1 orthogonal to b0.
303	let dot = b0.dot(a1);
304	let a1_orth = Vec3 {
305		x: a1.x - b0.x * dot,
306		y: a1.y - b0.y * dot,
307		z: a1.z - b0.z * dot,
308	};
309	let Some(b1) = a1_orth.try_normalized() else {
310		return Quat::identity();
311	};
312	let b2 = b0.cross(b1);
313
314	// Build a row-vector rotation matrix (rows = basis vectors) and extract
315	// the quaternion via the Shepperd method.
316	quat_from_rotation_rows(b0, b1, b2)
317}
318
319// ── Private helpers ───────────────────────────────────────────────────────────
320
321/// Build the row-major TRS+shear matrix from components.
322///
323/// Row-vector convention (same as OA VLM): a point is multiplied on the left:
324/// `p' = p * M`.
325///
326/// The construction matches OA's column ordering:
327/// - Row 0: right (scaled + sheared)
328/// - Row 1: up    (scaled + sheared)
329/// - Row 2: forward (scaled)
330/// - Row 3: translation (homogeneous W=1)
331fn trs_shear_to_mat4(t: Vec3, q: Quat, s: Vec3, shear: Vec3) -> Mat4 {
332	// Rotation matrix rows from quaternion.
333	let unit = q.try_normalized().unwrap_or(Quat::identity());
334	let r0 = unit
335		.try_rotate(Vec3 {
336			x: 1.0,
337			y: 0.0,
338			z: 0.0,
339		})
340		.unwrap_or(Vec3 {
341			x: 1.0,
342			y: 0.0,
343			z: 0.0,
344		});
345	let r1 = unit
346		.try_rotate(Vec3 {
347			x: 0.0,
348			y: 1.0,
349			z: 0.0,
350		})
351		.unwrap_or(Vec3 {
352			x: 0.0,
353			y: 1.0,
354			z: 0.0,
355		});
356	let r2 = unit
357		.try_rotate(Vec3 {
358			x: 0.0,
359			y: 0.0,
360			z: 1.0,
361		})
362		.unwrap_or(Vec3 {
363			x: 0.0,
364			y: 0.0,
365			z: 1.0,
366		});
367
368	// Apply scale then shear to the rotation rows.
369	// Shear (XY, XZ, YZ): row-0 += shear.x * row-1 + shear.y * row-2,
370	//                      row-1 += shear.z * row-2.
371	let sx = s.x;
372	let sy = s.y;
373	let sz = s.z;
374	let sxy = shear.x;
375	let sxz = shear.y;
376	let syz = shear.z;
377
378	let row0 = Vec3 {
379		x: r0.x * sx + r1.x * sy * sxy + r2.x * sz * sxz,
380		y: r0.y * sx + r1.y * sy * sxy + r2.y * sz * sxz,
381		z: r0.z * sx + r1.z * sy * sxy + r2.z * sz * sxz,
382	};
383	let row1 = Vec3 {
384		x: r1.x * sy + r2.x * sz * syz,
385		y: r1.y * sy + r2.y * sz * syz,
386		z: r1.z * sy + r2.z * sz * syz,
387	};
388	let row2 = Vec3 {
389		x: r2.x * sz,
390		y: r2.y * sz,
391		z: r2.z * sz,
392	};
393
394	Mat4 {
395		m: [
396			[row0.x, row0.y, row0.z, 0.0],
397			[row1.x, row1.y, row1.z, 0.0],
398			[row2.x, row2.y, row2.z, 0.0],
399			[t.x, t.y, t.z, 1.0],
400		],
401	}
402}
403
404/// Compute a look-at rotation quaternion from `eye` toward `target` with
405/// `world_up`. Returns `None` when degenerate.
406fn quat_look_at(eye: Vec3, target: Vec3, world_up: Vec3) -> Option<Quat> {
407	let f = (target - eye).try_normalized()?;
408	let r = f.cross(world_up).try_normalized()?;
409	let backward = -f;
410	let u = backward.cross(r);
411	quat_from_rotation_rows(r, u, backward).try_normalized()
412}
413
414/// Extract a quaternion from three orthonormal row-basis vectors (Shepperd).
415fn quat_from_rotation_rows(r: Vec3, u: Vec3, f: Vec3) -> Quat {
416	// The 3×3 rotation matrix in column-major (OpenGL) is:
417	//   [ r.x  u.x  f.x ]
418	//   [ r.y  u.y  f.y ]
419	//   [ r.z  u.z  f.z ]
420	// but OA row-vector means rows ARE the basis vectors:
421	//   m[0] = r, m[1] = u, m[2] = f
422	// Trace = r.x + u.y + f.z
423	let trace = r.x + u.y + f.z;
424	if trace > 0.0 {
425		let s = (trace + 1.0).sqrt() * 2.0; // s = 4w
426		Quat {
427			w: 0.25 * s,
428			x: (f.y - u.z) / s,
429			y: (r.z - f.x) / s,
430			z: (u.x - r.y) / s,
431		}
432	} else if r.x > u.y && r.x > f.z {
433		let s = (1.0 + r.x - u.y - f.z).sqrt() * 2.0; // s = 4x
434		Quat {
435			w: (f.y - u.z) / s,
436			x: 0.25 * s,
437			y: (r.y + u.x) / s,
438			z: (r.z + f.x) / s,
439		}
440	} else if u.y > f.z {
441		let s = (1.0 + u.y - r.x - f.z).sqrt() * 2.0; // s = 4y
442		Quat {
443			w: (r.z - f.x) / s,
444			x: (r.y + u.x) / s,
445			y: 0.25 * s,
446			z: (u.z + f.y) / s,
447		}
448	} else {
449		let s = (1.0 + f.z - r.x - u.y).sqrt() * 2.0; // s = 4z
450		Quat {
451			w: (u.x - r.y) / s,
452			x: (r.z + f.x) / s,
453			y: (u.z + f.y) / s,
454			z: 0.25 * s,
455		}
456	}
457}