euv-core 0.51.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
use super::*;

/// Parent accessor for `SkeletonJoint3D`.
impl SkeletonJoint3D {
    /// Creates a new `SkeletonJoint3D`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Joint label.
    /// - `Option<usize>` - Optional parent joint index.
    /// - `Transform3D` - Bind-pose local transform.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed joint record.
    #[must_use]
    pub fn new(name: &str, parent: Option<usize>, rest_transform: Transform3D) -> Self {
        Self {
            name: name.to_string(),
            parent,
            rest_transform,
        }
    }

    /// Returns the optional parent joint index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Joint reference.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Parent joint index if non-root.
    #[must_use]
    pub fn parent_index(&self) -> Option<usize> {
        let Self { parent, .. } = self;
        *parent
    }
}

/// Keyframe sampling helpers for `JointTrack3D`.
impl JointTrack3D {
    /// Creates a new `JointTrack3D` for `joint_index` sorting keyframes by timestamp.
    ///
    /// # Arguments
    ///
    /// - `usize` - Target joint index.
    /// - `Vec<Keyframe3D>` - Unsorted or sorted keyframes.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready animation track.
    #[must_use]
    pub fn new(joint_index: usize, mut keyframes: Vec<Keyframe3D>) -> Self {
        keyframes.sort_by(|alpha_val: &Keyframe3D, blue_val: &Keyframe3D| {
            alpha_val
                .get_time_secs()
                .total_cmp(&blue_val.get_time_secs())
        });
        Self {
            joint_index,
            keyframes,
        }
    }

    /// Samples this track at `time_secs` via O(log K) binary search, linearly interpolating between neighboring keyframes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Track reference.
    /// - `f32` - Evaluation time in seconds.
    /// - `Transform3D` - Fallback bind-pose transform when track is empty.
    ///
    /// # Returns
    ///
    /// - `Transform3D` - Interpolated local transform.
    #[must_use]
    pub fn sample(&self, time_secs: f32, fallback: Transform3D) -> Transform3D {
        let keys: &[Keyframe3D] = self.get_keyframes().as_slice();
        if keys.is_empty() {
            return fallback;
        }
        if keys.len() == 1 || time_secs <= keys[0].get_time_secs() {
            return keys[0].get_transform();
        }
        let last: Keyframe3D = keys[keys.len() - 1];
        if time_secs >= last.get_time_secs() {
            return last.get_transform();
        }
        let hi: usize = keys
            .partition_point(|entry_index: &Keyframe3D| entry_index.get_time_secs() <= time_secs);
        let idx1: usize = hi.clamp(1, keys.len() - 1);
        let k0: Keyframe3D = keys[idx1 - 1];
        let k1: Keyframe3D = keys[idx1];
        let span: f32 = (k1.get_time_secs() - k0.get_time_secs()).max(1e-5);
        let alpha: f32 = ((time_secs - k0.get_time_secs()) / span).clamp(0.0, 1.0);
        k0.get_transform().lerp(k1.get_transform(), alpha)
    }
}

/// Clip construction and time normalization for `AnimationClip3D`.
impl AnimationClip3D {
    /// Creates a new `AnimationClip3D`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Clip name.
    /// - `f32` - Total duration in seconds.
    /// - `bool` - Looping flag.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty animation clip ready for tracks.
    #[must_use]
    pub fn new(name: &str, duration_secs: f32, looping: bool) -> Self {
        Self {
            name: name.to_string(),
            duration_secs: duration_secs.max(1e-4),
            looping,
            tracks: Vec::new(),
        }
    }

    /// Appends a `JointTrack3D` to this clip and returns `self` for fluent chaining.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base animation clip.
    /// - `JointTrack3D` - Joint animation track.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated animation clip.
    #[must_use]
    pub fn with_track(mut self, track: JointTrack3D) -> Self {
        self.get_mut_tracks().push(track);
        self
    }

    /// Normalizes raw playback time into `[0.0, duration_secs]` respecting `looping`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Clip reference.
    /// - `f32` - Unclamped playback time in seconds.
    ///
    /// # Returns
    ///
    /// - `f32` - Normalized local evaluation timestamp.
    #[must_use]
    pub fn normalize_time(&self, time_secs: f32) -> f32 {
        let dur: f32 = self.get_duration_secs().max(1e-4);
        if self.get_looping() {
            time_secs - (time_secs / dur).floor() * dur
        } else {
            time_secs.clamp(0.0, dur)
        }
    }
}

/// Hierarchical forward-kinematics solver for `SkeletonRig3D`.
impl SkeletonRig3D {
    /// Appends a joint to the skeleton hierarchy and returns its assigned index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable skeleton rig.
    /// - `&str` - Joint label.
    /// - `Option<usize>` - Optional parent joint index.
    /// - `Transform3D` - Bind-pose local transform.
    ///
    /// # Returns
    ///
    /// - `usize` - Assigned joint index.
    pub fn add_joint(
        &mut self,
        name: &str,
        parent: Option<usize>,
        rest_transform: Transform3D,
    ) -> usize {
        let idx: usize = self.get_joints().len();
        self.get_mut_joints()
            .push(SkeletonJoint3D::new(name, parent, rest_transform));
        idx
    }

    /// Samples normalized local joint transforms at `time_secs` for `clip` into an existing `SkeletonPoseSnapshot` with zero allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Skeleton rig reference.
    /// - `&AnimationClip3D` - Active animation clip.
    /// - `f32` - Playback timestamp in seconds.
    /// - `bool` - Whether this sample represents a discontinuous animation cut.
    /// - `&mut SkeletonPoseSnapshot` - Reusable destination pose snapshot overwritten in place.
    pub fn sample_pose_snapshot_into(
        &self,
        clip: &AnimationClip3D,
        time_secs: f32,
        cut: bool,
        out: &mut SkeletonPoseSnapshot,
    ) {
        let blend_factor: f32 = clip.normalize_time(time_secs);
        let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
        let locals: &mut Vec<Transform3D> = out.get_mut_joint_transforms();
        locals.clear();
        locals.reserve(joints.len());
        for joint in joints.iter() {
            locals.push(joint.get_rest_transform());
        }
        for track in clip.get_tracks().iter() {
            let inner_index: usize = track.get_joint_index();
            if inner_index < locals.len() {
                locals[inner_index] = track.sample(blend_factor, locals[inner_index]);
            }
        }
        out.set_cut(cut);
    }

