euv-core 0.57.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
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
use super::*;

/// Analytic 2-Bone, FABRIK, and cone-constrained CCD inverse kinematics implementations for `IkSolver3D`.
impl IkSolver3D {
    /// Solves exact analytic 2-bone IK with a pole vector controlling the knee/elbow bend plane.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Root joint world position (hip or shoulder).
    /// - `f32` - Upper bone segment length.
    /// - `f32` - Lower bone segment length.
    /// - `Vec3` - Desired end-effector target position.
    /// - `Vec3` - World-space pole vector hint controlling knee/elbow orientation.
    ///
    /// # Returns
    ///
    /// - `IkTwoBoneResult` - Solved mid-joint, end-effector, bone rotations, and residual error.
    #[must_use]
    pub fn solve_two_bone(
        root: Vec3,
        upper_len: f32,
        lower_len: f32,
        target: Vec3,
        pole_target: Vec3,
    ) -> IkTwoBoneResult {
        let l1: f32 = upper_len.abs().max(1e-4);
        let l2: f32 = lower_len.abs().max(1e-4);
        let to_target: Vec3 = target.sub(root);
        let raw_dist: f32 = to_target.length();
        let target_dir: Vec3 = if raw_dist > 1e-6 {
            to_target.scale(1.0 / raw_dist)
        } else {
            let pole_hint: Vec3 = pole_target.sub(root);
            if pole_hint.length_sq() > 1e-10 {
                pole_hint.normalize()
            } else {
                Vec3::new(1.0, 0.0, 0.0)
            }
        };
        let min_reach: f32 = (l1 - l2).abs();
        let max_reach: f32 = l1 + l2;
        let clamped_dist: f32 = if max_reach > min_reach + 2e-5 {
            raw_dist.clamp(min_reach + 1e-5, max_reach - 1e-5)
        } else {
            max_reach
        };
        let cos_alpha: f32 = ((l1 * l1 + clamped_dist * clamped_dist - l2 * l2)
            / (2.0 * l1 * clamped_dist))
            .clamp(-1.0, 1.0);
        let sin_alpha: f32 = (1.0 - cos_alpha * cos_alpha).max(0.0).sqrt();
        let to_pole: Vec3 = pole_target.sub(root);
        let proj_pole: Vec3 = to_pole.sub(target_dir.scale(to_pole.dot(target_dir)));
        let bend_dir: Vec3 = if proj_pole.length_sq() > 1e-10 {
            proj_pole.normalize()
        } else {
            let fallback: Vec3 = if target_dir.get_y().abs() < 0.9 {
                Vec3::new(0.0, 1.0, 0.0)
            } else {
                Vec3::new(1.0, 0.0, 0.0)
            };
            target_dir.cross(fallback).normalize()
        };
        let joint_mid: Vec3 = root
            .add(target_dir.scale(l1 * cos_alpha))
            .add(bend_dir.scale(l1 * sin_alpha));
        let lower_vec: Vec3 = target.sub(joint_mid);
        let lower_dir: Vec3 = if lower_vec.length_sq() > 1e-12 {
            lower_vec.normalize()
        } else {
            target_dir
        };
        let effector: Vec3 = joint_mid.add(lower_dir.scale(l2));
        let up_axis: Vec3 = Vec3::new(0.0, 1.0, 0.0);
        let upper_rot: Quat = kin_quat_from_to(up_axis, joint_mid.sub(root).normalize());
        let lower_rot: Quat = kin_quat_from_to(up_axis, lower_dir);
        let error: f32 = effector.sub(target).length();
        IkTwoBoneResult::new(
            joint_mid,
            effector,
            upper_rot,
            lower_rot,
            error,
            error <= 1e-3,
        )
    }

    /// Solves a multi-bone chain in place using FABRIK (Forward And Backward Reaching IK).
    ///
    /// # Arguments
    ///
    /// - `&mut [Vec3]` - Mutable world-space joint positions (`len >= 2`; index `0` stays pinned).
    /// - `&[f32]` - Segment lengths of length `positions.len() - 1`.
    /// - `Vec3` - Desired end-effector target position.
    /// - `f32` - Reach convergence tolerance in world units.
    /// - `usize` - Maximum FABRIK forward-backward iterations.
    ///
    /// # Returns
    ///
    /// - `IkChainResult` - Executed iteration count, residual error, and reach status.
    pub fn solve_fabrik(
        positions: &mut [Vec3],
        lengths: &[f32],
        target: Vec3,
        tolerance: f32,
        max_iterations: usize,
    ) -> IkChainResult {
        let n: usize = positions.len();
        if n < 2 || lengths.len() + 1 < n {
            return IkChainResult::new(0, 0.0, false);
        }
        let tol: f32 = if tolerance.is_finite() && tolerance > 0.0 {
            tolerance
        } else {
            1e-4
        };
        let root: Vec3 = positions[0];
        let mut total_len: f32 = 0.0;
        for &len in &lengths[..(n - 1)] {
            total_len += len.abs();
        }
        let root_to_target: Vec3 = target.sub(root);
        let dist_root_target: f32 = root_to_target.length();
        if dist_root_target >= total_len {
            let dir: Vec3 = if dist_root_target > 1e-6 {
                root_to_target.scale(1.0 / dist_root_target)
            } else {
                Vec3::new(1.0, 0.0, 0.0)
            };
            for i in 0..(n - 1) {
                positions[i + 1] = positions[i].add(dir.scale(lengths[i].abs()));
            }
            let err: f32 = positions[n - 1].sub(target).length();
            return IkChainResult::new(1, err, err <= tol);
        }
        let mut iterations: usize = 0;
        let max_iters: usize = max_iterations.max(1);
        for iter in 0..max_iters {
            let cur_err: f32 = positions[n - 1].sub(target).length();
            if cur_err <= tol {
                return IkChainResult::new(iter, cur_err, true);
            }
            iterations = iter + 1;
            positions[n - 1] = target;
            for i in (0..(n - 1)).rev() {
                let seg: Vec3 = positions[i].sub(positions[i + 1]);
                let dir: Vec3 = if seg.length_sq() > 1e-12 {
                    seg.normalize()
                } else {
                    Vec3::new(0.0, 1.0, 0.0)
                };
                positions[i] = positions[i + 1].add(dir.scale(lengths[i].abs()));
            }
            positions[0] = root;
            for i in 0..(n - 1) {
                let seg: Vec3 = positions[i + 1].sub(positions[i]);
                let dir: Vec3 = if seg.length_sq() > 1e-12 {
                    seg.normalize()
                } else {
                    Vec3::new(0.0, 1.0, 0.0)
                };
                positions[i + 1] = positions[i].add(dir.scale(lengths[i].abs()));
            }
        }
        let final_err: f32 = positions[n - 1].sub(target).length();
        IkChainResult::new(iterations, final_err, final_err <= tol)
    }

