Skip to main content

oa/anim/
joint.rs

1//! Locked skeletal-joint transform value.
2//!
3//! The matrix contract follows Maya's joint transform semantics while
4//! retaining OA composition: scale/shear, scale orientation (rotateAxis),
5//! animated rotation, joint orientation, optional parent-scale compensation,
6//! translation.
7//!
8//! Donor: `oa/animation/joint.h` and `oa/animation/fnJoint.{h,cpp}`. The
9//! donor's `Joint` methods already forward every behavior to `FnJoint`; the
10//! Rust port keeps the methods as the single implementation and drops the
11//! separate operation namespace.
12
13use crate::{
14	Error, Result,
15	core::Transform,
16	vlm::{AffineDecomposition, Mat4, Quat, RotationOrder, Vec3},
17};
18
19/// Per-axis degrees-of-freedom flags.
20///
21/// Donor: `oa::JointDegreesOfFreedom`.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct JointDegreesOfFreedom {
24	pub x: bool,
25	pub y: bool,
26	pub z: bool,
27}
28
29impl Default for JointDegreesOfFreedom {
30	fn default() -> Self {
31		Self {
32			x: true,
33			y: true,
34			z: true,
35		}
36	}
37}
38
39/// Optional per-axis rotation limits in degrees.
40///
41/// An axis is clamped only when the matching enabled flag is set; enabling
42/// both bounds on an axis requires `minimum <= maximum` on it. Limits are
43/// disabled by default even though [`JointDegreesOfFreedom::default`] is
44/// all-enabled.
45///
46/// Donor: `oa::JointRotationLimits`.
47#[derive(Clone, Copy, Debug, PartialEq)]
48pub struct JointRotationLimits {
49	pub minimum_degrees: Vec3,
50	pub maximum_degrees: Vec3,
51	pub minimum_enabled: JointDegreesOfFreedom,
52	pub maximum_enabled: JointDegreesOfFreedom,
53}
54
55impl Default for JointRotationLimits {
56	fn default() -> Self {
57		Self {
58			minimum_degrees: Vec3::default(),
59			maximum_degrees: Vec3::default(),
60			minimum_enabled: JointDegreesOfFreedom {
61				x: false,
62				y: false,
63				z: false,
64			},
65			maximum_enabled: JointDegreesOfFreedom {
66				x: false,
67				y: false,
68				z: false,
69			},
70		}
71	}
72}
73
74/// Locked skeletal-joint transform value.
75///
76/// Donor: `oa::Joint`. Setters that the donor guards with contract aborts
77/// return `Result` here instead.
78#[derive(Clone, Debug, PartialEq)]
79pub struct Joint {
80	transform: Transform,
81	orientation: Quat,
82	scale_orientation: Quat,
83	segment_scale_compensate: bool,
84	rotation_order: RotationOrder,
85	degrees_of_freedom: JointDegreesOfFreedom,
86	rotation_limits: JointRotationLimits,
87	preferred_angles: Vec3,
88	stiffness: Vec3,
89}
90
91impl Default for Joint {
92	fn default() -> Self {
93		Self {
94			transform: Transform::default(),
95			orientation: Quat::identity(),
96			scale_orientation: Quat::identity(),
97			segment_scale_compensate: true,
98			rotation_order: RotationOrder::Xyz,
99			degrees_of_freedom: JointDegreesOfFreedom::default(),
100			rotation_limits: JointRotationLimits::default(),
101			preferred_angles: Vec3::default(),
102			stiffness: Vec3::default(),
103		}
104	}
105}
106
107impl From<Transform> for Joint {
108	fn from(transform: Transform) -> Self {
109		Self {
110			transform,
111			..Self::default()
112		}
113	}
114}
115
116fn valid_quaternion(value: Quat) -> bool {
117	value.is_finite() && value.norm_squared().is_finite() && value.norm_squared() > 0.0
118}
119
120fn valid_stiffness(value: Vec3) -> bool {
121	value.is_finite() && value.x >= 0.0 && value.y >= 0.0 && value.z >= 0.0
122}
123
124fn valid_limits(limits: &JointRotationLimits) -> bool {
125	if !limits.minimum_degrees.is_finite() || !limits.maximum_degrees.is_finite() {
126		return false;
127	}
128	let x_valid = !(limits.minimum_enabled.x && limits.maximum_enabled.x)
129		|| limits.minimum_degrees.x <= limits.maximum_degrees.x;
130	let y_valid = !(limits.minimum_enabled.y && limits.maximum_enabled.y)
131		|| limits.minimum_degrees.y <= limits.maximum_degrees.y;
132	let z_valid = !(limits.minimum_enabled.z && limits.maximum_enabled.z)
133		|| limits.minimum_degrees.z <= limits.maximum_degrees.z;
134	x_valid && y_valid && z_valid
135}
136
137fn clamp_axis(
138	value: f32,
139	minimum: f32,
140	maximum: f32,
141	minimum_enabled: bool,
142	maximum_enabled: bool,
143) -> f32 {
144	if minimum_enabled && value < minimum {
145		return minimum;
146	}
147	if maximum_enabled && value > maximum {
148		return maximum;
149	}
150	value
151}
152
153impl Joint {
154	/// Validate the complete authoring state.
155	///
156	/// # Errors
157	///
158	/// Returns an error for a non-finite transform or orientation, an
159	/// inverted enabled limit pair, non-finite preferred angles, or
160	/// non-finite/negative stiffness.
161	pub fn validate(&self) -> Result<()> {
162		self.transform.validate()?;
163		if !valid_quaternion(self.orientation) || !valid_quaternion(self.scale_orientation) {
164			return Err(Error::invalid_argument(
165				"Joint orientations must be finite non-zero quaternions",
166			));
167		}
168		if !valid_limits(&self.rotation_limits) {
169			return Err(Error::invalid_argument("Joint rotation limits are invalid"));
170		}
171		if !self.preferred_angles.is_finite() {
172			return Err(Error::invalid_argument(
173				"Joint preferred angles must be finite",
174			));
175		}
176		if !valid_stiffness(self.stiffness) {
177			return Err(Error::invalid_argument(
178				"Joint stiffness must be finite and non-negative",
179			));
180		}
181		Ok(())
182	}
183
184	/// Animated local transform.
185	pub fn transform(&self) -> &Transform {
186		&self.transform
187	}
188
189	/// Mutable access to the animated local transform.
190	pub fn transform_mut(&mut self) -> &mut Transform {
191		&mut self.transform
192	}
193
194	/// Joint orientation (Maya jointOrient); normalized on assignment.
195	///
196	/// # Errors
197	///
198	/// Returns an error for a non-finite or zero quaternion.
199	pub fn set_orientation(&mut self, orientation: Quat) -> Result<()> {
200		if !valid_quaternion(orientation) {
201			return Err(Error::invalid_argument(
202				"Joint orientation must be a finite non-zero quaternion",
203			));
204		}
205		self.orientation = orientation.try_normalized().unwrap_or(orientation);
206		Ok(())
207	}
208
209	/// Stored joint orientation.
210	pub fn orientation(&self) -> Quat {
211		self.orientation
212	}
213
214	/// Scale orientation (Maya rotateAxis); normalized on assignment.
215	///
216	/// # Errors
217	///
218	/// Returns an error for a non-finite or zero quaternion.
219	pub fn set_scale_orientation(&mut self, orientation: Quat) -> Result<()> {
220		if !valid_quaternion(orientation) {
221			return Err(Error::invalid_argument(
222				"Joint scale orientation must be a finite non-zero quaternion",
223			));
224		}
225		self.scale_orientation = orientation.try_normalized().unwrap_or(orientation);
226		Ok(())
227	}
228
229	/// Stored scale orientation.
230	pub fn scale_orientation(&self) -> Quat {
231		self.scale_orientation
232	}
233
234	/// Enable or disable parent-scale compensation.
235	pub fn set_segment_scale_compensate(&mut self, enabled: bool) {
236		self.segment_scale_compensate = enabled;
237	}
238
239	/// Whether parent-scale compensation applies.
240	pub fn segment_scale_compensate(&self) -> bool {
241		self.segment_scale_compensate
242	}
243
244	/// Euler decomposition order retained as metadata.
245	pub fn set_rotation_order(&mut self, order: RotationOrder) {
246		self.rotation_order = order;
247	}
248
249	/// Stored rotation order.
250	pub fn rotation_order(&self) -> RotationOrder {
251		self.rotation_order
252	}
253
254	/// Degrees-of-freedom flags.
255	pub fn set_degrees_of_freedom(&mut self, degrees_of_freedom: JointDegreesOfFreedom) {
256		self.degrees_of_freedom = degrees_of_freedom;
257	}
258
259	/// Stored degrees-of-freedom flags.
260	pub fn degrees_of_freedom(&self) -> JointDegreesOfFreedom {
261		self.degrees_of_freedom
262	}
263
264	/// Rotation limits in degrees.
265	///
266	/// # Errors
267	///
268	/// Returns an error for non-finite bounds or an axis whose enabled
269	/// minimum exceeds its enabled maximum.
270	pub fn set_rotation_limits(&mut self, limits: JointRotationLimits) -> Result<()> {
271		if !valid_limits(&limits) {
272			return Err(Error::invalid_argument("Joint rotation limits are invalid"));
273		}
274		self.rotation_limits = limits;
275		Ok(())
276	}
277
278	/// Stored rotation limits.
279	pub fn rotation_limits(&self) -> JointRotationLimits {
280		self.rotation_limits
281	}
282
283	/// Preferred rest angles in degrees.
284	///
285	/// # Errors
286	///
287	/// Returns an error for non-finite angles.
288	pub fn set_preferred_angles(&mut self, degrees: Vec3) -> Result<()> {
289		if !degrees.is_finite() {
290			return Err(Error::invalid_argument(
291				"Joint preferred angles must be finite",
292			));
293		}
294		self.preferred_angles = degrees;
295		Ok(())
296	}
297
298	/// Stored preferred angles in degrees.
299	pub fn preferred_angles(&self) -> Vec3 {
300		self.preferred_angles
301	}
302
303	/// Per-axis stiffness in `[0, ∞)`.
304	///
305	/// # Errors
306	///
307	/// Returns an error for non-finite or negative stiffness.
308	pub fn set_stiffness(&mut self, stiffness: Vec3) -> Result<()> {
309		if !valid_stiffness(stiffness) {
310			return Err(Error::invalid_argument(
311				"Joint stiffness must be finite and non-negative",
312			));
313		}
314		self.stiffness = stiffness;
315		Ok(())
316	}
317
318	/// Stored stiffness.
319	pub fn stiffness(&self) -> Vec3 {
320		self.stiffness
321	}
322
323	/// Animated rotation expressed in joint orientation space:
324	/// `orientation * transform.rotation`, normalized.
325	pub fn oriented_rotation(&self) -> Quat {
326		(self.orientation * self.transform.rotation())
327			.try_normalized()
328			.unwrap_or_else(Quat::identity)
329	}
330
331	/// Clamp rotation angles in degrees to the enabled limits.
332	///
333	/// # Errors
334	///
335	/// Returns an error for non-finite input.
336	pub fn clamp_rotation_degrees(&self, degrees: Vec3) -> Result<Vec3> {
337		if !degrees.is_finite() {
338			return Err(Error::invalid_argument(
339				"Joint rotation angles must be finite",
340			));
341		}
342		let limits = &self.rotation_limits;
343		Ok(Vec3 {
344			x: clamp_axis(
345				degrees.x,
346				limits.minimum_degrees.x,
347				limits.maximum_degrees.x,
348				limits.minimum_enabled.x,
349				limits.maximum_enabled.x,
350			),
351			y: clamp_axis(
352				degrees.y,
353				limits.minimum_degrees.y,
354				limits.maximum_degrees.y,
355				limits.minimum_enabled.y,
356				limits.maximum_enabled.y,
357			),
358			z: clamp_axis(
359				degrees.z,
360				limits.minimum_degrees.z,
361				limits.maximum_degrees.z,
362				limits.minimum_enabled.z,
363				limits.maximum_enabled.z,
364			),
365		})
366	}
367
368	/// Compose the joint matrix in Maya factor order:
369	/// `S*Shear * SO * R * O * P^-1 * T` under the row-vector convention.
370	///
371	/// When segment-scale compensation is enabled, `parent_scale` must be
372	/// finite and non-zero on every axis.
373	///
374	/// # Errors
375	///
376	/// Returns an error when the joint state is invalid, `parent_scale` is
377	/// non-finite, or compensation needs a zero parent-scale axis.
378	pub fn matrix(&self, parent_scale: Vec3) -> Result<Mat4> {
379		self.validate()?;
380		if !parent_scale.is_finite() {
381			return Err(Error::invalid_argument("Joint parent scale must be finite"));
382		}
383		let mut inverse_parent_scale = Vec3 {
384			x: 1.0,
385			y: 1.0,
386			z: 1.0,
387		};
388		if self.segment_scale_compensate {
389			if parent_scale.x == 0.0 || parent_scale.y == 0.0 || parent_scale.z == 0.0 {
390				return Err(Error::invalid_argument(
391					"Joint segment-scale compensation requires non-zero parent scale",
392				));
393			}
394			inverse_parent_scale = Vec3 {
395				x: 1.0 / parent_scale.x,
396				y: 1.0 / parent_scale.y,
397				z: 1.0 / parent_scale.z,
398			};
399		}
400		let scale_and_shear = AffineDecomposition {
401			scale: self.transform.scale(),
402			shear: self.transform.shear(),
403			..AffineDecomposition::default()
404		};
405		let compose = |quat: Quat| {
406			Mat4::try_from_quaternion(quat)
407				.ok_or_else(|| Error::invalid_argument("Joint quaternions must be normalizable"))
408		};
409		Ok(
410			Mat4::compose_affine(scale_and_shear)
411				.ok_or_else(|| Error::invalid_argument("Joint scale/shear must be finite"))?
412				* compose(self.scale_orientation)?
413				* compose(self.transform.rotation())?
414				* compose(self.orientation)?
415				* Mat4::scaling(inverse_parent_scale)
416				* Mat4::translation(self.transform.position()),
417		)
418	}
419}