    /// Samples normalized local joint transforms at `time_secs` for `clip` into a `SkeletonPoseSnapshot`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Skeleton rig reference.
    /// - `&AnimationClip3D` - Active animation clip.
    /// - `f32` - Playback timestamp in seconds.
    /// - `bool` - Whether this sample represents a discontinuous animation cut.
    ///
    /// # Returns
    ///
    /// - `SkeletonPoseSnapshot` - Immutable local joint pose snapshot suitable for render-time interpolation.
    #[must_use]
    pub fn sample_pose_snapshot(
        &self,
        clip: &AnimationClip3D,
        time_secs: f32,
        cut: bool,
    ) -> SkeletonPoseSnapshot {
        let mut out: SkeletonPoseSnapshot = SkeletonPoseSnapshot::default();
        self.sample_pose_snapshot_into(clip, time_secs, cut, &mut out);
        out
    }

    /// Evaluates hierarchical world-space `Mat4` joint palettes from `pose` into a reusable caller buffer with zero allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Skeleton rig reference.
    /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot.
    /// - `Transform3D` - Root world transform of the animated actor.
    /// - `&mut Vec<Mat4>` - Reusable output palette buffer cleared and populated in place.
    pub fn evaluate_world_matrices_into(
        &self,
        pose: &SkeletonPoseSnapshot,
        root_world: Transform3D,
        out: &mut Vec<Mat4>,
    ) {
        let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
        let locals: &[Transform3D] = pose.get_joint_transforms().as_slice();
        let root_m: Mat4 = root_world.to_mat4();
        out.clear();
        out.reserve(joints.len());
        for (idx, joint) in joints.iter().enumerate() {
            let local_tr: Transform3D = locals
                .get(idx)
                .copied()
                .unwrap_or_else(|| joint.get_rest_transform());
            let local_m: Mat4 = local_tr.to_mat4();
            let parent_m: Mat4 = match joint.parent_index() {
                Some(point_val) if point_val < out.len() => out[point_val],
                _ => root_m,
            };
            out.push(parent_m.mul(local_m));
        }
    }

    /// Evaluates hierarchical world-space `Mat4` joint palettes from an interpolated `SkeletonPoseSnapshot`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Skeleton rig reference.
    /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot (e.g. interpolated between two fixed steps).
    /// - `Transform3D` - Interpolated root world transform of the animated actor.
    ///
    /// # Returns
    ///
    /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
    #[must_use]
    pub fn evaluate_world_matrices(
        &self,
        pose: &SkeletonPoseSnapshot,
        root_world: Transform3D,
    ) -> Vec<Mat4> {
        let mut world: Vec<Mat4> = Vec::with_capacity(self.get_joints().len());
        self.evaluate_world_matrices_into(pose, root_world, &mut world);
        world
    }

    /// Samples `clip` at `time_secs` and writes world-space `Mat4` joint palettes into reusable scratch buffers with zero allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Skeleton rig reference.
    /// - `&AnimationClip3D` - Active animation clip.
    /// - `f32` - Playback timestamp in seconds.
    /// - `Transform3D` - Root world transform of the animated actor.
    /// - `&mut SkeletonPoseSnapshot` - Reusable local pose scratch buffer.
    /// - `&mut Vec<Mat4>` - Reusable world-matrix output buffer.
    pub fn sample_world_matrices_into(
        &self,
        clip: &AnimationClip3D,
        time_secs: f32,
        root_world: Transform3D,
        pose_scratch: &mut SkeletonPoseSnapshot,
        out_matrices: &mut Vec<Mat4>,
    ) {
        self.sample_pose_snapshot_into(clip, time_secs, false, pose_scratch);
        self.evaluate_world_matrices_into(pose_scratch, root_world, out_matrices);
    }

    /// Evaluates hierarchical world-space `Mat4` joint palettes at `time_secs` for `clip`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Skeleton rig reference.
    /// - `&AnimationClip3D` - Active animation clip.
    /// - `f32` - Playback timestamp in seconds.
    /// - `Transform3D` - Root world transform of the animated actor.
    ///
    /// # Returns
    ///
    /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
    #[must_use]
    pub fn sample_world_matrices(
        &self,
        clip: &AnimationClip3D,
        time_secs: f32,
        root_world: Transform3D,
    ) -> Vec<Mat4> {
        let pose: SkeletonPoseSnapshot = self.sample_pose_snapshot(clip, time_secs, false);
        self.evaluate_world_matrices(&pose, root_world)
    }

