Skip to main content

euv_core/game/engine3d/animation/
impl.rs

1use super::*;
2
3/// Parent accessor for `SkeletonJoint3D`.
4impl SkeletonJoint3D {
5    /// Creates a new `SkeletonJoint3D`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - Joint label.
10    /// - `Option<usize>` - Optional parent joint index.
11    /// - `Transform3D` - Bind-pose local transform.
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Constructed joint record.
16    #[must_use]
17    pub fn new(name: &str, parent: Option<usize>, rest_transform: Transform3D) -> Self {
18        Self {
19            name: name.to_string(),
20            parent,
21            rest_transform,
22        }
23    }
24
25    /// Returns the optional parent joint index.
26    ///
27    /// # Arguments
28    ///
29    /// - `&Self` - Joint reference.
30    ///
31    /// # Returns
32    ///
33    /// - `Option<usize>` - Parent joint index if non-root.
34    #[must_use]
35    pub fn parent_index(&self) -> Option<usize> {
36        let Self { parent, .. } = self;
37        *parent
38    }
39}
40
41/// Keyframe sampling helpers for `JointTrack3D`.
42impl JointTrack3D {
43    /// Creates a new `JointTrack3D` for `joint_index` sorting keyframes by timestamp.
44    ///
45    /// # Arguments
46    ///
47    /// - `usize` - Target joint index.
48    /// - `Vec<Keyframe3D>` - Unsorted or sorted keyframes.
49    ///
50    /// # Returns
51    ///
52    /// - `Self` - Ready animation track.
53    #[must_use]
54    pub fn new(joint_index: usize, mut keyframes: Vec<Keyframe3D>) -> Self {
55        keyframes.sort_by(|alpha_val: &Keyframe3D, blue_val: &Keyframe3D| {
56            alpha_val
57                .get_time_secs()
58                .total_cmp(&blue_val.get_time_secs())
59        });
60        Self {
61            joint_index,
62            keyframes,
63        }
64    }
65
66    /// Samples this track at `time_secs` via O(log K) binary search, linearly interpolating between neighboring keyframes.
67    ///
68    /// # Arguments
69    ///
70    /// - `&Self` - Track reference.
71    /// - `f32` - Evaluation time in seconds.
72    /// - `Transform3D` - Fallback bind-pose transform when track is empty.
73    ///
74    /// # Returns
75    ///
76    /// - `Transform3D` - Interpolated local transform.
77    #[must_use]
78    pub fn sample(&self, time_secs: f32, fallback: Transform3D) -> Transform3D {
79        let keys: &[Keyframe3D] = self.get_keyframes().as_slice();
80        if keys.is_empty() {
81            return fallback;
82        }
83        if keys.len() == 1 || time_secs <= keys[0].get_time_secs() {
84            return keys[0].get_transform();
85        }
86        let last: Keyframe3D = keys[keys.len() - 1];
87        if time_secs >= last.get_time_secs() {
88            return last.get_transform();
89        }
90        let hi: usize = keys
91            .partition_point(|entry_index: &Keyframe3D| entry_index.get_time_secs() <= time_secs);
92        let idx1: usize = hi.clamp(1, keys.len() - 1);
93        let k0: Keyframe3D = keys[idx1 - 1];
94        let k1: Keyframe3D = keys[idx1];
95        let span: f32 = (k1.get_time_secs() - k0.get_time_secs()).max(1e-5);
96        let alpha: f32 = ((time_secs - k0.get_time_secs()) / span).clamp(0.0, 1.0);
97        k0.get_transform().lerp(k1.get_transform(), alpha)
98    }
99}
100
101/// Clip construction and time normalization for `AnimationClip3D`.
102impl AnimationClip3D {
103    /// Creates a new `AnimationClip3D`.
104    ///
105    /// # Arguments
106    ///
107    /// - `&str` - Clip name.
108    /// - `f32` - Total duration in seconds.
109    /// - `bool` - Looping flag.
110    ///
111    /// # Returns
112    ///
113    /// - `Self` - Empty animation clip ready for tracks.
114    #[must_use]
115    pub fn new(name: &str, duration_secs: f32, looping: bool) -> Self {
116        Self {
117            name: name.to_string(),
118            duration_secs: duration_secs.max(1e-4),
119            looping,
120            tracks: Vec::new(),
121        }
122    }
123
124    /// Appends a `JointTrack3D` to this clip and returns `self` for fluent chaining.
125    ///
126    /// # Arguments
127    ///
128    /// - `Self` - Base animation clip.
129    /// - `JointTrack3D` - Joint animation track.
130    ///
131    /// # Returns
132    ///
133    /// - `Self` - Updated animation clip.
134    #[must_use]
135    pub fn with_track(mut self, track: JointTrack3D) -> Self {
136        self.get_mut_tracks().push(track);
137        self
138    }
139
140    /// Normalizes raw playback time into `[0.0, duration_secs]` respecting `looping`.
141    ///
142    /// # Arguments
143    ///
144    /// - `&Self` - Clip reference.
145    /// - `f32` - Unclamped playback time in seconds.
146    ///
147    /// # Returns
148    ///
149    /// - `f32` - Normalized local evaluation timestamp.
150    #[must_use]
151    pub fn normalize_time(&self, time_secs: f32) -> f32 {
152        let dur: f32 = self.get_duration_secs().max(1e-4);
153        if self.get_looping() {
154            time_secs - (time_secs / dur).floor() * dur
155        } else {
156            time_secs.clamp(0.0, dur)
157        }
158    }
159}
160
161/// Hierarchical forward-kinematics solver for `SkeletonRig3D`.
162impl SkeletonRig3D {
163    /// Appends a joint to the skeleton hierarchy and returns its assigned index.
164    ///
165    /// # Arguments
166    ///
167    /// - `&Self` - Mutable skeleton rig.
168    /// - `&str` - Joint label.
169    /// - `Option<usize>` - Optional parent joint index.
170    /// - `Transform3D` - Bind-pose local transform.
171    ///
172    /// # Returns
173    ///
174    /// - `usize` - Assigned joint index.
175    pub fn add_joint(
176        &mut self,
177        name: &str,
178        parent: Option<usize>,
179        rest_transform: Transform3D,
180    ) -> usize {
181        let idx: usize = self.get_joints().len();
182        self.get_mut_joints()
183            .push(SkeletonJoint3D::new(name, parent, rest_transform));
184        idx
185    }
186
187    /// Samples normalized local joint transforms at `time_secs` for `clip` into an existing `SkeletonPoseSnapshot` with zero allocations.
188    ///
189    /// # Arguments
190    ///
191    /// - `&Self` - Skeleton rig reference.
192    /// - `&AnimationClip3D` - Active animation clip.
193    /// - `f32` - Playback timestamp in seconds.
194    /// - `bool` - Whether this sample represents a discontinuous animation cut.
195    /// - `&mut SkeletonPoseSnapshot` - Reusable destination pose snapshot overwritten in place.
196    pub fn sample_pose_snapshot_into(
197        &self,
198        clip: &AnimationClip3D,
199        time_secs: f32,
200        cut: bool,
201        out: &mut SkeletonPoseSnapshot,
202    ) {
203        let blend_factor: f32 = clip.normalize_time(time_secs);
204        let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
205        let locals: &mut Vec<Transform3D> = out.get_mut_joint_transforms();
206        locals.clear();
207        locals.reserve(joints.len());
208        for joint in joints.iter() {
209            locals.push(joint.get_rest_transform());
210        }
211        for track in clip.get_tracks().iter() {
212            let inner_index: usize = track.get_joint_index();
213            if inner_index < locals.len() {
214                locals[inner_index] = track.sample(blend_factor, locals[inner_index]);
215            }
216        }
217        out.set_cut(cut);
218    }
219
220    /// Samples normalized local joint transforms at `time_secs` for `clip` into a `SkeletonPoseSnapshot`.
221    ///
222    /// # Arguments
223    ///
224    /// - `&Self` - Skeleton rig reference.
225    /// - `&AnimationClip3D` - Active animation clip.
226    /// - `f32` - Playback timestamp in seconds.
227    /// - `bool` - Whether this sample represents a discontinuous animation cut.
228    ///
229    /// # Returns
230    ///
231    /// - `SkeletonPoseSnapshot` - Immutable local joint pose snapshot suitable for render-time interpolation.
232    #[must_use]
233    pub fn sample_pose_snapshot(
234        &self,
235        clip: &AnimationClip3D,
236        time_secs: f32,
237        cut: bool,
238    ) -> SkeletonPoseSnapshot {
239        let mut out: SkeletonPoseSnapshot = SkeletonPoseSnapshot::default();
240        self.sample_pose_snapshot_into(clip, time_secs, cut, &mut out);
241        out
242    }
243
244    /// Evaluates hierarchical world-space `Mat4` joint palettes from `pose` into a reusable caller buffer with zero allocations.
245    ///
246    /// # Arguments
247    ///
248    /// - `&Self` - Skeleton rig reference.
249    /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot.
250    /// - `Transform3D` - Root world transform of the animated actor.
251    /// - `&mut Vec<Mat4>` - Reusable output palette buffer cleared and populated in place.
252    pub fn evaluate_world_matrices_into(
253        &self,
254        pose: &SkeletonPoseSnapshot,
255        root_world: Transform3D,
256        out: &mut Vec<Mat4>,
257    ) {
258        let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
259        let locals: &[Transform3D] = pose.get_joint_transforms().as_slice();
260        let root_m: Mat4 = root_world.to_mat4();
261        out.clear();
262        out.reserve(joints.len());
263        for (idx, joint) in joints.iter().enumerate() {
264            let local_tr: Transform3D = locals
265                .get(idx)
266                .copied()
267                .unwrap_or_else(|| joint.get_rest_transform());
268            let local_m: Mat4 = local_tr.to_mat4();
269            let parent_m: Mat4 = match joint.parent_index() {
270                Some(point_val) if point_val < out.len() => out[point_val],
271                _ => root_m,
272            };
273            out.push(parent_m.mul(local_m));
274        }
275    }
276
277    /// Evaluates hierarchical world-space `Mat4` joint palettes from an interpolated `SkeletonPoseSnapshot`.
278    ///
279    /// # Arguments
280    ///
281    /// - `&Self` - Skeleton rig reference.
282    /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot (e.g. interpolated between two fixed steps).
283    /// - `Transform3D` - Interpolated root world transform of the animated actor.
284    ///
285    /// # Returns
286    ///
287    /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
288    #[must_use]
289    pub fn evaluate_world_matrices(
290        &self,
291        pose: &SkeletonPoseSnapshot,
292        root_world: Transform3D,
293    ) -> Vec<Mat4> {
294        let mut world: Vec<Mat4> = Vec::with_capacity(self.get_joints().len());
295        self.evaluate_world_matrices_into(pose, root_world, &mut world);
296        world
297    }
298
299    /// Samples `clip` at `time_secs` and writes world-space `Mat4` joint palettes into reusable scratch buffers with zero allocations.
300    ///
301    /// # Arguments
302    ///
303    /// - `&Self` - Skeleton rig reference.
304    /// - `&AnimationClip3D` - Active animation clip.
305    /// - `f32` - Playback timestamp in seconds.
306    /// - `Transform3D` - Root world transform of the animated actor.
307    /// - `&mut SkeletonPoseSnapshot` - Reusable local pose scratch buffer.
308    /// - `&mut Vec<Mat4>` - Reusable world-matrix output buffer.
309    pub fn sample_world_matrices_into(
310        &self,
311        clip: &AnimationClip3D,
312        time_secs: f32,
313        root_world: Transform3D,
314        pose_scratch: &mut SkeletonPoseSnapshot,
315        out_matrices: &mut Vec<Mat4>,
316    ) {
317        self.sample_pose_snapshot_into(clip, time_secs, false, pose_scratch);
318        self.evaluate_world_matrices_into(pose_scratch, root_world, out_matrices);
319    }
320
321    /// Evaluates hierarchical world-space `Mat4` joint palettes at `time_secs` for `clip`.
322    ///
323    /// # Arguments
324    ///
325    /// - `&Self` - Skeleton rig reference.
326    /// - `&AnimationClip3D` - Active animation clip.
327    /// - `f32` - Playback timestamp in seconds.
328    /// - `Transform3D` - Root world transform of the animated actor.
329    ///
330    /// # Returns
331    ///
332    /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
333    #[must_use]
334    pub fn sample_world_matrices(
335        &self,
336        clip: &AnimationClip3D,
337        time_secs: f32,
338        root_world: Transform3D,
339    ) -> Vec<Mat4> {
340        let pose: SkeletonPoseSnapshot = self.sample_pose_snapshot(clip, time_secs, false);
341        self.evaluate_world_matrices(&pose, root_world)
342    }
343
344    /// Evaluates 4-bone linear-blend vertex skinning from bind-pose vertices and joint palette into `out_vertices` with zero allocations.
345    ///
346    /// # Arguments
347    ///
348    /// - `&[Vertex3D]` - Bind-pose mesh vertices.
349    /// - `&[SkinWeight3D]` - Matching per-vertex joint indices and weights.
350    /// - `&[Mat4]` - World or skinning joint palette matrices.
351    /// - `&mut Vec<Vertex3D>` - Reusable destination skinned vertex buffer overwritten in place.
352    pub fn skin_vertices_into(
353        &self,
354        bind_vertices: &[Vertex3D],
355        skin_weights: &[SkinWeight3D],
356        world_matrices: &[Mat4],
357        out_vertices: &mut Vec<Vertex3D>,
358    ) {
359        let vertex_count: usize = bind_vertices.len().min(skin_weights.len());
360        out_vertices.clear();
361        out_vertices.reserve(vertex_count);
362        if world_matrices.is_empty() {
363            out_vertices.extend_from_slice(&bind_vertices[..vertex_count]);
364            return;
365        }
366        let max_joint: usize = world_matrices.len() - 1;
367        for vertex_idx in 0..vertex_count {
368            let bind_vertex: Vertex3D = bind_vertices[vertex_idx];
369            let bind_pos: Vec3 = bind_vertex.get_position();
370            let bind_normal: Vec3 = bind_vertex.get_normal();
371            let skin: SkinWeight3D = skin_weights[vertex_idx];
372            let indices: [u16; 4] = skin.get_joint_indices();
373            let weights: [f32; 4] = skin.get_weights();
374            let mut skinned_pos: Vec3 = Vec3::zero();
375            let mut skinned_normal: Vec3 = Vec3::zero();
376            let mut weight_sum: f32 = 0.0;
377            for lane in 0..4usize {
378                let bone_weight: f32 = weights[lane];
379                if bone_weight <= 1e-6 {
380                    continue;
381                }
382                let joint_idx: usize = (indices[lane] as usize).min(max_joint);
383                let bone_matrix: Mat4 = world_matrices[joint_idx];
384                skinned_pos = skinned_pos.add(bone_matrix.mul_point3(bind_pos).scale(bone_weight));
385                skinned_normal =
386                    skinned_normal.add(bone_matrix.mul_vec3(bind_normal).scale(bone_weight));
387                weight_sum += bone_weight;
388            }
389            if weight_sum > 1e-5 {
390                let inv_weight: f32 = 1.0 / weight_sum;
391                let final_pos: Vec3 = skinned_pos.scale(inv_weight);
392                let final_normal: Vec3 = if skinned_normal.length_sq() > 1e-8 {
393                    skinned_normal.normalize()
394                } else {
395                    bind_normal
396                };
397                out_vertices.push(Vertex3D::new(final_pos, final_normal));
398            } else {
399                out_vertices.push(bind_vertex);
400            }
401        }
402    }
403}
404
405/// Real armature skinning (LBS and DQS) and pre-skinning morph evaluation for `Skin3D`.
406impl Skin3D {
407    /// Constructs a `Skin3D` directly from an imported glTF/Blender `ImportedSkin3D`.
408    ///
409    /// # Arguments
410    ///
411    /// - `&ImportedSkin3D` - Imported armature skin asset.
412    ///
413    /// # Returns
414    ///
415    /// - `Self` - Runtime skin configured in `SkinningMode::LinearBlend`.
416    #[must_use]
417    pub fn from_imported(imported: &ImportedSkin3D) -> Self {
418        Self {
419            name: imported.get_name().clone(),
420            joints: imported.get_joints().clone(),
421            skeleton_root: imported.try_get_skeleton_root(),
422            inverse_bind_matrices: imported.get_inverse_bind_matrices().clone(),
423            skinning_mode: SkinningMode::LinearBlend,
424        }
425    }
426
427    /// Constructs a `Skin3D` from explicit joint node indices and inverse bind matrices.
428    ///
429    /// # Arguments
430    ///
431    /// - `&str` - Human-readable skin name.
432    /// - `Vec<u32>` - Scene-graph node indices for each bone joint.
433    /// - `Option<u32>` - Optional skeleton root node index.
434    /// - `Vec<Mat4>` - Inverse bind matrices aligned 1:1 with `joints`.
435    ///
436    /// # Returns
437    ///
438    /// - `Self` - Configured armature skin.
439    #[must_use]
440    pub fn new(
441        name: &str,
442        joints: Vec<u32>,
443        skeleton_root: Option<u32>,
444        inverse_bind_matrices: Vec<Mat4>,
445    ) -> Self {
446        Self {
447            name: name.to_string(),
448            joints,
449            skeleton_root,
450            inverse_bind_matrices,
451            skinning_mode: SkinningMode::LinearBlend,
452        }
453    }
454
455    /// Returns a copy of this skin configured with `mode` (`LinearBlend` or `DualQuaternion`).
456    ///
457    /// # Arguments
458    ///
459    /// - `Self` - Base skin descriptor.
460    /// - `SkinningMode` - Desired vertex deformation algorithm.
461    ///
462    /// # Returns
463    ///
464    /// - `Self` - Updated skin descriptor.
465    #[must_use]
466    pub fn with_skinning_mode(mut self, mode: SkinningMode) -> Self {
467        self.set_skinning_mode(mode);
468        self
469    }
470
471    /// Computes exact per-joint skin matrices `inv(M_mesh_world) * M_joint_world[j] * M_inv_bind[j]`, cofactor normal bases, and dual quaternions into `scratch` with zero steady-state allocations.
472    ///
473    /// # Arguments
474    ///
475    /// - `&Self` - Armature skin reference.
476    /// - `Mat4` - World transformation matrix of the skinned mesh node.
477    /// - `&SceneGraph3D` - Propagated hierarchical scene graph supplying current joint world matrices.
478    /// - `&mut SkinPaletteScratch3D` - Reusable scratch arena overwritten in place.
479    pub fn compute_skin_matrices_into(
480        &self,
481        mesh_world_matrix: Mat4,
482        scene_graph: &SceneGraph3D,
483        scratch: &mut SkinPaletteScratch3D,
484    ) {
485        let inv_mesh_world: Mat4 = mesh_world_matrix.inverse().unwrap_or_else(Mat4::identity);
486        let joints: &[u32] = self.get_joints().as_slice();
487        let inv_binds: &[Mat4] = self.get_inverse_bind_matrices().as_slice();
488        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
489        let joint_count: usize = joints.len().min(SKIN_MAX_BONES);
490        let SkinPaletteScratch3D {
491            skin_matrices,
492            skin_normal_matrices,
493            skin_dual_quats,
494            ..
495        } = scratch;
496        skin_matrices.clear();
497        skin_normal_matrices.clear();
498        skin_dual_quats.clear();
499        if skin_matrices.capacity() < joint_count {
500            skin_matrices.reserve(joint_count - skin_matrices.len());
501        }
502        if skin_normal_matrices.capacity() < joint_count {
503            skin_normal_matrices.reserve(joint_count - skin_normal_matrices.len());
504        }
505        if skin_dual_quats.capacity() < joint_count {
506            skin_dual_quats.reserve(joint_count - skin_dual_quats.len());
507        }
508        for (joint_idx, &joint_node_id) in joints.iter().enumerate().take(joint_count) {
509            let node_idx: usize = joint_node_id as usize;
510            let joint_world: Mat4 = nodes
511                .get(node_idx)
512                .map_or_else(Mat4::identity, |node_ref: &SceneNode3D| {
513                    node_ref.get_world_matrix()
514                });
515            let inv_bind: Mat4 = inv_binds
516                .get(joint_idx)
517                .copied()
518                .unwrap_or_else(Mat4::identity);
519            let skin_mat: Mat4 = inv_mesh_world.mul(joint_world).mul(inv_bind);
520            let normal_mat: [Vec3; 3] = skin_mat.normal_matrix_3x3();
521            let (trans_vec, rot_quat, _scale_vec): (Vec3, Quat, Vec3) = skin_mat.decompose_trs();
522            let dual_quat: DualQuat = DualQuat::from_rotation_translation(rot_quat, trans_vec);
523            skin_matrices.push(skin_mat);
524            skin_normal_matrices.push(normal_mat);
525            skin_dual_quats.push(dual_quat);
526        }
527    }
528
529    /// Evaluates 8-bone Linear-Blend Skinning (LBS) over `source_vertices` into `out_vertices` preserving UVs, colors, and tangent handedness.
530    ///
531    /// # Arguments
532    ///
533    /// - `&[Vertex3D]` - Bind-pose or pre-morphed source vertices.
534    /// - `&[MeshSkinInfluence3D]` - Per-vertex 8-bone joint indices and weights.
535    /// - `&[Mat4]` - Precomputed skin palette matrices.
536    /// - `&[[Vec3; 3]]` - Precomputed cofactor 3x3 normal bases aligned with `skin_matrices`.
537    /// - `&mut Vec<Vertex3D>` - Reusable destination vertex buffer populated in place.
538    pub fn skin_vertices_lbs_into(
539        source_vertices: &[Vertex3D],
540        skin_influences: &[MeshSkinInfluence3D],
541        skin_matrices: &[Mat4],
542        skin_normal_matrices: &[[Vec3; 3]],
543        out_vertices: &mut Vec<Vertex3D>,
544    ) {
545        let vert_count: usize = source_vertices.len();
546        out_vertices.clear();
547        if out_vertices.capacity() < vert_count {
548            out_vertices.reserve(vert_count - out_vertices.len());
549        }
550        if skin_matrices.is_empty() || skin_influences.len() < vert_count {
551            out_vertices.extend_from_slice(source_vertices);
552            return;
553        }
554        let max_joint_idx: usize = skin_matrices.len() - 1;
555        for vert_idx in 0..vert_count {
556            let src_vert: Vertex3D = source_vertices[vert_idx];
557            let influence: MeshSkinInfluence3D = skin_influences[vert_idx];
558            let all_joints: [u16; 8] = [
559                influence.get_joints_0()[0],
560                influence.get_joints_0()[1],
561                influence.get_joints_0()[2],
562                influence.get_joints_0()[3],
563                influence.get_joints_1()[0],
564                influence.get_joints_1()[1],
565                influence.get_joints_1()[2],
566                influence.get_joints_1()[3],
567            ];
568            let all_weights: [f32; 8] = [
569                influence.get_weights_0()[0],
570                influence.get_weights_0()[1],
571                influence.get_weights_0()[2],
572                influence.get_weights_0()[3],
573                influence.get_weights_1()[0],
574                influence.get_weights_1()[1],
575                influence.get_weights_1()[2],
576                influence.get_weights_1()[3],
577            ];
578            let src_pos: Vec3 = src_vert.get_position();
579            let src_norm: Vec3 = src_vert.get_normal();
580            let src_tan: [f32; 4] = src_vert.get_tangent();
581            let src_tan_vec: Vec3 = Vec3::new(src_tan[0], src_tan[1], src_tan[2]);
582            let mut accum_pos: Vec3 = Vec3::zero();
583            let mut accum_norm: Vec3 = Vec3::zero();
584            let mut accum_tan: Vec3 = Vec3::zero();
585            let mut weight_sum: f32 = 0.0;
586            for lane_idx in 0..8usize {
587                let bone_weight: f32 = all_weights[lane_idx];
588                if bone_weight.abs() <= SKIN_WEIGHT_EPSILON {
589                    continue;
590                }
591                let joint_slot: usize = (all_joints[lane_idx] as usize).min(max_joint_idx);
592                let bone_mat: Mat4 = skin_matrices[joint_slot];
593                let norm_basis: [Vec3; 3] = skin_normal_matrices[joint_slot];
594                accum_pos = accum_pos.add(bone_mat.mul_point3(src_pos).scale(bone_weight));
595                let transformed_norm: Vec3 =
596                    Mat4::transform_normal_with_basis(src_norm, norm_basis);
597                accum_norm = accum_norm.add(transformed_norm.scale(bone_weight));
598                accum_tan = accum_tan.add(bone_mat.mul_vec3(src_tan_vec).scale(bone_weight));
599                weight_sum += bone_weight;
600            }
601            if weight_sum.abs() > SKIN_WEIGHT_EPSILON {
602                let inv_sum: f32 = 1.0 / weight_sum;
603                let final_pos: Vec3 = accum_pos.scale(inv_sum);
604                let final_norm: Vec3 = if accum_norm.length_sq() > 1.0e-10 {
605                    accum_norm.normalize()
606                } else {
607                    src_norm
608                };
609                let final_tan_vec: Vec3 = if accum_tan.length_sq() > 1.0e-10 {
610                    accum_tan.normalize()
611                } else {
612                    src_tan_vec
613                };
614                out_vertices.push(Vertex3D::from_full(
615                    final_pos,
616                    final_norm,
617                    [
618                        final_tan_vec.get_x(),
619                        final_tan_vec.get_y(),
620                        final_tan_vec.get_z(),
621                        src_tan[3],
622                    ],
623                    src_vert.get_uv0(),
624                    src_vert.get_uv1(),
625                    src_vert.get_color0(),
626                    src_vert.get_flags(),
627                ));
628            } else {
629                out_vertices.push(src_vert);
630            }
631        }
632    }
633
634    /// Evaluates volume-preserving 8-bone Dual-Quaternion Skinning (DQS) over `source_vertices` into `out_vertices`, avoiding candy-wrapper collapse at large twist angles.
635    ///
636    /// # Arguments
637    ///
638    /// - `&[Vertex3D]` - Bind-pose or pre-morphed source vertices.
639    /// - `&[MeshSkinInfluence3D]` - Per-vertex 8-bone joint indices and weights.
640    /// - `&[DualQuat]` - Precomputed bone dual quaternions.
641    /// - `&mut Vec<Vertex3D>` - Reusable destination vertex buffer populated in place.
642    pub fn skin_vertices_dqs_into(
643        source_vertices: &[Vertex3D],
644        skin_influences: &[MeshSkinInfluence3D],
645        skin_dual_quats: &[DualQuat],
646        out_vertices: &mut Vec<Vertex3D>,
647    ) {
648        let vert_count: usize = source_vertices.len();
649        out_vertices.clear();
650        if out_vertices.capacity() < vert_count {
651            out_vertices.reserve(vert_count - out_vertices.len());
652        }
653        if skin_dual_quats.is_empty() || skin_influences.len() < vert_count {
654            out_vertices.extend_from_slice(source_vertices);
655            return;
656        }
657        let max_joint_idx: usize = skin_dual_quats.len() - 1;
658        for vert_idx in 0..vert_count {
659            let src_vert: Vertex3D = source_vertices[vert_idx];
660            let influence: MeshSkinInfluence3D = skin_influences[vert_idx];
661            let all_joints: [u16; 8] = [
662                influence.get_joints_0()[0],
663                influence.get_joints_0()[1],
664                influence.get_joints_0()[2],
665                influence.get_joints_0()[3],
666                influence.get_joints_1()[0],
667                influence.get_joints_1()[1],
668                influence.get_joints_1()[2],
669                influence.get_joints_1()[3],
670            ];
671            let all_weights: [f32; 8] = [
672                influence.get_weights_0()[0],
673                influence.get_weights_0()[1],
674                influence.get_weights_0()[2],
675                influence.get_weights_0()[3],
676                influence.get_weights_1()[0],
677                influence.get_weights_1()[1],
678                influence.get_weights_1()[2],
679                influence.get_weights_1()[3],
680            ];
681            let mut lane_duals: [DualQuat; 8] = [DualQuat::identity(); 8];
682            let mut lane_weights: [f32; 8] = [0.0; 8];
683            let mut active_count: usize = 0;
684            for lane_idx in 0..8usize {
685                let bone_weight: f32 = all_weights[lane_idx];
686                if bone_weight.abs() <= SKIN_WEIGHT_EPSILON {
687                    continue;
688                }
689                let joint_slot: usize = (all_joints[lane_idx] as usize).min(max_joint_idx);
690                lane_duals[active_count] = skin_dual_quats[joint_slot];
691                lane_weights[active_count] = bone_weight;
692                active_count += 1;
693            }
694            if active_count == 0 {
695                out_vertices.push(src_vert);
696                continue;
697            }
698            let blended_dq: DualQuat = DualQuat::blend_weighted(
699                &lane_duals[..active_count],
700                &lane_weights[..active_count],
701            );
702            let final_pos: Vec3 = blended_dq.transform_point(src_vert.get_position());
703            let rot_norm: Vec3 = blended_dq.transform_vector(src_vert.get_normal());
704            let final_norm: Vec3 = if rot_norm.length_sq() > 1.0e-10 {
705                rot_norm.normalize()
706            } else {
707                src_vert.get_normal()
708            };
709            let src_tan: [f32; 4] = src_vert.get_tangent();
710            let rot_tan: Vec3 =
711                blended_dq.transform_vector(Vec3::new(src_tan[0], src_tan[1], src_tan[2]));
712            let final_tan_vec: Vec3 = if rot_tan.length_sq() > 1.0e-10 {
713                rot_tan.normalize()
714            } else {
715                Vec3::new(src_tan[0], src_tan[1], src_tan[2])
716            };
717            out_vertices.push(Vertex3D::from_full(
718                final_pos,
719                final_norm,
720                [
721                    final_tan_vec.get_x(),
722                    final_tan_vec.get_y(),
723                    final_tan_vec.get_z(),
724                    src_tan[3],
725                ],
726                src_vert.get_uv0(),
727                src_vert.get_uv1(),
728                src_vert.get_color0(),
729                src_vert.get_flags(),
730            ));
731        }
732    }
733
734    /// Evaluates Blender's exact modifier order (Shape Keys BEFORE Armature Skinning) for `mesh` into `scratch.skinned_vertices` with zero steady-state allocations.
735    ///
736    /// # Arguments
737    ///
738    /// - `&Self` - Armature skin reference.
739    /// - `&Mesh3D` - Source bind-pose mesh with optional `morph_targets` and `skin_influences`.
740    /// - `&[f32]` - Active shape-key weights for this mesh node.
741    /// - `Mat4` - Current mesh node world matrix.
742    /// - `&SceneGraph3D` - Propagated hierarchical scene graph.
743    /// - `&mut SkinPaletteScratch3D` - Reusable deformation scratch arena.
744    ///
745    /// # Returns
746    ///
747    /// - `bool` - `true` when `scratch.skinned_vertices` was populated with deformed vertices.
748    pub fn deform_mesh_into(
749        &self,
750        mesh: &Mesh3D,
751        morph_weights: &[f32],
752        mesh_world_matrix: Mat4,
753        scene_graph: &SceneGraph3D,
754        scratch: &mut SkinPaletteScratch3D,
755    ) -> bool {
756        let base_vertices: &[Vertex3D] = mesh.get_vertices().as_slice();
757        if base_vertices.is_empty() {
758            scratch.get_mut_skinned_vertices().clear();
759            return false;
760        }
761        let has_morphs: bool = apply_morph_targets_into(
762            base_vertices,
763            mesh.get_morph_targets().as_slice(),
764            morph_weights,
765            scratch.get_mut_morphed_vertices(),
766        );
767        let skin_influences: &[MeshSkinInfluence3D] = mesh.get_skin_influences().as_slice();
768        let has_skinning: bool =
769            !self.get_joints().is_empty() && skin_influences.len() >= base_vertices.len();
770        if !has_skinning {
771            if has_morphs {
772                let SkinPaletteScratch3D {
773                    morphed_vertices,
774                    skinned_vertices,
775                    ..
776                } = scratch;
777                skinned_vertices.clear();
778                if skinned_vertices.capacity() < morphed_vertices.len() {
779                    skinned_vertices.reserve(morphed_vertices.len() - skinned_vertices.len());
780                }
781                skinned_vertices.extend_from_slice(morphed_vertices.as_slice());
782                return true;
783            }
784            return false;
785        }
786        self.compute_skin_matrices_into(mesh_world_matrix, scene_graph, scratch);
787        let SkinPaletteScratch3D {
788            skin_matrices,
789            skin_normal_matrices,
790            skin_dual_quats,
791            morphed_vertices,
792            skinned_vertices,
793        } = scratch;
794        let pre_skin_verts: &[Vertex3D] = if has_morphs {
795            morphed_vertices.as_slice()
796        } else {
797            base_vertices
798        };
799        match self.get_skinning_mode() {
800            SkinningMode::LinearBlend => {
801                Self::skin_vertices_lbs_into(
802                    pre_skin_verts,
803                    skin_influences,
804                    skin_matrices.as_slice(),
805                    skin_normal_matrices.as_slice(),
806                    skinned_vertices,
807                );
808            }
809            SkinningMode::DualQuaternion => {
810                Self::skin_vertices_dqs_into(
811                    pre_skin_verts,
812                    skin_influences,
813                    skin_dual_quats.as_slice(),
814                    skinned_vertices,
815                );
816            }
817        }
818        true
819    }
820}
821
822/// Default playback configuration for `NlaLayer3D`.
823impl Default for NlaLayer3D {
824    /// Returns an enabled looping override layer targeting clip `0` at full weight.
825    ///
826    /// # Returns
827    ///
828    /// - `Self` - Default NLA layer.
829    fn default() -> Self {
830        Self::new(0)
831    }
832}
833
834/// Fluent configuration and crossfade helpers for `NlaLayer3D`.
835impl NlaLayer3D {
836    /// Creates an enabled looping `NlaLayer3D` playing `clip_index` at full weight across all nodes.
837    ///
838    /// # Arguments
839    ///
840    /// - `usize` - Target clip index in `AnimationMixer3D::clips`.
841    ///
842    /// # Returns
843    ///
844    /// - `Self` - Configured NLA layer.
845    #[must_use]
846    pub const fn new(clip_index: usize) -> Self {
847        Self {
848            clip_index,
849            weight: 1.0,
850            blend_mode: NlaBlendMode::Override,
851            repeat_mode: NlaRepeatMode::Loop,
852            time_secs: 0.0,
853            time_scale: 1.0,
854            fade_elapsed_secs: 0.0,
855            fade_duration_secs: 0.0,
856            fade_start_weight: 1.0,
857            fade_target_weight: 1.0,
858            joint_mask: u64::MAX,
859            enabled: true,
860        }
861    }
862
863    /// Sets the initial blend weight clamped to `[0.0, 1.0]`.
864    ///
865    /// # Arguments
866    ///
867    /// - `Self` - Base NLA layer.
868    /// - `f32` - Layer blend weight.
869    ///
870    /// # Returns
871    ///
872    /// - `Self` - Updated NLA layer.
873    #[must_use]
874    pub fn with_weight(mut self, weight: f32) -> Self {
875        let clamped: f32 = weight.clamp(0.0, 1.0);
876        self.set_weight(clamped);
877        self.set_fade_start_weight(clamped);
878        self.set_fade_target_weight(clamped);
879        self
880    }
881
882    /// Sets the composition blend mode (`Override` or `Additive`).
883    ///
884    /// # Arguments
885    ///
886    /// - `Self` - Base NLA layer.
887    /// - `NlaBlendMode` - Blend composition mode.
888    ///
889    /// # Returns
890    ///
891    /// - `Self` - Updated NLA layer.
892    #[must_use]
893    pub fn with_blend_mode(mut self, blend_mode: NlaBlendMode) -> Self {
894        self.set_blend_mode(blend_mode);
895        self
896    }
897
898    /// Sets the playback repeat policy (`Loop`, `Clamp`, or `PingPong`).
899    ///
900    /// # Arguments
901    ///
902    /// - `Self` - Base NLA layer.
903    /// - `NlaRepeatMode` - Playback wrap policy.
904    ///
905    /// # Returns
906    ///
907    /// - `Self` - Updated NLA layer.
908    #[must_use]
909    pub fn with_repeat_mode(mut self, repeat_mode: NlaRepeatMode) -> Self {
910        self.set_repeat_mode(repeat_mode);
911        self
912    }
913
914    /// Sets the playback speed multiplier.
915    ///
916    /// # Arguments
917    ///
918    /// - `Self` - Base NLA layer.
919    /// - `f32` - Time scale multiplier.
920    ///
921    /// # Returns
922    ///
923    /// - `Self` - Updated NLA layer.
924    #[must_use]
925    pub fn with_time_scale(mut self, time_scale: f32) -> Self {
926        self.set_time_scale(time_scale);
927        self
928    }
929
930    /// Restricts this layer to scene nodes matching `joint_mask` (`(1 << (node_id & 63)) & joint_mask != 0`).
931    ///
932    /// # Arguments
933    ///
934    /// - `Self` - Base NLA layer.
935    /// - `u64` - Node eligibility bitmask.
936    ///
937    /// # Returns
938    ///
939    /// - `Self` - Updated NLA layer.
940    #[must_use]
941    pub fn with_joint_mask(mut self, joint_mask: u64) -> Self {
942        self.set_joint_mask(joint_mask);
943        self
944    }
945
946    /// Initiates a smooth linear crossfade from the current layer weight to `target_weight` over `duration_secs`.
947    ///
948    /// # Arguments
949    ///
950    /// - `&Self` - Mutable NLA layer.
951    /// - `f32` - Destination blend weight in `[0.0, 1.0]`.
952    /// - `f32` - Fade duration in seconds (`<= 0.0` snaps immediately).
953    pub fn start_crossfade(&mut self, target_weight: f32, duration_secs: f32) {
954        let clamped_target: f32 = target_weight.clamp(0.0, 1.0);
955        if duration_secs <= ANIM_MIN_SPAN_SECS {
956            self.set_weight(clamped_target);
957            self.set_fade_start_weight(clamped_target);
958            self.set_fade_target_weight(clamped_target);
959            self.set_fade_elapsed_secs(0.0);
960            self.set_fade_duration_secs(0.0);
961            return;
962        }
963        let current_weight: f32 = self.get_weight();
964        self.set_fade_start_weight(current_weight);
965        self.set_fade_target_weight(clamped_target);
966        self.set_fade_elapsed_secs(0.0);
967        self.set_fade_duration_secs(duration_secs);
968    }
969
970    /// Advances this layer's clock and active crossfade envelope by `dt_secs`.
971    ///
972    /// # Arguments
973    ///
974    /// - `&Self` - Mutable NLA layer.
975    /// - `f32` - Elapsed frame delta time in seconds.
976    pub fn advance(&mut self, dt_secs: f32) {
977        if !self.get_enabled() {
978            return;
979        }
980        let safe_dt: f32 = dt_secs.max(0.0);
981        self.set_time_secs(self.get_time_secs() + safe_dt * self.get_time_scale());
982        let fade_dur: f32 = self.get_fade_duration_secs();
983        if fade_dur > ANIM_MIN_SPAN_SECS {
984            let next_elapsed: f32 = (self.get_fade_elapsed_secs() + safe_dt).min(fade_dur);
985            let fade_alpha: f32 = (next_elapsed / fade_dur).clamp(0.0, 1.0);
986            let start_w: f32 = self.get_fade_start_weight();
987            let target_w: f32 = self.get_fade_target_weight();
988            self.set_weight(start_w + (target_w - start_w) * fade_alpha);
989            self.set_fade_elapsed_secs(next_elapsed);
990            if next_elapsed >= fade_dur {
991                self.set_fade_duration_secs(0.0);
992            }
993        }
994    }
995}
996
997/// Multi-layer glTF/NLA animation mixing and zero-allocation scene-graph application for `AnimationMixer3D`.
998impl AnimationMixer3D {
999    /// Captures the current `SceneGraph3D` local transforms and morph weights as the bind/rest pose and pre-reserves scratch buffers.
1000    ///
1001    /// # Arguments
1002    ///
1003    /// - `&Self` - Mutable animation mixer.
1004    /// - `&SceneGraph3D` - Scene graph in its rest pose.
1005    pub fn capture_rest_pose(&mut self, scene_graph: &SceneGraph3D) {
1006        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
1007        let node_count: usize = nodes.len();
1008        let morph_slice: &[f32] = scene_graph.get_morph_weights().as_slice();
1009        let AnimationMixer3D {
1010            pose_scratch,
1011            rest_translations,
1012            rest_rotations,
1013            rest_scales,
1014            rest_morph_weights,
1015            ..
1016        } = self;
1017        rest_translations.clear();
1018        rest_rotations.clear();
1019        rest_scales.clear();
1020        rest_translations.reserve(node_count);
1021        rest_rotations.reserve(node_count);
1022        rest_scales.reserve(node_count);
1023        for node_item in nodes.iter() {
1024            rest_translations.push(node_item.get_local_translation());
1025            rest_rotations.push(node_item.get_local_rotation());
1026            rest_scales.push(node_item.get_local_scale());
1027        }
1028        rest_morph_weights.clear();
1029        rest_morph_weights.extend_from_slice(morph_slice);
1030        pose_scratch
1031            .node_translations
1032            .resize(node_count, Vec3::zero());
1033        pose_scratch
1034            .node_rotations
1035            .resize(node_count, Quat::identity());
1036        pose_scratch
1037            .node_scales
1038            .resize(node_count, Vec3::splat(1.0));
1039        pose_scratch
1040            .node_touched_translation
1041            .resize(node_count, false);
1042        pose_scratch.node_touched_rotation.resize(node_count, false);
1043        pose_scratch.node_touched_scale.resize(node_count, false);
1044        pose_scratch.morph_weights.resize(morph_slice.len(), 0.0);
1045        pose_scratch.morph_touched.resize(morph_slice.len(), false);
1046        if pose_scratch.sampler_values.capacity() < 16 {
1047            pose_scratch.sampler_values.reserve(16);
1048        }
1049    }
1050
1051    /// Registers an imported animation clip and returns its clip index.
1052    ///
1053    /// # Arguments
1054    ///
1055    /// - `&Self` - Mutable animation mixer.
1056    /// - `ImportedAnimationClip3D` - Imported glTF/Blender animation clip.
1057    ///
1058    /// # Returns
1059    ///
1060    /// - `usize` - Assigned index inside `clips`.
1061    pub fn add_clip(&mut self, clip: ImportedAnimationClip3D) -> usize {
1062        let clip_idx: usize = self.get_clips().len();
1063        self.get_mut_clips().push(clip);
1064        clip_idx
1065    }
1066
1067    /// Appends an `NlaLayer3D` to the mixing stack and returns its layer index.
1068    ///
1069    /// # Arguments
1070    ///
1071    /// - `&Self` - Mutable animation mixer.
1072    /// - `NlaLayer3D` - Playback layer descriptor.
1073    ///
1074    /// # Returns
1075    ///
1076    /// - `usize` - Assigned index inside `layers`.
1077    pub fn push_layer(&mut self, layer: NlaLayer3D) -> usize {
1078        let layer_idx: usize = self.get_layers().len();
1079        self.get_mut_layers().push(layer);
1080        layer_idx
1081    }
1082
1083    /// Triggers a smooth crossfade on `layer_index` toward `target_weight` over `duration_secs`.
1084    ///
1085    /// # Arguments
1086    ///
1087    /// - `&Self` - Mutable animation mixer.
1088    /// - `usize` - Target layer index inside `layers`.
1089    /// - `f32` - Destination blend weight in `[0.0, 1.0]`.
1090    /// - `f32` - Crossfade duration in seconds.
1091    ///
1092    /// # Returns
1093    ///
1094    /// - `bool` - `true` when `layer_index` existed.
1095    pub fn crossfade_layer(
1096        &mut self,
1097        layer_index: usize,
1098        target_weight: f32,
1099        duration_secs: f32,
1100    ) -> bool {
1101        if let Some(layer) = self.get_mut_layers().get_mut(layer_index) {
1102            layer.start_crossfade(target_weight, duration_secs);
1103            true
1104        } else {
1105            false
1106        }
1107    }
1108
1109    /// Removes all active NLA playback layers while preserving registered clips and captured rest pose.
1110    pub fn clear_layers(&mut self) {
1111        self.get_mut_layers().clear();
1112    }
1113
1114    /// Advances all enabled NLA layers by `dt_secs`, mixes `Override` and `Additive` channels into reusable SoA scratch buffers, and writes modified TRS and morph weights directly into `scene_graph` with zero steady-state heap allocations.
1115    ///
1116    /// # Arguments
1117    ///
1118    /// - `&Self` - Mutable animation mixer.
1119    /// - `f32` - Elapsed frame delta time in seconds.
1120    /// - `&mut SceneGraph3D` - Target scene graph updated in place.
1121    ///
1122    /// # Returns
1123    ///
1124    /// - `usize` - Number of scene nodes or morph channels updated during this tick.
1125    pub fn advance_and_apply(&mut self, dt_secs: f32, scene_graph: &mut SceneGraph3D) -> usize {
1126        let node_count: usize = scene_graph.get_nodes().len();
1127        let morph_count: usize = scene_graph.get_morph_weights().len();
1128        if node_count == 0 || self.get_layers().is_empty() || self.get_clips().is_empty() {
1129            return 0;
1130        }
1131        if self.get_rest_translations().len() != node_count
1132            || self.get_rest_morph_weights().len() != morph_count
1133        {
1134            self.capture_rest_pose(scene_graph);
1135        }
1136        let AnimationMixer3D {
1137            clips,
1138            layers,
1139            pose_scratch,
1140            rest_translations,
1141            rest_rotations,
1142            rest_scales,
1143            rest_morph_weights,
1144        } = self;
1145        pose_scratch
1146            .node_translations
1147            .copy_from_slice(rest_translations.as_slice());
1148        pose_scratch
1149            .node_rotations
1150            .copy_from_slice(rest_rotations.as_slice());
1151        pose_scratch
1152            .node_scales
1153            .copy_from_slice(rest_scales.as_slice());
1154        pose_scratch.node_touched_translation.fill(false);
1155        pose_scratch.node_touched_rotation.fill(false);
1156        pose_scratch.node_touched_scale.fill(false);
1157        pose_scratch
1158            .morph_weights
1159            .copy_from_slice(rest_morph_weights.as_slice());
1160        pose_scratch.morph_touched.fill(false);
1161        let mut any_layer_active: bool = false;
1162        for layer in layers.iter_mut() {
1163            if !layer.get_enabled() {
1164                continue;
1165            }
1166            layer.advance(dt_secs);
1167            let layer_weight: f32 = layer.get_weight().clamp(0.0, 1.0);
1168            if layer_weight <= SKIN_WEIGHT_EPSILON {
1169                continue;
1170            }
1171            let Some(clip) = clips.get(layer.get_clip_index()) else {
1172                continue;
1173            };
1174            any_layer_active = true;
1175            let eval_time: f32 = wrap_animation_time(
1176                layer.get_time_secs(),
1177                clip.get_duration_secs(),
1178                layer.get_repeat_mode(),
1179            );
1180            let blend_mode: NlaBlendMode = layer.get_blend_mode();
1181            let joint_mask: u64 = layer.get_joint_mask();
1182            let samplers: &[ImportedAnimationSampler3D] = clip.get_samplers().as_slice();
1183            for channel in clip.get_channels().iter() {
1184                let target_node: u32 = channel.get_target_node();
1185                let node_idx: usize = target_node as usize;
1186                if node_idx >= node_count {
1187                    continue;
1188                }
1189                if joint_mask != u64::MAX {
1190                    let bit_flag: u64 = 1_u64 << (target_node & 63);
1191                    if (joint_mask & bit_flag) == 0 {
1192                        continue;
1193                    }
1194                }
1195                let Some(sampler) = samplers.get(channel.get_sampler_index()) else {
1196                    continue;
1197                };
1198                let path_kind: GltfAnimationPath = channel.get_path();
1199                let is_rotation: bool = path_kind == GltfAnimationPath::Rotation;
1200                sample_gltf_sampler_into(
1201                    sampler,
1202                    eval_time,
1203                    is_rotation,
1204                    &mut pose_scratch.sampler_values,
1205                );
1206                let sampled: &[f32] = pose_scratch.sampler_values.as_slice();
1207                match path_kind {
1208                    GltfAnimationPath::Translation if sampled.len() >= 3 => {
1209                        let sample_vec: Vec3 = Vec3::new(sampled[0], sampled[1], sampled[2]);
1210                        let cur_vec: Vec3 = pose_scratch.node_translations[node_idx];
1211                        let next_vec: Vec3 = match blend_mode {
1212                            NlaBlendMode::Override => cur_vec.lerp(sample_vec, layer_weight),
1213                            NlaBlendMode::Additive => {
1214                                let delta_vec: Vec3 = sample_vec.sub(rest_translations[node_idx]);
1215                                cur_vec.add(delta_vec.scale(layer_weight))
1216                            }
1217                        };
1218                        pose_scratch.node_translations[node_idx] = next_vec;
1219                        pose_scratch.node_touched_translation[node_idx] = true;
1220                    }
1221                    GltfAnimationPath::Rotation if sampled.len() >= 4 => {
1222                        let sample_quat: Quat =
1223                            Quat::from_xyzw(sampled[0], sampled[1], sampled[2], sampled[3])
1224                                .normalize();
1225                        let cur_quat: Quat = pose_scratch.node_rotations[node_idx];
1226                        let next_quat: Quat = match blend_mode {
1227                            NlaBlendMode::Override => cur_quat.slerp(sample_quat, layer_weight),
1228                            NlaBlendMode::Additive => {
1229                                let rest_inv: Quat = rest_rotations[node_idx].conjugate();
1230                                let delta_quat: Quat = rest_inv.mul_quat(sample_quat).normalize();
1231                                let scaled_delta: Quat =
1232                                    Quat::identity().slerp(delta_quat, layer_weight);
1233                                cur_quat.mul_quat(scaled_delta).normalize()
1234                            }
1235                        };
1236                        pose_scratch.node_rotations[node_idx] = next_quat;
1237                        pose_scratch.node_touched_rotation[node_idx] = true;
1238                    }
1239                    GltfAnimationPath::Scale if sampled.len() >= 3 => {
1240                        let sample_scale: Vec3 = Vec3::new(sampled[0], sampled[1], sampled[2]);
1241                        let cur_scale: Vec3 = pose_scratch.node_scales[node_idx];
1242                        let next_scale: Vec3 = match blend_mode {
1243                            NlaBlendMode::Override => cur_scale.lerp(sample_scale, layer_weight),
1244                            NlaBlendMode::Additive => {
1245                                let rest_s: Vec3 = rest_scales[node_idx];
1246                                let ratio_x: f32 = if rest_s.get_x().abs() > 1.0e-5 {
1247                                    sample_scale.get_x() / rest_s.get_x()
1248                                } else {
1249                                    1.0
1250                                };
1251                                let ratio_y: f32 = if rest_s.get_y().abs() > 1.0e-5 {
1252                                    sample_scale.get_y() / rest_s.get_y()
1253                                } else {
1254                                    1.0
1255                                };
1256                                let ratio_z: f32 = if rest_s.get_z().abs() > 1.0e-5 {
1257                                    sample_scale.get_z() / rest_s.get_z()
1258                                } else {
1259                                    1.0
1260                                };
1261                                let factor_vec: Vec3 = Vec3::splat(1.0)
1262                                    .lerp(Vec3::new(ratio_x, ratio_y, ratio_z), layer_weight);
1263                                cur_scale.mul(factor_vec)
1264                            }
1265                        };
1266                        pose_scratch.node_scales[node_idx] = next_scale;
1267                        pose_scratch.node_touched_scale[node_idx] = true;
1268                    }
1269                    GltfAnimationPath::MorphWeights if !sampled.is_empty() => {
1270                        let node_ref: &SceneNode3D = &scene_graph.get_nodes()[node_idx];
1271                        let morph_off: usize = node_ref.get_morph_weight_offset() as usize;
1272                        let morph_len: usize = usize::from(node_ref.get_morph_weight_count());
1273                        let apply_len: usize = morph_len
1274                            .min(sampled.len())
1275                            .min(morph_count.saturating_sub(morph_off));
1276                        for (local_idx, &sample_val) in sampled.iter().enumerate().take(apply_len) {
1277                            let slot_idx: usize = morph_off + local_idx;
1278                            let cur_val: f32 = pose_scratch.morph_weights[slot_idx];
1279                            let next_val: f32 = match blend_mode {
1280                                NlaBlendMode::Override => {
1281                                    cur_val + (sample_val - cur_val) * layer_weight
1282                                }
1283                                NlaBlendMode::Additive => {
1284                                    let delta_val: f32 = sample_val - rest_morph_weights[slot_idx];
1285                                    cur_val + delta_val * layer_weight
1286                                }
1287                            };
1288                            pose_scratch.morph_weights[slot_idx] = next_val;
1289                            pose_scratch.morph_touched[slot_idx] = true;
1290                        }
1291                    }
1292                    _ => {}
1293                }
1294            }
1295        }
1296        if !any_layer_active {
1297            return 0;
1298        }
1299        let mut updates_applied: usize = 0;
1300        for node_idx in 0..node_count {
1301            let touched_tr: bool = pose_scratch.node_touched_translation[node_idx]
1302                || pose_scratch.node_touched_rotation[node_idx];
1303            let touched_any: bool = touched_tr || pose_scratch.node_touched_scale[node_idx];
1304            if touched_any {
1305                scene_graph.set_local_trs(
1306                    node_idx as u32,
1307                    pose_scratch.node_translations[node_idx],
1308                    pose_scratch.node_rotations[node_idx],
1309                    pose_scratch.node_scales[node_idx],
1310                );
1311                updates_applied += 1;
1312            }
1313        }
1314        let dst_morphs: &mut Vec<f32> = scene_graph.get_mut_morph_weights();
1315        for morph_idx in 0..morph_count {
1316            if pose_scratch.morph_touched[morph_idx] {
1317                dst_morphs[morph_idx] = pose_scratch.morph_weights[morph_idx];
1318                updates_applied += 1;
1319            }
1320        }
1321        updates_applied
1322    }
1323}