    /// Solves a multi-bone chain in place using Cyclic Coordinate Descent (CCD) with angular cone limits.
    ///
    /// # Arguments
    ///
    /// - `&mut [Vec3]` - Mutable world-space joint positions (`len >= 2`; index `0` stays pinned).
    /// - `&[IkBoneConstraint]` - Optional angular cone constraints per joint (`0..positions.len() - 1`).
    /// - `Vec3` - Desired end-effector target position.
    /// - `f32` - Reach convergence tolerance in world units.
    /// - `usize` - Maximum CCD sweep iterations.
    ///
    /// # Returns
    ///
    /// - `IkChainResult` - Executed iteration count, residual error, and reach status.
    pub fn solve_ccd(
        positions: &mut [Vec3],
        constraints: &[IkBoneConstraint],
        target: Vec3,
        tolerance: f32,
        max_iterations: usize,
    ) -> IkChainResult {
        let n: usize = positions.len();
        if n < 2 {
            return IkChainResult::new(0, 0.0, false);
        }
        let tol: f32 = if tolerance.is_finite() && tolerance > 0.0 {
            tolerance
        } else {
            1e-4
        };
        let max_iters: usize = max_iterations.max(1);
        let mut iterations: usize = 0;
        for iter in 0..max_iters {
            let cur_err: f32 = positions[n - 1].sub(target).length();
            if cur_err <= tol {
                return IkChainResult::new(iter, cur_err, true);
            }
            iterations = iter + 1;
            for j in (0..(n - 1)).rev() {
                let pivot: Vec3 = positions[j];
                let to_eff: Vec3 = positions[n - 1].sub(pivot);
                let to_tgt: Vec3 = target.sub(pivot);
                if to_eff.length_sq() <= 1e-12 || to_tgt.length_sq() <= 1e-12 {
                    continue;
                }
                let step_rot: Quat = kin_quat_from_to(to_eff.normalize(), to_tgt.normalize());
                for pos in &mut positions[(j + 1)..n] {
                    let rel: Vec3 = pos.sub(pivot);
                    *pos = pivot.add(step_rot.rotate_vec3(rel));
                }
                if let Some(constraint) = constraints.get(j) {
                    let max_ang: f32 = constraint.get_max_cone_angle_rad().clamp(0.0, PI);
                    let ref_axis: Vec3 = if j == 0 {
                        let axis: Vec3 = constraint.get_reference_axis();
                        if axis.length_sq() > 1e-10 {
                            axis.normalize()
                        } else {
                            Vec3::new(0.0, 1.0, 0.0)
                        }
                    } else {
                        let parent_seg: Vec3 = pivot.sub(positions[j - 1]);
                        if parent_seg.length_sq() > 1e-10 {
                            parent_seg.normalize()
                        } else {
                            Vec3::new(0.0, 1.0, 0.0)
                        }
                    };
                    let bone_seg: Vec3 = positions[j + 1].sub(pivot);
                    if bone_seg.length_sq() > 1e-12 {
                        let bone_dir: Vec3 = bone_seg.normalize();
                        let angle: f32 = bone_dir.dot(ref_axis).clamp(-1.0, 1.0).acos();
                        if angle > max_ang {
                            let lateral: Vec3 =
                                bone_dir.sub(ref_axis.scale(bone_dir.dot(ref_axis)));
                            let lat_dir: Vec3 = if lateral.length_sq() > 1e-10 {
                                lateral.normalize()
                            } else {
                                let fallback: Vec3 = if ref_axis.get_y().abs() < 0.9 {
                                    Vec3::new(0.0, 1.0, 0.0)
                                } else {
                                    Vec3::new(1.0, 0.0, 0.0)
                                };
                                ref_axis.cross(fallback).normalize()
                            };
                            let clamped_dir: Vec3 = ref_axis
                                .scale(max_ang.cos())
                                .add(lat_dir.scale(max_ang.sin()))
                                .normalize();
                            let clamp_rot: Quat = kin_quat_from_to(bone_dir, clamped_dir);
                            for pos in &mut positions[(j + 1)..n] {
                                let rel: Vec3 = pos.sub(pivot);
                                *pos = pivot.add(clamp_rot.rotate_vec3(rel));
                            }
                        }
                    }
                }
            }
        }
        let final_err: f32 = positions[n - 1].sub(target).length();
        IkChainResult::new(iterations, final_err, final_err <= tol)
    }
}

/// Support mapping and translation helpers for `ConvexShape3D`.
impl ConvexShape3D {
    /// Returns the approximate geometric center of this convex shape.
    ///
    /// # Returns
    ///
    /// - `Vec3` - World-space reference center.
    #[must_use]
    pub fn center_hint(&self) -> Vec3 {
        match self {
            Self::Sphere { center, .. }
            | Self::Box { center, .. }
            | Self::Capsule { center, .. }
            | Self::Cylinder { center, .. } => *center,
            Self::ConvexHull {
                vertices,
                position,
                rotation,
            } => {
                if vertices.is_empty() {
                    return *position;
                }
                let mut sum: Vec3 = Vec3::zero();
                for &v in vertices {
                    sum = sum.add(v);
                }
                let avg: Vec3 = sum.scale(1.0 / (vertices.len() as f32));
                position.add(rotation.rotate_vec3(avg))
            }
        }
    }