    /// Evaluates 4-bone linear-blend vertex skinning from bind-pose vertices and joint palette into `out_vertices` with zero allocations.
    ///
    /// # Arguments
    ///
    /// - `&[Vertex3D]` - Bind-pose mesh vertices.
    /// - `&[SkinWeight3D]` - Matching per-vertex joint indices and weights.
    /// - `&[Mat4]` - World or skinning joint palette matrices.
    /// - `&mut Vec<Vertex3D>` - Reusable destination skinned vertex buffer overwritten in place.
    pub fn skin_vertices_into(
        &self,
        bind_vertices: &[Vertex3D],
        skin_weights: &[SkinWeight3D],
        world_matrices: &[Mat4],
        out_vertices: &mut Vec<Vertex3D>,
    ) {
        let vertex_count: usize = bind_vertices.len().min(skin_weights.len());
        out_vertices.clear();
        out_vertices.reserve(vertex_count);
        if world_matrices.is_empty() {
            out_vertices.extend_from_slice(&bind_vertices[..vertex_count]);
            return;
        }
        let max_joint: usize = world_matrices.len() - 1;
        for vertex_idx in 0..vertex_count {
            let bind_vertex: Vertex3D = bind_vertices[vertex_idx];
            let bind_pos: Vec3 = bind_vertex.get_position();
            let bind_normal: Vec3 = bind_vertex.get_normal();
            let skin: SkinWeight3D = skin_weights[vertex_idx];
            let indices: [u16; 4] = skin.get_joint_indices();
            let weights: [f32; 4] = skin.get_weights();
            let mut skinned_pos: Vec3 = Vec3::zero();
            let mut skinned_normal: Vec3 = Vec3::zero();
            let mut weight_sum: f32 = 0.0;
            for lane in 0..4usize {
                let bone_weight: f32 = weights[lane];
                if bone_weight <= 1e-6 {
                    continue;
                }
                let joint_idx: usize = (indices[lane] as usize).min(max_joint);
                let bone_matrix: Mat4 = world_matrices[joint_idx];
                skinned_pos = skinned_pos.add(bone_matrix.mul_point3(bind_pos).scale(bone_weight));
                skinned_normal =
                    skinned_normal.add(bone_matrix.mul_vec3(bind_normal).scale(bone_weight));
                weight_sum += bone_weight;
            }
            if weight_sum > 1e-5 {
                let inv_weight: f32 = 1.0 / weight_sum;
                let final_pos: Vec3 = skinned_pos.scale(inv_weight);
                let final_normal: Vec3 = if skinned_normal.length_sq() > 1e-8 {
                    skinned_normal.normalize()
                } else {
                    bind_normal
                };
                out_vertices.push(Vertex3D::new(final_pos, final_normal));
            } else {
                out_vertices.push(bind_vertex);
            }
        }
    }
}

/// Real armature skinning (LBS and DQS) and pre-skinning morph evaluation for `Skin3D`.
impl Skin3D {
    /// Constructs a `Skin3D` directly from an imported glTF/Blender `ImportedSkin3D`.
    ///
    /// # Arguments
    ///
    /// - `&ImportedSkin3D` - Imported armature skin asset.
    ///
    /// # Returns
    ///
    /// - `Self` - Runtime skin configured in `SkinningMode::LinearBlend`.
    #[must_use]
    pub fn from_imported(imported: &ImportedSkin3D) -> Self {
        Self {
            name: imported.get_name().clone(),
            joints: imported.get_joints().clone(),
            skeleton_root: imported.try_get_skeleton_root(),
            inverse_bind_matrices: imported.get_inverse_bind_matrices().clone(),
            skinning_mode: SkinningMode::LinearBlend,
        }
    }

    /// Constructs a `Skin3D` from explicit joint node indices and inverse bind matrices.
    ///
    /// # Arguments
    ///
    /// - `&str` - Human-readable skin name.
    /// - `Vec<u32>` - Scene-graph node indices for each bone joint.
    /// - `Option<u32>` - Optional skeleton root node index.
    /// - `Vec<Mat4>` - Inverse bind matrices aligned 1:1 with `joints`.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured armature skin.
    #[must_use]
    pub fn new(
        name: &str,
        joints: Vec<u32>,
        skeleton_root: Option<u32>,
        inverse_bind_matrices: Vec<Mat4>,
    ) -> Self {
        Self {
            name: name.to_string(),
            joints,
            skeleton_root,
            inverse_bind_matrices,
            skinning_mode: SkinningMode::LinearBlend,
        }
    }

    /// Returns a copy of this skin configured with `mode` (`LinearBlend` or `DualQuaternion`).
    ///
    /// # Arguments
    ///
    /// - `Self` - Base skin descriptor.
    /// - `SkinningMode` - Desired vertex deformation algorithm.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated skin descriptor.
    #[must_use]
    pub fn with_skinning_mode(mut self, mode: SkinningMode) -> Self {
        self.set_skinning_mode(mode);
        self
    }

    /// 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.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Armature skin reference.
    /// - `Mat4` - World transformation matrix of the skinned mesh node.
    /// - `&SceneGraph3D` - Propagated hierarchical scene graph supplying current joint world matrices.
    /// - `&mut SkinPaletteScratch3D` - Reusable scratch arena overwritten in place.
    pub fn compute_skin_matrices_into(
        &self,
        mesh_world_matrix: Mat4,
        scene_graph: &SceneGraph3D,
        scratch: &mut SkinPaletteScratch3D,
    ) {
        let inv_mesh_world: Mat4 = mesh_world_matrix.inverse().unwrap_or_else(Mat4::identity);
        let joints: &[u32] = self.get_joints().as_slice();
        let inv_binds: &[Mat4] = self.get_inverse_bind_matrices().as_slice();
        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
        let joint_count: usize = joints.len().min(SKIN_MAX_BONES);
        let SkinPaletteScratch3D {
            skin_matrices,
            skin_normal_matrices,
            skin_dual_quats,
            ..
        } = scratch;
        skin_matrices.clear();
        skin_normal_matrices.clear();
        skin_dual_quats.clear();
        if skin_matrices.capacity() < joint_count {
            skin_matrices.reserve(joint_count - skin_matrices.len());
        }
        if skin_normal_matrices.capacity() < joint_count {
            skin_normal_matrices.reserve(joint_count - skin_normal_matrices.len());
        }
        if skin_dual_quats.capacity() < joint_count {
            skin_dual_quats.reserve(joint_count - skin_dual_quats.len());
        }
        for (joint_idx, &joint_node_id) in joints.iter().enumerate().take(joint_count) {
            let node_idx: usize = joint_node_id as usize;
            let joint_world: Mat4 = nodes
                .get(node_idx)
                .map_or_else(Mat4::identity, |node_ref: &SceneNode3D| {
                    node_ref.get_world_matrix()
                });
            let inv_bind: Mat4 = inv_binds
                .get(joint_idx)
                .copied()
                .unwrap_or_else(Mat4::identity);
            let skin_mat: Mat4 = inv_mesh_world.mul(joint_world).mul(inv_bind);
            let normal_mat: [Vec3; 3] = skin_mat.normal_matrix_3x3();
            let (trans_vec, rot_quat, _scale_vec): (Vec3, Quat, Vec3) = skin_mat.decompose_trs();
            let dual_quat: DualQuat = DualQuat::from_rotation_translation(rot_quat, trans_vec);
            skin_matrices.push(skin_mat);
            skin_normal_matrices.push(normal_mat);
            skin_dual_quats.push(dual_quat);
        }
    }

    /// Evaluates 8-bone Linear-Blend Skinning (LBS) over `source_vertices` into `out_vertices` preserving UVs, colors, and tangent handedness.
    ///
    /// # Arguments
    ///
    /// - `&[Vertex3D]` - Bind-pose or pre-morphed source vertices.
    /// - `&[MeshSkinInfluence3D]` - Per-vertex 8-bone joint indices and weights.
    /// - `&[Mat4]` - Precomputed skin palette matrices.
    /// - `&[[Vec3; 3]]` - Precomputed cofactor 3x3 normal bases aligned with `skin_matrices`.
    /// - `&mut Vec<Vertex3D>` - Reusable destination vertex buffer populated in place.
    pub fn skin_vertices_lbs_into(
        source_vertices: &[Vertex3D],
        skin_influences: &[MeshSkinInfluence3D],
        skin_matrices: &[Mat4],
        skin_normal_matrices: &[[Vec3; 3]],
        out_vertices: &mut Vec<Vertex3D>,
    ) {
        let vert_count: usize = source_vertices.len();
        out_vertices.clear();
        if out_vertices.capacity() < vert_count {
            out_vertices.reserve(vert_count - out_vertices.len());
        }
        if skin_matrices.is_empty() || skin_influences.len() < vert_count {
            out_vertices.extend_from_slice(source_vertices);
            return;
        }
        let max_joint_idx: usize = skin_matrices.len() - 1;
        for vert_idx in 0..vert_count {
            let src_vert: Vertex3D = source_vertices[vert_idx];
            let influence: MeshSkinInfluence3D = skin_influences[vert_idx];
            let all_joints: [u16; 8] = [
                influence.get_joints_0()[0],
                influence.get_joints_0()[1],
                influence.get_joints_0()[2],
                influence.get_joints_0()[3],
                influence.get_joints_1()[0],
                influence.get_joints_1()[1],
                influence.get_joints_1()[2],
                influence.get_joints_1()[3],
            ];
            let all_weights: [f32; 8] = [
                influence.get_weights_0()[0],
                influence.get_weights_0()[1],
                influence.get_weights_0()[2],
                influence.get_weights_0()[3],
                influence.get_weights_1()[0],
                influence.get_weights_1()[1],
                influence.get_weights_1()[2],
                influence.get_weights_1()[3],
            ];
            let src_pos: Vec3 = src_vert.get_position();
            let src_norm: Vec3 = src_vert.get_normal();
            let src_tan: [f32; 4] = src_vert.get_tangent();
            let src_tan_vec: Vec3 = Vec3::new(src_tan[0], src_tan[1], src_tan[2]);
            let mut accum_pos: Vec3 = Vec3::zero();
            let mut accum_norm: Vec3 = Vec3::zero();
            let mut accum_tan: Vec3 = Vec3::zero();
            let mut weight_sum: f32 = 0.0;
            for lane_idx in 0..8usize {
                let bone_weight: f32 = all_weights[lane_idx];
                if bone_weight.abs() <= SKIN_WEIGHT_EPSILON {
                    continue;
                }
                let joint_slot: usize = (all_joints[lane_idx] as usize).min(max_joint_idx);
                let bone_mat: Mat4 = skin_matrices[joint_slot];
                let norm_basis: [Vec3; 3] = skin_normal_matrices[joint_slot];
                accum_pos = accum_pos.add(bone_mat.mul_point3(src_pos).scale(bone_weight));
                let transformed_norm: Vec3 =
                    Mat4::transform_normal_with_basis(src_norm, norm_basis);
                accum_norm = accum_norm.add(transformed_norm.scale(bone_weight));
                accum_tan = accum_tan.add(bone_mat.mul_vec3(src_tan_vec).scale(bone_weight));
                weight_sum += bone_weight;
            }
            if weight_sum.abs() > SKIN_WEIGHT_EPSILON {
                let inv_sum: f32 = 1.0 / weight_sum;
                let final_pos: Vec3 = accum_pos.scale(inv_sum);
                let final_norm: Vec3 = if accum_norm.length_sq() > 1.0e-10 {
                    accum_norm.normalize()
                } else {
                    src_norm
                };
                let final_tan_vec: Vec3 = if accum_tan.length_sq() > 1.0e-10 {
                    accum_tan.normalize()
                } else {
                    src_tan_vec
                };
                out_vertices.push(Vertex3D::from_full(
                    final_pos,
                    final_norm,
                    [
                        final_tan_vec.get_x(),
                        final_tan_vec.get_y(),
                        final_tan_vec.get_z(),
                        src_tan[3],
                    ],
                    src_vert.get_uv0(),
                    src_vert.get_uv1(),
                    src_vert.get_color0(),
                    src_vert.get_flags(),
                ));
            } else {
                out_vertices.push(src_vert);
            }
        }
    }