    /// Returns a copy of this convex shape translated by `delta` in world space.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space translation offset.
    ///
    /// # Returns
    ///
    /// - `Self` - Translated convex shape.
    #[must_use]
    pub fn translated(&self, delta: Vec3) -> Self {
        match self {
            Self::Sphere { center, radius } => Self::Sphere {
                center: center.add(delta),
                radius: *radius,
            },
            Self::Box {
                center,
                half_extents,
                rotation,
            } => Self::Box {
                center: center.add(delta),
                half_extents: *half_extents,
                rotation: *rotation,
            },
            Self::Capsule {
                center,
                half_height,
                radius,
                rotation,
            } => Self::Capsule {
                center: center.add(delta),
                half_height: *half_height,
                radius: *radius,
                rotation: *rotation,
            },
            Self::Cylinder {
                center,
                half_height,
                radius,
                rotation,
            } => Self::Cylinder {
                center: center.add(delta),
                half_height: *half_height,
                radius: *radius,
                rotation: *rotation,
            },
            Self::ConvexHull {
                vertices,
                position,
                rotation,
            } => Self::ConvexHull {
                vertices: vertices.clone(),
                position: position.add(delta),
                rotation: *rotation,
            },
        }
    }

    /// Evaluates the furthest world-space support point of this shape along `direction`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space search direction.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Support point maximizing `point · direction`.
    #[must_use]
    pub fn support(&self, direction: Vec3) -> Vec3 {
        let dir: Vec3 = if direction.length_sq() > 1e-12 {
            direction
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        };
        match self {
            Self::Sphere { center, radius } => center.add(dir.normalize().scale(radius.max(0.0))),
            Self::Box {
                center,
                half_extents,
                rotation,
            } => {
                let unit_rot: Quat = rotation.normalize();
                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
                let local_pt: Vec3 = Vec3::new(
                    if local_dir.get_x() >= 0.0 {
                        half_extents.get_x().abs()
                    } else {
                        -half_extents.get_x().abs()
                    },
                    if local_dir.get_y() >= 0.0 {
                        half_extents.get_y().abs()
                    } else {
                        -half_extents.get_y().abs()
                    },
                    if local_dir.get_z() >= 0.0 {
                        half_extents.get_z().abs()
                    } else {
                        -half_extents.get_z().abs()
                    },
                );
                center.add(unit_rot.rotate_vec3(local_pt))
            }
            Self::Capsule {
                center,
                half_height,
                radius,
                rotation,
            } => {
                let unit_rot: Quat = rotation.normalize();
                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
                let hh: f32 = half_height.abs();
                let tip_y: f32 = if local_dir.get_y() >= 0.0 { hh } else { -hh };
                let spine_pt: Vec3 = center.add(unit_rot.rotate_vec3(Vec3::new(0.0, tip_y, 0.0)));
                spine_pt.add(dir.normalize().scale(radius.max(0.0)))
            }
            Self::Cylinder {
                center,
                half_height,
                radius,
                rotation,
            } => {
                let unit_rot: Quat = rotation.normalize();
                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
                let hh: f32 = half_height.abs();
                let r: f32 = radius.max(0.0);
                let rad_sq: f32 =
                    local_dir.get_x() * local_dir.get_x() + local_dir.get_z() * local_dir.get_z();
                let (rx, rz): (f32, f32) = if rad_sq > 1e-12 {
                    let inv: f32 = r / rad_sq.sqrt();
                    (local_dir.get_x() * inv, local_dir.get_z() * inv)
                } else {
                    (r, 0.0)
                };
                let ry: f32 = if local_dir.get_y() >= 0.0 { hh } else { -hh };
                center.add(unit_rot.rotate_vec3(Vec3::new(rx, ry, rz)))
            }
            Self::ConvexHull {
                vertices,
                position,
                rotation,
            } => {
                if vertices.is_empty() {
                    return *position;
                }
                let unit_rot: Quat = rotation.normalize();
                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
                let mut best_v: Vec3 = vertices[0];
                let mut best_dot: f32 = best_v.dot(local_dir);
                for &v in &vertices[1..] {
                    let d: f32 = v.dot(local_dir);
                    if d > best_dot {
                        best_dot = d;
                        best_v = v;
                    }
                }
                position.add(unit_rot.rotate_vec3(best_v))
            }
        }
    }
}

/// 3D GJK intersection test and EPA exact penetration solver for `GjkEpaSolver3D`.
impl GjkEpaSolver3D {
    /// Creates a new `GjkEpaSolver3D` with pre-allocated polytope scratch buffers.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready convex collision solver.
    #[must_use]
    pub fn new() -> Self {
        Self {
            scratch: GjkEpaScratch {
                vertices: Vec::with_capacity(64),
                faces: Vec::with_capacity(128),
                loose_edges: Vec::with_capacity(64),
            },
        }
    }

    /// Runs GJK to determine intersection and leaves the enclosing simplex inside `simplex`.
    ///
    /// # Arguments
    ///
    /// - `&ConvexShape3D` - First convex shape A.
    /// - `&ConvexShape3D` - Second convex shape B.
    /// - `&mut Vec<Vec3>` - Reusable vertex buffer populated with the terminating simplex.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `shape_a` and `shape_b` intersect.
    fn run_gjk(shape_a: &ConvexShape3D, shape_b: &ConvexShape3D, simplex: &mut Vec<Vec3>) -> bool {
        simplex.clear();
        let initial_diff: Vec3 = shape_a.center_hint().sub(shape_b.center_hint());
        let mut dir: Vec3 = if initial_diff.length_sq() > 1e-10 {
            initial_diff
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        };
        let first: Vec3 = gjk_support_diff(shape_a, shape_b, dir);
        simplex.push(first);
        if first.length_sq() <= 1e-12 {
            return true;
        }
        dir = first.scale(-1.0);
        for _ in 0..GJK_MAX_ITERS {
            let next_pt: Vec3 = gjk_support_diff(shape_a, shape_b, dir);
            if next_pt.dot(dir) <= 0.0 {
                return false;
            }
            simplex.insert(0, next_pt);
            let hit: bool = match simplex.len() {
                2 => gjk_handle_line(simplex, &mut dir),
                3 => gjk_handle_triangle(simplex, &mut dir),
                4 => gjk_handle_tetrahedron(simplex, &mut dir),
                _ => false,
            };
            if hit {
                return true;
            }
        }
        false
    }