    /// Evaluates volume-preserving 8-bone Dual-Quaternion Skinning (DQS) over `source_vertices` into `out_vertices`, avoiding candy-wrapper collapse at large twist angles.
    ///
    /// # Arguments
    ///
    /// - `&[Vertex3D]` - Bind-pose or pre-morphed source vertices.
    /// - `&[MeshSkinInfluence3D]` - Per-vertex 8-bone joint indices and weights.
    /// - `&[DualQuat]` - Precomputed bone dual quaternions.
    /// - `&mut Vec<Vertex3D>` - Reusable destination vertex buffer populated in place.
    pub fn skin_vertices_dqs_into(
        source_vertices: &[Vertex3D],
        skin_influences: &[MeshSkinInfluence3D],
        skin_dual_quats: &[DualQuat],
        out_vertices: &mut Vec<Vertex3D>,
    ) {
        let vert_count: usize = source_vertices.len();
        out_vertices.clear();
        if out_vertices.capacity() < vert_count {
            out_vertices.reserve(vert_count - out_vertices.len());
        }
        if skin_dual_quats.is_empty() || skin_influences.len() < vert_count {
            out_vertices.extend_from_slice(source_vertices);
            return;
        }
        let max_joint_idx: usize = skin_dual_quats.len() - 1;
        for vert_idx in 0..vert_count {
            let src_vert: Vertex3D = source_vertices[vert_idx];
            let influence: MeshSkinInfluence3D = skin_influences[vert_idx];
            let all_joints: [u16; 8] = [
                influence.get_joints_0()[0],
                influence.get_joints_0()[1],
                influence.get_joints_0()[2],
                influence.get_joints_0()[3],
                influence.get_joints_1()[0],
                influence.get_joints_1()[1],
                influence.get_joints_1()[2],
                influence.get_joints_1()[3],
            ];
            let all_weights: [f32; 8] = [
                influence.get_weights_0()[0],
                influence.get_weights_0()[1],
                influence.get_weights_0()[2],
                influence.get_weights_0()[3],
                influence.get_weights_1()[0],
                influence.get_weights_1()[1],
                influence.get_weights_1()[2],
                influence.get_weights_1()[3],
            ];
            let mut lane_duals: [DualQuat; 8] = [DualQuat::identity(); 8];
            let mut lane_weights: [f32; 8] = [0.0; 8];
            let mut active_count: usize = 0;
            for lane_idx in 0..8usize {
                let bone_weight: f32 = all_weights[lane_idx];
                if bone_weight.abs() <= SKIN_WEIGHT_EPSILON {
                    continue;
                }
                let joint_slot: usize = (all_joints[lane_idx] as usize).min(max_joint_idx);
                lane_duals[active_count] = skin_dual_quats[joint_slot];
                lane_weights[active_count] = bone_weight;
                active_count += 1;
            }
            if active_count == 0 {
                out_vertices.push(src_vert);
                continue;
            }
            let blended_dq: DualQuat = DualQuat::blend_weighted(
                &lane_duals[..active_count],
                &lane_weights[..active_count],
            );
            let final_pos: Vec3 = blended_dq.transform_point(src_vert.get_position());
            let rot_norm: Vec3 = blended_dq.transform_vector(src_vert.get_normal());
            let final_norm: Vec3 = if rot_norm.length_sq() > 1.0e-10 {
                rot_norm.normalize()
            } else {
                src_vert.get_normal()
            };
            let src_tan: [f32; 4] = src_vert.get_tangent();
            let rot_tan: Vec3 =
                blended_dq.transform_vector(Vec3::new(src_tan[0], src_tan[1], src_tan[2]));
            let final_tan_vec: Vec3 = if rot_tan.length_sq() > 1.0e-10 {
                rot_tan.normalize()
            } else {
                Vec3::new(src_tan[0], src_tan[1], src_tan[2])
            };
            out_vertices.push(Vertex3D::from_full(
                final_pos,
                final_norm,
                [
                    final_tan_vec.get_x(),
                    final_tan_vec.get_y(),
                    final_tan_vec.get_z(),
                    src_tan[3],
                ],
                src_vert.get_uv0(),
                src_vert.get_uv1(),
                src_vert.get_color0(),
                src_vert.get_flags(),
            ));
        }
    }

    /// Evaluates Blender's exact modifier order (Shape Keys BEFORE Armature Skinning) for `mesh` into `scratch.skinned_vertices` with zero steady-state allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Armature skin reference.
    /// - `&Mesh3D` - Source bind-pose mesh with optional `morph_targets` and `skin_influences`.
    /// - `&[f32]` - Active shape-key weights for this mesh node.
    /// - `Mat4` - Current mesh node world matrix.
    /// - `&SceneGraph3D` - Propagated hierarchical scene graph.
    /// - `&mut SkinPaletteScratch3D` - Reusable deformation scratch arena.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `scratch.skinned_vertices` was populated with deformed vertices.
    pub fn deform_mesh_into(
        &self,
        mesh: &Mesh3D,
        morph_weights: &[f32],
        mesh_world_matrix: Mat4,
        scene_graph: &SceneGraph3D,
        scratch: &mut SkinPaletteScratch3D,
    ) -> bool {
        let base_vertices: &[Vertex3D] = mesh.get_vertices().as_slice();
        if base_vertices.is_empty() {
            scratch.get_mut_skinned_vertices().clear();
            return false;
        }
        let has_morphs: bool = apply_morph_targets_into(
            base_vertices,
            mesh.get_morph_targets().as_slice(),
            morph_weights,
            scratch.get_mut_morphed_vertices(),
        );
        let skin_influences: &[MeshSkinInfluence3D] = mesh.get_skin_influences().as_slice();
        let has_skinning: bool =
            !self.get_joints().is_empty() && skin_influences.len() >= base_vertices.len();
        if !has_skinning {
            if has_morphs {
                let SkinPaletteScratch3D {
                    morphed_vertices,
                    skinned_vertices,
                    ..
                } = scratch;
                skinned_vertices.clear();
                if skinned_vertices.capacity() < morphed_vertices.len() {
                    skinned_vertices.reserve(morphed_vertices.len() - skinned_vertices.len());
                }
                skinned_vertices.extend_from_slice(morphed_vertices.as_slice());
                return true;
            }
            return false;
        }
        self.compute_skin_matrices_into(mesh_world_matrix, scene_graph, scratch);
        let SkinPaletteScratch3D {
            skin_matrices,
            skin_normal_matrices,
            skin_dual_quats,
            morphed_vertices,
            skinned_vertices,
        } = scratch;
        let pre_skin_verts: &[Vertex3D] = if has_morphs {
            morphed_vertices.as_slice()
        } else {
            base_vertices
        };
        match self.get_skinning_mode() {
            SkinningMode::LinearBlend => {
                Self::skin_vertices_lbs_into(
                    pre_skin_verts,
                    skin_influences,
                    skin_matrices.as_slice(),
                    skin_normal_matrices.as_slice(),
                    skinned_vertices,
                );
            }
            SkinningMode::DualQuaternion => {
                Self::skin_vertices_dqs_into(
                    pre_skin_verts,
                    skin_influences,
                    skin_dual_quats.as_slice(),
                    skinned_vertices,
                );
            }
        }
        true
    }
}