    /// Expands a degenerate 1-, 2-, or 3-vertex hit simplex into a full non-degenerate tetrahedron for EPA.
    ///
    /// # Arguments
    ///
    /// - `&ConvexShape3D` - First convex shape A.
    /// - `&ConvexShape3D` - Second convex shape B.
    /// - `&mut Vec<Vec3>` - Simplex vertices expanded to length `4` when possible.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if a non-degenerate tetrahedron was formed.
    fn blow_up_simplex(
        shape_a: &ConvexShape3D,
        shape_b: &ConvexShape3D,
        verts: &mut Vec<Vec3>,
    ) -> bool {
        let probe_axes: [Vec3; 6] = [
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(-1.0, 0.0, 0.0),
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(0.0, -1.0, 0.0),
            Vec3::new(0.0, 0.0, 1.0),
            Vec3::new(0.0, 0.0, -1.0),
        ];
        if verts.len() == 1 {
            for &axis in &probe_axes {
                let p: Vec3 = gjk_support_diff(shape_a, shape_b, axis);
                if p.sub(verts[0]).length_sq() > 1e-8 {
                    verts.push(p);
                    break;
                }
            }
        }
        if verts.len() == 2 {
            let line: Vec3 = verts[1].sub(verts[0]);
            for &axis in &probe_axes {
                let perp: Vec3 = line.cross(axis);
                if perp.length_sq() <= 1e-10 {
                    continue;
                }
                let p: Vec3 = gjk_support_diff(shape_a, shape_b, perp);
                if line.cross(p.sub(verts[0])).length_sq() > 1e-8 {
                    verts.push(p);
                    break;
                }
            }
        }
        if verts.len() == 3 {
            let normal: Vec3 = verts[1].sub(verts[0]).cross(verts[2].sub(verts[0]));
            let candidates: [Vec3; 2] = [normal, normal.scale(-1.0)];
            for &dir in &candidates {
                if dir.length_sq() <= 1e-12 {
                    continue;
                }
                let p: Vec3 = gjk_support_diff(shape_a, shape_b, dir);
                if normal.dot(p.sub(verts[0])).abs() > 1e-8 {
                    verts.push(p);
                    break;
                }
            }
        }
        verts.len() == 4
    }

    /// Tests whether two convex 3D shapes intersect via GJK.
    ///
    /// # Arguments
    ///
    /// - `&ConvexShape3D` - First convex shape.
    /// - `&ConvexShape3D` - Second convex shape.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the two shapes overlap.
    pub fn intersects(&mut self, shape_a: &ConvexShape3D, shape_b: &ConvexShape3D) -> bool {
        let mut scratch: GjkEpaScratch = take(self.get_mut_scratch());
        let hit: bool = Self::run_gjk(shape_a, shape_b, &mut scratch.vertices);
        self.set_scratch(scratch);
        hit
    }

    /// Runs GJK + EPA to compute exact minimum-translation penetration normal and depth for overlapping shapes.
    ///
    /// # Arguments
    ///
    /// - `&ConvexShape3D` - First convex shape A.
    /// - `&ConvexShape3D` - Second convex shape B.
    ///
    /// # Returns
    ///
    /// - `Option<GjkEpaContact3D>` - MTV contact separating A from B (`A + normal * depth`), or `None` if separated.
    pub fn solve_penetration(
        &mut self,
        shape_a: &ConvexShape3D,
        shape_b: &ConvexShape3D,
    ) -> Option<GjkEpaContact3D> {
        let mut scratch: GjkEpaScratch = take(self.get_mut_scratch());
        let hit: bool = Self::run_gjk(shape_a, shape_b, &mut scratch.vertices);
        if !hit {
            self.set_scratch(scratch);
            return None;
        }
        if scratch.vertices.len() < 4
            && !Self::blow_up_simplex(shape_a, shape_b, &mut scratch.vertices)
        {
            self.set_scratch(scratch);
            return None;
        }
        let interior: Vec3 = scratch.vertices[0]
            .add(scratch.vertices[1])
            .add(scratch.vertices[2])
            .add(scratch.vertices[3])
            .scale(0.25);
        scratch.faces.clear();
        let init_tris: [(usize, usize, usize); 4] = [(0, 1, 2), (0, 2, 3), (0, 3, 1), (1, 3, 2)];
        for &(i0, i1, i2) in &init_tris {
            if let Some(face) = epa_make_face(&scratch.vertices, i0, i1, i2, interior) {
                scratch.faces.push(face);
            }
        }
        if scratch.faces.is_empty() {
            self.set_scratch(scratch);
            return None;
        }
        let mut best_normal: Vec3 = scratch.faces[0].normal;
        let mut best_dist: f32 = scratch.faces[0].distance;
        for _ in 0..EPA_MAX_ITERS {
            let mut closest_idx: usize = 0;
            let mut closest_dist: f32 = f32::INFINITY;
            for (idx, face) in scratch.faces.iter().enumerate() {
                if face.distance < closest_dist {
                    closest_dist = face.distance;
                    closest_idx = idx;
                }
            }
            let closest: EpaFace3D = scratch.faces[closest_idx];
            best_normal = closest.normal;
            best_dist = closest.distance;
            let support_pt: Vec3 = gjk_support_diff(shape_a, shape_b, closest.normal);
            let support_dist: f32 = support_pt.dot(closest.normal);
            if support_dist - closest.distance <= EPA_EPSILON {
                break;
            }
            let mut duplicate: bool = false;
            for &existing in &scratch.vertices {
                if existing.sub(support_pt).length_sq() <= 1e-10 {
                    duplicate = true;
                    break;
                }
            }
            if duplicate {
                break;
            }
            let new_vert_idx: usize = scratch.vertices.len();
            scratch.vertices.push(support_pt);
            scratch.loose_edges.clear();
            let mut f_idx: usize = 0;
            while f_idx < scratch.faces.len() {
                let face: EpaFace3D = scratch.faces[f_idx];
                let v0: Vec3 = scratch.vertices[face.indices[0]];
                if face.normal.dot(support_pt.sub(v0)) > 1e-6 {
                    let edges: [(usize, usize); 3] = [
                        (face.indices[0], face.indices[1]),
                        (face.indices[1], face.indices[2]),
                        (face.indices[2], face.indices[0]),
                    ];
                    for &(eu, ev) in &edges {
                        if let Some(rev_pos) = scratch
                            .loose_edges
                            .iter()
                            .position(|&(lu, lv): &(usize, usize)| lu == ev && lv == eu)
                        {
                            let _: (usize, usize) = scratch.loose_edges.swap_remove(rev_pos);
                        } else {
                            scratch.loose_edges.push((eu, ev));
                        }
                    }
                    let _: EpaFace3D = scratch.faces.swap_remove(f_idx);
                } else {
                    f_idx += 1;
                }
            }
            for &(eu, ev) in &scratch.loose_edges {
                if let Some(new_face) =
                    epa_make_face(&scratch.vertices, eu, ev, new_vert_idx, interior)
                {
                    scratch.faces.push(new_face);
                }
            }
            if scratch.faces.is_empty() {
                break;
            }
        }
        self.set_scratch(scratch);
        let mtv_normal: Vec3 = best_normal.scale(-1.0).normalize();
        let depth: f32 = best_dist.max(0.0);
        Some(GjkEpaContact3D::new(mtv_normal, depth))
    }
}

/// Verlet / PBD cloth construction, pinning, colliders, and simulation steps for `VerletClothSolver`.
impl VerletClothSolver {
    /// Builds a `cols x rows` cloth grid with structural, shear, and 2-hop bend constraints.
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of vertex columns (`>= 2`).
    /// - `usize` - Number of vertex rows (`>= 2`).
    /// - `f32` - Rest spacing between adjacent vertices.
    /// - `Vec3` - Top-left corner world-space origin `(col = 0, row = 0)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized cloth solver lying in the horizontal XZ plane.
    #[must_use]
    pub fn new(cols: usize, rows: usize, spacing: f32, origin: Vec3) -> Self {
        let safe_cols: usize = cols.max(2);
        let safe_rows: usize = rows.max(2);
        let safe_spacing: f32 = if spacing.is_finite() && spacing > 1e-4 {
            spacing
        } else {
            0.25
        };
        let mut particles: Vec<VerletParticle3D> = Vec::with_capacity(safe_cols * safe_rows);
        for r in 0..safe_rows {
            for c in 0..safe_cols {
                let pos: Vec3 = origin.add(Vec3::new(
                    (c as f32) * safe_spacing,
                    0.0,
                    (r as f32) * safe_spacing,
                ));
                particles.push(VerletParticle3D::new(pos, pos, 1.0));
            }
        }
        let mut constraints: Vec<VerletDistanceConstraint> =
            Vec::with_capacity(safe_cols * safe_rows * 6);
        let diag_len: f32 = safe_spacing * SQRT_2;
        let bend_len: f32 = safe_spacing * 2.0;
        for r in 0..safe_rows {
            for c in 0..safe_cols {
                let idx: usize = r * safe_cols + c;
                if c + 1 < safe_cols {
                    constraints.push(VerletDistanceConstraint::new(
                        idx,
                        idx + 1,
                        safe_spacing,
                        1.0,
                    ));
                }
                if r + 1 < safe_rows {
                    constraints.push(VerletDistanceConstraint::new(
                        idx,
                        idx + safe_cols,
                        safe_spacing,
                        1.0,
                    ));
                }
                if c + 1 < safe_cols && r + 1 < safe_rows {
                    constraints.push(VerletDistanceConstraint::new(
                        idx,
                        idx + safe_cols + 1,
                        diag_len,
                        0.85,
                    ));
                    constraints.push(VerletDistanceConstraint::new(
                        idx + 1,
                        idx + safe_cols,
                        diag_len,
                        0.85,
                    ));
                }
                if c + 2 < safe_cols {
                    constraints.push(VerletDistanceConstraint::new(idx, idx + 2, bend_len, 0.5));
                }
                if r + 2 < safe_rows {
                    constraints.push(VerletDistanceConstraint::new(
                        idx,
                        idx + safe_cols * 2,
                        bend_len,
                        0.5,
                    ));
                }
            }
        }
        Self {
            cols: safe_cols,
            rows: safe_rows,
            gravity: Vec3::new(0.0, -9.81, 0.0),
            wind: Vec3::zero(),
            damping: VERLET_DAMPING,
            solver_iterations: 6,
            particles,
            constraints,
            sphere_colliders: Vec::new(),
            plane_colliders: Vec::new(),
        }
    }

    /// Permanently pins cloth vertex `(col, row)` as an immovable anchor (`inv_mass = 0.0`).
    ///
    /// # Arguments
    ///
    /// - `usize` - Column index.
    /// - `usize` - Row index.
    pub fn pin_particle(&mut self, col: usize, row: usize) {
        let cols: usize = self.get_cols();
        let rows: usize = self.get_rows();
        if col < cols && row < rows {
            self.get_mut_particles()[row * cols + col].set_inv_mass(0.0);
        }
    }

    /// Registers a solid sphere collider interacting with free cloth particles.
    ///
    /// # Arguments
    ///
    /// - `VerletSphereCollider` - Sphere collider descriptor.
    pub fn add_sphere_collider(&mut self, collider: VerletSphereCollider) {
        self.get_mut_sphere_colliders().push(collider);
    }

    /// Registers a solid infinite plane collider interacting with free cloth particles.
    ///
    /// # Arguments
    ///
    /// - `VerletPlaneCollider` - Plane collider descriptor.
    pub fn add_plane_collider(&mut self, collider: VerletPlaneCollider) {
        self.get_mut_plane_colliders().push(collider);
    }

    /// Advances the cloth simulation by `dt` with zero steady-state heap allocations.
    ///
    /// # Arguments
    ///
    /// - `f32` - Simulation time step in seconds.
    pub fn step(&mut self, dt: f32) {
        if !dt.is_finite() || dt <= 1e-6 {
            return;
        }
        let accel: Vec3 = self.get_gravity().add(self.get_wind());
        let accel_dt2: Vec3 = accel.scale(dt * dt);
        let damping: f32 = self.get_damping().clamp(0.0, 1.0);
        let iterations: usize = self.get_solver_iterations();
        let mut particles: Vec<VerletParticle3D> = take(self.get_mut_particles());
        for particle in &mut particles {
            if particle.get_inv_mass() <= 0.0 {
                continue;
            }
            let pos: Vec3 = particle.get_position();
            let vel: Vec3 = pos.sub(particle.get_prev_position()).scale(damping);
            particle.set_prev_position(pos);
            particle.set_position(pos.add(vel).add(accel_dt2));
        }
        verlet_project_constraints(
            &mut particles,
            self.get_constraints(),
            self.get_sphere_colliders(),
            self.get_plane_colliders(),
            iterations,
        );
        self.set_particles(particles);
    }
}