/// Default playback configuration for `NlaLayer3D`.
impl Default for NlaLayer3D {
    /// Returns an enabled looping override layer targeting clip `0` at full weight.
    ///
    /// # Returns
    ///
    /// - `Self` - Default NLA layer.
    fn default() -> Self {
        Self::new(0)
    }
}

/// Fluent configuration and crossfade helpers for `NlaLayer3D`.
impl NlaLayer3D {
    /// Creates an enabled looping `NlaLayer3D` playing `clip_index` at full weight across all nodes.
    ///
    /// # Arguments
    ///
    /// - `usize` - Target clip index in `AnimationMixer3D::clips`.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured NLA layer.
    #[must_use]
    pub const fn new(clip_index: usize) -> Self {
        Self {
            clip_index,
            weight: 1.0,
            blend_mode: NlaBlendMode::Override,
            repeat_mode: NlaRepeatMode::Loop,
            time_secs: 0.0,
            time_scale: 1.0,
            fade_elapsed_secs: 0.0,
            fade_duration_secs: 0.0,
            fade_start_weight: 1.0,
            fade_target_weight: 1.0,
            joint_mask: u64::MAX,
            enabled: true,
        }
    }

    /// Sets the initial blend weight clamped to `[0.0, 1.0]`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base NLA layer.
    /// - `f32` - Layer blend weight.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated NLA layer.
    #[must_use]
    pub fn with_weight(mut self, weight: f32) -> Self {
        let clamped: f32 = weight.clamp(0.0, 1.0);
        self.set_weight(clamped);
        self.set_fade_start_weight(clamped);
        self.set_fade_target_weight(clamped);
        self
    }

    /// Sets the composition blend mode (`Override` or `Additive`).
    ///
    /// # Arguments
    ///
    /// - `Self` - Base NLA layer.
    /// - `NlaBlendMode` - Blend composition mode.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated NLA layer.
    #[must_use]
    pub fn with_blend_mode(mut self, blend_mode: NlaBlendMode) -> Self {
        self.set_blend_mode(blend_mode);
        self
    }

    /// Sets the playback repeat policy (`Loop`, `Clamp`, or `PingPong`).
    ///
    /// # Arguments
    ///
    /// - `Self` - Base NLA layer.
    /// - `NlaRepeatMode` - Playback wrap policy.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated NLA layer.
    #[must_use]
    pub fn with_repeat_mode(mut self, repeat_mode: NlaRepeatMode) -> Self {
        self.set_repeat_mode(repeat_mode);
        self
    }

    /// Sets the playback speed multiplier.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base NLA layer.
    /// - `f32` - Time scale multiplier.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated NLA layer.
    #[must_use]
    pub fn with_time_scale(mut self, time_scale: f32) -> Self {
        self.set_time_scale(time_scale);
        self
    }

    /// Restricts this layer to scene nodes matching `joint_mask` (`(1 << (node_id & 63)) & joint_mask != 0`).
    ///
    /// # Arguments
    ///
    /// - `Self` - Base NLA layer.
    /// - `u64` - Node eligibility bitmask.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated NLA layer.
    #[must_use]
    pub fn with_joint_mask(mut self, joint_mask: u64) -> Self {
        self.set_joint_mask(joint_mask);
        self
    }

    /// Initiates a smooth linear crossfade from the current layer weight to `target_weight` over `duration_secs`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable NLA layer.
    /// - `f32` - Destination blend weight in `[0.0, 1.0]`.
    /// - `f32` - Fade duration in seconds (`<= 0.0` snaps immediately).
    pub fn start_crossfade(&mut self, target_weight: f32, duration_secs: f32) {
        let clamped_target: f32 = target_weight.clamp(0.0, 1.0);
        if duration_secs <= ANIM_MIN_SPAN_SECS {
            self.set_weight(clamped_target);
            self.set_fade_start_weight(clamped_target);
            self.set_fade_target_weight(clamped_target);
            self.set_fade_elapsed_secs(0.0);
            self.set_fade_duration_secs(0.0);
            return;
        }
        let current_weight: f32 = self.get_weight();
        self.set_fade_start_weight(current_weight);
        self.set_fade_target_weight(clamped_target);
        self.set_fade_elapsed_secs(0.0);
        self.set_fade_duration_secs(duration_secs);
    }

    /// Advances this layer's clock and active crossfade envelope by `dt_secs`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable NLA layer.
    /// - `f32` - Elapsed frame delta time in seconds.
    pub fn advance(&mut self, dt_secs: f32) {
        if !self.get_enabled() {
            return;
        }
        let safe_dt: f32 = dt_secs.max(0.0);
        self.set_time_secs(self.get_time_secs() + safe_dt * self.get_time_scale());
        let fade_dur: f32 = self.get_fade_duration_secs();
        if fade_dur > ANIM_MIN_SPAN_SECS {
            let next_elapsed: f32 = (self.get_fade_elapsed_secs() + safe_dt).min(fade_dur);
            let fade_alpha: f32 = (next_elapsed / fade_dur).clamp(0.0, 1.0);
            let start_w: f32 = self.get_fade_start_weight();
            let target_w: f32 = self.get_fade_target_weight();
            self.set_weight(start_w + (target_w - start_w) * fade_alpha);
            self.set_fade_elapsed_secs(next_elapsed);
            if next_elapsed >= fade_dur {
                self.set_fade_duration_secs(0.0);
            }
        }
    }
}