/// Verlet / PBD rope construction, pinning, colliders, and simulation steps for `VerletRopeSolver`.
impl VerletRopeSolver {
    /// Builds a 1D rope chain with structural distance and 2-hop bend stiffness constraints.
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of particles along the rope (`>= 2`).
    /// - `f32` - Rest length of each rope segment.
    /// - `Vec3` - World-space starting anchor position.
    /// - `Vec3` - Initial extension direction (normalized internally).
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized rope solver.
    #[must_use]
    pub fn new(count: usize, segment_length: f32, start: Vec3, direction: Vec3) -> Self {
        let safe_count: usize = count.max(2);
        let safe_len: f32 = if segment_length.is_finite() && segment_length > 1e-4 {
            segment_length
        } else {
            0.25
        };
        let unit_dir: Vec3 = if direction.length_sq() > 1e-10 {
            direction.normalize()
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        };
        let mut particles: Vec<VerletParticle3D> = Vec::with_capacity(safe_count);
        for i in 0..safe_count {
            let pos: Vec3 = start.add(unit_dir.scale((i as f32) * safe_len));
            particles.push(VerletParticle3D::new(pos, pos, 1.0));
        }
        let mut constraints: Vec<VerletDistanceConstraint> = Vec::with_capacity(safe_count * 2);
        for i in 0..(safe_count - 1) {
            constraints.push(VerletDistanceConstraint::new(i, i + 1, safe_len, 1.0));
        }
        for i in 0..safe_count.saturating_sub(2) {
            constraints.push(VerletDistanceConstraint::new(
                i,
                i + 2,
                safe_len * 2.0,
                0.35,
            ));
        }
        Self {
            gravity: Vec3::new(0.0, -9.81, 0.0),
            wind: Vec3::zero(),
            damping: VERLET_DAMPING,
            solver_iterations: 8,
            particles,
            constraints,
            sphere_colliders: Vec::new(),
            plane_colliders: Vec::new(),
        }
    }

    /// Permanently pins rope particle `index` (`inv_mass = 0.0`).
    ///
    /// # Arguments
    ///
    /// - `usize` - Particle index to pin.
    pub fn pin_particle(&mut self, index: usize) {
        if let Some(particle) = self.get_mut_particles().get_mut(index) {
            particle.set_inv_mass(0.0);
        }
    }

    /// Registers a solid sphere collider interacting with free rope particles.
    ///
    /// # Arguments
    ///
    /// - `VerletSphereCollider` - Sphere collider descriptor.
    pub fn add_sphere_collider(&mut self, collider: VerletSphereCollider) {
        self.get_mut_sphere_colliders().push(collider);
    }

    /// Registers a solid plane collider interacting with free rope particles.
    ///
    /// # Arguments
    ///
    /// - `VerletPlaneCollider` - Plane collider descriptor.
    pub fn add_plane_collider(&mut self, collider: VerletPlaneCollider) {
        self.get_mut_plane_colliders().push(collider);
    }

    /// Advances the rope simulation by `dt` with zero steady-state heap allocations.
    ///
    /// # Arguments
    ///
    /// - `f32` - Simulation time step in seconds.
    pub fn step(&mut self, dt: f32) {
        if !dt.is_finite() || dt <= 1e-6 {
            return;
        }
        let accel: Vec3 = self.get_gravity().add(self.get_wind());
        let accel_dt2: Vec3 = accel.scale(dt * dt);
        let damping: f32 = self.get_damping().clamp(0.0, 1.0);
        let iterations: usize = self.get_solver_iterations();
        let mut particles: Vec<VerletParticle3D> = take(self.get_mut_particles());
        for particle in &mut particles {
            if particle.get_inv_mass() <= 0.0 {
                continue;
            }
            let pos: Vec3 = particle.get_position();
            let vel: Vec3 = pos.sub(particle.get_prev_position()).scale(damping);
            particle.set_prev_position(pos);
            particle.set_position(pos.add(vel).add(accel_dt2));
        }
        verlet_project_constraints(
            &mut particles,
            self.get_constraints(),
            self.get_sphere_colliders(),
            self.get_plane_colliders(),
            iterations,
        );
        self.set_particles(particles);
    }
}

/// Default settings for `CameraRigConfig`.
impl Default for CameraRigConfig {
    /// Returns balanced third-person Spring-Arm camera rig defaults.
    ///
    /// # Returns
    ///
    /// - `Self` - Default camera rig configuration.
    fn default() -> Self {
        Self {
            mode: CameraRigMode::SpringArm,
            arm_length: 6.0,
            arm_min_length: 0.5,
            pivot_offset: Vec3::new(0.0, 1.5, 0.0),
            position_stiffness: 10.0,
            rotation_stiffness: 12.0,
            min_pitch: -1.35,
            max_pitch: 1.35,
            eye_height: 1.7,
            fov_deg: 60.0,
            near: 0.1,
            far: 500.0,
            trauma_decay: 1.5,
            shake_max_offset: 0.35,
            shake_max_angle_rad: 0.08,
            shake_frequency: 14.0,
            spline_loop: false,
        }
    }
}

/// Conversion into `Camera3D` for `CameraRigState`.
impl CameraRigState {
    /// Converts this rig output pose into a standard `Camera3D` for `euv-core` rendering.
    ///
    /// # Arguments
    ///
    /// - `f32` - Near clipping plane distance.
    /// - `f32` - Far clipping plane distance.
    ///
    /// # Returns
    ///
    /// - `Camera3D` - Ready perspective camera.
    #[must_use]
    pub fn to_camera3d(&self, near: f32, far: f32) -> Camera3D {
        let mut cam: Camera3D = Camera3D::default();
        cam.set_position(self.get_position());
        cam.set_yaw(self.get_yaw());
        cam.set_pitch(self.get_pitch());
        cam.set_fov_deg(self.get_fov_deg());
        cam.set_near(near);
        cam.set_far(far);
        cam
    }
}

/// Spring-Arm, Orbit, First-Person, Catmull-Rom Spline Rail, and Perlin Trauma Shake for `CameraRig3D`.
impl CameraRig3D {
    /// Creates a new `CameraRig3D` from `config` and deterministic Perlin shake `seed`.
    ///
    /// # Arguments
    ///
    /// - `CameraRigConfig` - Camera rig settings.
    /// - `u64` - Seed for deterministic Perlin trauma shake.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized camera rig.
    #[must_use]
    pub fn new(config: CameraRigConfig, seed: u64) -> Self {
        let arm_len: f32 = config
            .get_arm_length()
            .max(config.get_arm_min_length().max(0.1));
        let init_pos: Vec3 = Vec3::new(0.0, config.get_pivot_offset().get_y(), arm_len);
        let init_target: Vec3 = config.get_pivot_offset();
        let state: CameraRigState = CameraRigState::new(
            init_pos,
            init_target,
            Quat::identity(),
            0.0,
            0.0,
            0.0,
            config.get_fov_deg(),
        );
        Self {
            config,
            desired_yaw: 0.0,
            desired_pitch: 0.0,
            smooth_position: init_pos,
            smooth_target: init_target,
            smooth_yaw: 0.0,
            smooth_pitch: 0.0,
            smooth_fov_deg: config.get_fov_deg(),
            current_arm_length: arm_len,
            trauma: 0.0,
            shake_clock: 0.0,
            spline_t: 0.0,
            spline_points: Vec::new(),
            noise: NoiseField::new(seed),
            state,
        }
    }

    /// Applies yaw and pitch input deltas in radians, clamping pitch inside configured limits.
    ///
    /// # Arguments
    ///
    /// - `f32` - Horizontal yaw delta in radians.
    /// - `f32` - Vertical pitch delta in radians.
    pub fn apply_look_delta(&mut self, delta_yaw: f32, delta_pitch: f32) {
        if delta_yaw.is_finite() {
            self.set_desired_yaw(self.get_desired_yaw() + delta_yaw);
        }
        if delta_pitch.is_finite() {
            let cfg: CameraRigConfig = self.get_config();
            let clamped: f32 = (self.get_desired_pitch() + delta_pitch)
                .clamp(cfg.get_min_pitch(), cfg.get_max_pitch());
            self.set_desired_pitch(clamped);
        }
    }

    /// Adds impact trauma clamped into `[0.0, 1.0]` to trigger smooth Perlin camera shake.
    ///
    /// # Arguments
    ///
    /// - `f32` - Non-negative trauma impulse.
    pub fn add_trauma(&mut self, amount: f32) {
        if amount.is_finite() && amount > 0.0 {
            self.set_trauma((self.get_trauma() + amount).clamp(0.0, 1.0));
        }
    }

    /// Evaluates the Catmull-Rom cinematic spline rail at normalized parameter `t` in `[0.0, 1.0]`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Normalized spline progress in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Option<CameraSplinePoint>` - Interpolated eye position, look target, and FOV.
    #[must_use]
    pub fn sample_spline(&self, t: f32) -> Option<CameraSplinePoint> {
        let pts: &[CameraSplinePoint] = self.get_spline_points();
        let n: usize = pts.len();
        if n == 0 {
            return None;
        }
        if n == 1 {
            return Some(pts[0]);
        }
        let looping: bool = self.get_config().get_spline_loop();
        let clamped_t: f32 = if looping {
            t.rem_euclid(1.0)
        } else {
            t.clamp(0.0, 1.0)
        };
        let seg_count: usize = if looping { n } else { n - 1 };
        let scaled: f32 = clamped_t * (seg_count as f32);
        let seg_idx: usize = (scaled.floor() as usize).min(seg_count - 1);
        let local_t: f32 = (scaled - (seg_idx as f32)).clamp(0.0, 1.0);
        let (i0, i1, i2, i3): (usize, usize, usize, usize) = if looping {
            (
                (seg_idx + n - 1) % n,
                seg_idx % n,
                (seg_idx + 1) % n,
                (seg_idx + 2) % n,
            )
        } else {
            (
                seg_idx.saturating_sub(1),
                seg_idx,
                (seg_idx + 1).min(n - 1),
                (seg_idx + 2).min(n - 1),
            )
        };
        let p0: CameraSplinePoint = pts[i0];
        let p1: CameraSplinePoint = pts[i1];
        let p2: CameraSplinePoint = pts[i2];
        let p3: CameraSplinePoint = pts[i3];
        Some(CameraSplinePoint::new(
            catmull_rom_vec3(
                p0.get_position(),
                p1.get_position(),
                p2.get_position(),
                p3.get_position(),
                local_t,
            ),
            catmull_rom_vec3(
                p0.get_look_target(),
                p1.get_look_target(),
                p2.get_look_target(),
                p3.get_look_target(),
                local_t,
            ),
            catmull_rom_f32(
                p0.get_fov_deg(),
                p1.get_fov_deg(),
                p2.get_fov_deg(),
                p3.get_fov_deg(),
                local_t,
            )
            .clamp(10.0, 150.0),
        ))
    }