/// Multi-layer glTF/NLA animation mixing and zero-allocation scene-graph application for `AnimationMixer3D`.
impl AnimationMixer3D {
    /// Captures the current `SceneGraph3D` local transforms and morph weights as the bind/rest pose and pre-reserves scratch buffers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable animation mixer.
    /// - `&SceneGraph3D` - Scene graph in its rest pose.
    pub fn capture_rest_pose(&mut self, scene_graph: &SceneGraph3D) {
        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
        let node_count: usize = nodes.len();
        let morph_slice: &[f32] = scene_graph.get_morph_weights().as_slice();
        let AnimationMixer3D {
            pose_scratch,
            rest_translations,
            rest_rotations,
            rest_scales,
            rest_morph_weights,
            ..
        } = self;
        rest_translations.clear();
        rest_rotations.clear();
        rest_scales.clear();
        rest_translations.reserve(node_count);
        rest_rotations.reserve(node_count);
        rest_scales.reserve(node_count);
        for node_item in nodes.iter() {
            rest_translations.push(node_item.get_local_translation());
            rest_rotations.push(node_item.get_local_rotation());
            rest_scales.push(node_item.get_local_scale());
        }
        rest_morph_weights.clear();
        rest_morph_weights.extend_from_slice(morph_slice);
        pose_scratch
            .node_translations
            .resize(node_count, Vec3::zero());
        pose_scratch
            .node_rotations
            .resize(node_count, Quat::identity());
        pose_scratch
            .node_scales
            .resize(node_count, Vec3::splat(1.0));
        pose_scratch
            .node_touched_translation
            .resize(node_count, false);
        pose_scratch.node_touched_rotation.resize(node_count, false);
        pose_scratch.node_touched_scale.resize(node_count, false);
        pose_scratch.morph_weights.resize(morph_slice.len(), 0.0);
        pose_scratch.morph_touched.resize(morph_slice.len(), false);
        if pose_scratch.sampler_values.capacity() < 16 {
            pose_scratch.sampler_values.reserve(16);
        }
    }

    /// Registers an imported animation clip and returns its clip index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable animation mixer.
    /// - `ImportedAnimationClip3D` - Imported glTF/Blender animation clip.
    ///
    /// # Returns
    ///
    /// - `usize` - Assigned index inside `clips`.
    pub fn add_clip(&mut self, clip: ImportedAnimationClip3D) -> usize {
        let clip_idx: usize = self.get_clips().len();
        self.get_mut_clips().push(clip);
        clip_idx
    }

    /// Appends an `NlaLayer3D` to the mixing stack and returns its layer index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable animation mixer.
    /// - `NlaLayer3D` - Playback layer descriptor.
    ///
    /// # Returns
    ///
    /// - `usize` - Assigned index inside `layers`.
    pub fn push_layer(&mut self, layer: NlaLayer3D) -> usize {
        let layer_idx: usize = self.get_layers().len();
        self.get_mut_layers().push(layer);
        layer_idx
    }

    /// Triggers a smooth crossfade on `layer_index` toward `target_weight` over `duration_secs`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable animation mixer.
    /// - `usize` - Target layer index inside `layers`.
    /// - `f32` - Destination blend weight in `[0.0, 1.0]`.
    /// - `f32` - Crossfade duration in seconds.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `layer_index` existed.
    pub fn crossfade_layer(
        &mut self,
        layer_index: usize,
        target_weight: f32,
        duration_secs: f32,
    ) -> bool {
        if let Some(layer) = self.get_mut_layers().get_mut(layer_index) {
            layer.start_crossfade(target_weight, duration_secs);
            true
        } else {
            false
        }
    }

    /// Removes all active NLA playback layers while preserving registered clips and captured rest pose.
    pub fn clear_layers(&mut self) {
        self.get_mut_layers().clear();
    }