    /// Updates the camera rig for frame step `dt`, resolving spring-arm obstacles and Perlin trauma shake.
    ///
    /// # Arguments
    ///
    /// - `f32` - Frame delta time in seconds.
    /// - `Vec3` - Followed subject anchor position in world space.
    /// - `&[AxisAlignedBox3D]` - World geometry obstacles for spring-arm ray pullback.
    ///
    /// # Returns
    ///
    /// - `CameraRigState` - Updated world-space camera pose for this frame.
    pub fn update(
        &mut self,
        dt: f32,
        follow_target: Vec3,
        obstacles: &[AxisAlignedBox3D],
    ) -> CameraRigState {
        let safe_dt: f32 = if dt.is_finite() && dt > 0.0 { dt } else { 0.0 };
        let cfg: CameraRigConfig = self.get_config();
        let pos_alpha: f32 = 1.0 - (-cfg.get_position_stiffness().max(0.1) * safe_dt).exp();
        let rot_alpha: f32 = 1.0 - (-cfg.get_rotation_stiffness().max(0.1) * safe_dt).exp();
        let next_yaw: f32 =
            self.get_smooth_yaw() + (self.get_desired_yaw() - self.get_smooth_yaw()) * rot_alpha;
        let clamped_desired_pitch: f32 = self
            .get_desired_pitch()
            .clamp(cfg.get_min_pitch(), cfg.get_max_pitch());
        let next_pitch: f32 =
            self.get_smooth_pitch() + (clamped_desired_pitch - self.get_smooth_pitch()) * rot_alpha;
        self.set_smooth_yaw(next_yaw);
        self.set_smooth_pitch(next_pitch);
        let cp: f32 = next_pitch.cos();
        let sp: f32 = next_pitch.sin();
        let sy: f32 = next_yaw.sin();
        let cy: f32 = next_yaw.cos();
        let forward: Vec3 = Vec3::new(sy * cp, sp, -cy * cp).normalize();
        let (goal_pos, goal_target, goal_fov, base_yaw, base_pitch): (Vec3, Vec3, f32, f32, f32) =
            match cfg.get_mode() {
                CameraRigMode::SpringArm => {
                    let pivot: Vec3 = follow_target.add(cfg.get_pivot_offset());
                    let arm_dir: Vec3 = forward.scale(-1.0);
                    let max_arm: f32 = cfg.get_arm_length().max(cfg.get_arm_min_length().max(0.1));
                    let min_arm: f32 = cfg.get_arm_min_length().clamp(0.05, max_arm);
                    let mut target_arm: f32 = max_arm;
                    if !obstacles.is_empty() {
                        let ray: Ray3D = Ray3D::new(pivot, arm_dir);
                        for obs in obstacles {
                            let hit_t: f32 = obs.intersect_ray_near(
                                ray.get_origin(),
                                ray.get_inv_direction(),
                                0.0,
                                target_arm,
                            );
                            if hit_t.is_finite() && hit_t < target_arm {
                                target_arm = (hit_t - CAMERA_ARM_MARGIN).clamp(min_arm, max_arm);
                            }
                        }
                    }
                    let smoothed_arm: f32 = if target_arm < self.get_current_arm_length() {
                        target_arm
                    } else {
                        self.get_current_arm_length()
                            + (target_arm - self.get_current_arm_length()) * pos_alpha
                    };
                    self.set_current_arm_length(smoothed_arm);
                    (
                        pivot.add(arm_dir.scale(smoothed_arm)),
                        pivot,
                        cfg.get_fov_deg(),
                        next_yaw,
                        next_pitch,
                    )
                }
                CameraRigMode::Orbit => {
                    let pivot: Vec3 = follow_target.add(cfg.get_pivot_offset());
                    let dist: f32 = cfg.get_arm_length().max(0.1);
                    let eye: Vec3 = pivot.sub(forward.scale(dist));
                    (eye, pivot, cfg.get_fov_deg(), next_yaw, next_pitch)
                }
                CameraRigMode::FirstPerson => {
                    let eye: Vec3 = follow_target.add(Vec3::new(0.0, cfg.get_eye_height(), 0.0));
                    let focus: Vec3 = eye.add(forward);
                    (eye, focus, cfg.get_fov_deg(), next_yaw, next_pitch)
                }
                CameraRigMode::SplineRail => {
                    if let Some(sample) = self.sample_spline(self.get_spline_t()) {
                        let look: Vec3 = sample
                            .get_look_target()
                            .sub(sample.get_position())
                            .normalize();
                        let s_yaw: f32 = look.get_x().atan2(-look.get_z());
                        let s_pitch: f32 = look.get_y().clamp(-1.0, 1.0).asin();
                        (
                            sample.get_position(),
                            sample.get_look_target(),
                            sample.get_fov_deg(),
                            s_yaw,
                            s_pitch,
                        )
                    } else {
                        (
                            self.get_smooth_position(),
                            self.get_smooth_target(),
                            cfg.get_fov_deg(),
                            next_yaw,
                            next_pitch,
                        )
                    }
                }
            };
        let next_pos: Vec3 = self.get_smooth_position().lerp(goal_pos, pos_alpha);
        let next_target: Vec3 = self.get_smooth_target().lerp(goal_target, pos_alpha);
        let next_fov: f32 =
            self.get_smooth_fov_deg() + (goal_fov - self.get_smooth_fov_deg()) * pos_alpha;
        self.set_smooth_position(next_pos);
        self.set_smooth_target(next_target);
        self.set_smooth_fov_deg(next_fov);
        let clock: f32 = self.get_shake_clock() + safe_dt * cfg.get_shake_frequency().max(0.1);
        self.set_shake_clock(clock);
        let cur_trauma: f32 = self.get_trauma();
        let shake_amp: f32 = cur_trauma * cur_trauma;
        let next_trauma: f32 = (cur_trauma - cfg.get_trauma_decay().max(0.0) * safe_dt).max(0.0);
        self.set_trauma(next_trauma);
        let (shake_pos, shake_yaw, shake_pitch, shake_roll): (Vec3, f32, f32, f32) =
            if shake_amp > 1e-6 {
                let max_off: f32 = cfg.get_shake_max_offset() * shake_amp;
                let max_ang: f32 = cfg.get_shake_max_angle_rad() * shake_amp;
                let noise: &NoiseField = self.get_noise();
                (
                    Vec3::new(
                        noise.perlin_2d(clock, 1.37) * max_off,
                        noise.perlin_2d(clock, 5.91) * max_off,
                        noise.perlin_2d(clock, 11.43) * max_off,
                    ),
                    noise.perlin_2d(clock, 17.83) * max_ang,
                    noise.perlin_2d(clock, 23.19) * max_ang,
                    noise.perlin_2d(clock, 31.67) * max_ang,
                )
            } else {
                (Vec3::zero(), 0.0, 0.0, 0.0)
            };
        let final_pos: Vec3 = next_pos.add(shake_pos);
        let final_yaw: f32 = base_yaw + shake_yaw;
        let final_pitch: f32 =
            (base_pitch + shake_pitch).clamp(cfg.get_min_pitch(), cfg.get_max_pitch());
        let final_rot: Quat = Quat::from_euler_yxz(final_yaw, final_pitch, shake_roll);
        let final_state: CameraRigState = CameraRigState::new(
            final_pos,
            next_target,
            final_rot,
            final_yaw,
            final_pitch,
            shake_roll,
            next_fov,
        );
        self.set_state(final_state);
        final_state
    }
}