    /// 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.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable animation mixer.
    /// - `f32` - Elapsed frame delta time in seconds.
    /// - `&mut SceneGraph3D` - Target scene graph updated in place.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of scene nodes or morph channels updated during this tick.
    pub fn advance_and_apply(&mut self, dt_secs: f32, scene_graph: &mut SceneGraph3D) -> usize {
        let node_count: usize = scene_graph.get_nodes().len();
        let morph_count: usize = scene_graph.get_morph_weights().len();
        if node_count == 0 || self.get_layers().is_empty() || self.get_clips().is_empty() {
            return 0;
        }
        if self.get_rest_translations().len() != node_count
            || self.get_rest_morph_weights().len() != morph_count
        {
            self.capture_rest_pose(scene_graph);
        }
        let AnimationMixer3D {
            clips,
            layers,
            pose_scratch,
            rest_translations,
            rest_rotations,
            rest_scales,
            rest_morph_weights,
        } = self;
        pose_scratch
            .node_translations
            .copy_from_slice(rest_translations.as_slice());
        pose_scratch
            .node_rotations
            .copy_from_slice(rest_rotations.as_slice());
        pose_scratch
            .node_scales
            .copy_from_slice(rest_scales.as_slice());
        pose_scratch.node_touched_translation.fill(false);
        pose_scratch.node_touched_rotation.fill(false);
        pose_scratch.node_touched_scale.fill(false);
        pose_scratch
            .morph_weights
            .copy_from_slice(rest_morph_weights.as_slice());
        pose_scratch.morph_touched.fill(false);
        let mut any_layer_active: bool = false;
        for layer in layers.iter_mut() {
            if !layer.get_enabled() {
                continue;
            }
            layer.advance(dt_secs);
            let layer_weight: f32 = layer.get_weight().clamp(0.0, 1.0);
            if layer_weight <= SKIN_WEIGHT_EPSILON {
                continue;
            }
            let Some(clip) = clips.get(layer.get_clip_index()) else {
                continue;
            };
            any_layer_active = true;
            let eval_time: f32 = wrap_animation_time(
                layer.get_time_secs(),
                clip.get_duration_secs(),
                layer.get_repeat_mode(),
            );
            let blend_mode: NlaBlendMode = layer.get_blend_mode();
            let joint_mask: u64 = layer.get_joint_mask();
            let samplers: &[ImportedAnimationSampler3D] = clip.get_samplers().as_slice();
            for channel in clip.get_channels().iter() {
                let target_node: u32 = channel.get_target_node();
                let node_idx: usize = target_node as usize;
                if node_idx >= node_count {
                    continue;
                }
                if joint_mask != u64::MAX {
                    let bit_flag: u64 = 1_u64 << (target_node & 63);
                    if (joint_mask & bit_flag) == 0 {
                        continue;
                    }
                }
                let Some(sampler) = samplers.get(channel.get_sampler_index()) else {
                    continue;
                };
                let path_kind: GltfAnimationPath = channel.get_path();
                let is_rotation: bool = path_kind == GltfAnimationPath::Rotation;
                sample_gltf_sampler_into(
                    sampler,
                    eval_time,
                    is_rotation,
                    &mut pose_scratch.sampler_values,
                );
                let sampled: &[f32] = pose_scratch.sampler_values.as_slice();
                match path_kind {
                    GltfAnimationPath::Translation if sampled.len() >= 3 => {
                        let sample_vec: Vec3 = Vec3::new(sampled[0], sampled[1], sampled[2]);
                        let cur_vec: Vec3 = pose_scratch.node_translations[node_idx];
                        let next_vec: Vec3 = match blend_mode {
                            NlaBlendMode::Override => cur_vec.lerp(sample_vec, layer_weight),
                            NlaBlendMode::Additive => {
                                let delta_vec: Vec3 = sample_vec.sub(rest_translations[node_idx]);
                                cur_vec.add(delta_vec.scale(layer_weight))
                            }
                        };
                        pose_scratch.node_translations[node_idx] = next_vec;
                        pose_scratch.node_touched_translation[node_idx] = true;
                    }
                    GltfAnimationPath::Rotation if sampled.len() >= 4 => {
                        let sample_quat: Quat =
                            Quat::from_xyzw(sampled[0], sampled[1], sampled[2], sampled[3])
                                .normalize();
                        let cur_quat: Quat = pose_scratch.node_rotations[node_idx];
                        let next_quat: Quat = match blend_mode {
                            NlaBlendMode::Override => cur_quat.slerp(sample_quat, layer_weight),
                            NlaBlendMode::Additive => {
                                let rest_inv: Quat = rest_rotations[node_idx].conjugate();
                                let delta_quat: Quat = rest_inv.mul_quat(sample_quat).normalize();
                                let scaled_delta: Quat =
                                    Quat::identity().slerp(delta_quat, layer_weight);
                                cur_quat.mul_quat(scaled_delta).normalize()
                            }
                        };
                        pose_scratch.node_rotations[node_idx] = next_quat;
                        pose_scratch.node_touched_rotation[node_idx] = true;
                    }
                    GltfAnimationPath::Scale if sampled.len() >= 3 => {
                        let sample_scale: Vec3 = Vec3::new(sampled[0], sampled[1], sampled[2]);
                        let cur_scale: Vec3 = pose_scratch.node_scales[node_idx];
                        let next_scale: Vec3 = match blend_mode {
                            NlaBlendMode::Override => cur_scale.lerp(sample_scale, layer_weight),
                            NlaBlendMode::Additive => {
                                let rest_s: Vec3 = rest_scales[node_idx];
                                let ratio_x: f32 = if rest_s.get_x().abs() > 1.0e-5 {
                                    sample_scale.get_x() / rest_s.get_x()
                                } else {
                                    1.0
                                };
                                let ratio_y: f32 = if rest_s.get_y().abs() > 1.0e-5 {
                                    sample_scale.get_y() / rest_s.get_y()
                                } else {
                                    1.0
                                };
                                let ratio_z: f32 = if rest_s.get_z().abs() > 1.0e-5 {
                                    sample_scale.get_z() / rest_s.get_z()
                                } else {
                                    1.0
                                };
                                let factor_vec: Vec3 = Vec3::splat(1.0)
                                    .lerp(Vec3::new(ratio_x, ratio_y, ratio_z), layer_weight);
                                cur_scale.mul(factor_vec)
                            }
                        };
                        pose_scratch.node_scales[node_idx] = next_scale;
                        pose_scratch.node_touched_scale[node_idx] = true;
                    }
                    GltfAnimationPath::MorphWeights if !sampled.is_empty() => {
                        let node_ref: &SceneNode3D = &scene_graph.get_nodes()[node_idx];
                        let morph_off: usize = node_ref.get_morph_weight_offset() as usize;
                        let morph_len: usize = usize::from(node_ref.get_morph_weight_count());
                        let apply_len: usize = morph_len
                            .min(sampled.len())
                            .min(morph_count.saturating_sub(morph_off));
                        for (local_idx, &sample_val) in sampled.iter().enumerate().take(apply_len) {
                            let slot_idx: usize = morph_off + local_idx;
                            let cur_val: f32 = pose_scratch.morph_weights[slot_idx];
                            let next_val: f32 = match blend_mode {
                                NlaBlendMode::Override => {
                                    cur_val + (sample_val - cur_val) * layer_weight
                                }
                                NlaBlendMode::Additive => {
                                    let delta_val: f32 = sample_val - rest_morph_weights[slot_idx];
                                    cur_val + delta_val * layer_weight
                                }
                            };
                            pose_scratch.morph_weights[slot_idx] = next_val;
                            pose_scratch.morph_touched[slot_idx] = true;
                        }
                    }
                    _ => {}
                }
            }
        }
        if !any_layer_active {
            return 0;
        }
        let mut updates_applied: usize = 0;
        for node_idx in 0..node_count {
            let touched_tr: bool = pose_scratch.node_touched_translation[node_idx]
                || pose_scratch.node_touched_rotation[node_idx];
            let touched_any: bool = touched_tr || pose_scratch.node_touched_scale[node_idx];
            if touched_any {
                scene_graph.set_local_trs(
                    node_idx as u32,
                    pose_scratch.node_translations[node_idx],
                    pose_scratch.node_rotations[node_idx],
                    pose_scratch.node_scales[node_idx],
                );
                updates_applied += 1;
            }
        }
        let dst_morphs: &mut Vec<f32> = scene_graph.get_mut_morph_weights();
        for morph_idx in 0..morph_count {
            if pose_scratch.morph_touched[morph_idx] {
                dst_morphs[morph_idx] = pose_scratch.morph_weights[morph_idx];
                updates_applied += 1;
            }
        }
        updates_applied
    }
}