aada 0.1.1

纯 Rust 的 2D 骨骼动画引擎,兼容 Spine 4.x 导出格式(JSON + atlas)。求解到分层 Mesh 与各 Mesh 渲染设置为止,之后交给渲染器。
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
//! 运行时动画数据与采样器。
//!
//! [`AnimateSet`] 保存全部动画(骨骼时间轴 / slot 时间轴 / 约束时间轴 / deform / draw order)。
//! [`AnimateSet::sample`] 配合跨帧复用的 [`AnimateConfig`](连续时间采样 O(1) 加速)输出
//! [`SampledAnimate`],再由 `apply_pose` / `apply_constraints` 应用到姿态与约束状态。
//! 采样语义遵循官方 spine:t 在时间轴首帧之前时间轴未生效,t 超出末帧后取末帧值。

use crate::{
    cacl::curve::{prebuild_curve, sample_curve, Bezier, CurveSampling, Pt2},
    custom_index::NameMap,
    data::runtime::skeleton::{BoneIdx, Pose},
    data::runtime::skin::AttachmentNameIdx,
    new_index,
};

new_index!(AnimIdx);

/// 骨骼通道类型,对应 [crate::data::runtime::skeleton::BoneData] 中的各个可动画字段
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum BoneChannel {
    TranslateX,
    TranslateY,
    Rotate,
    ScaleX,
    ScaleY,
    ShearX,
    ShearY,
}

/// slot 动画时间轴类型
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SlotChannel {
    /// 颜色时间轴(RGBA 各分量独立插值)
    Color,
    /// attachment 切换时间轴(step 语义,无插值)
    Attachment,
}

/// 贝塞尔曲线,作为两个关键帧之间的插值
///
/// 控制点 (cx1,cy1)、(cx2,cy2) 与关键帧处于同一坐标系:X 轴为时间(秒),Y 轴为值。
/// 即 spine 数据格式中的 curve 数组原样存储("The X axis unit is frame and the Y axis unit is value")。
/// 求值在 (time, value) 绝对坐标系进行:构建期 [`AnimationRT::prebuild_curves`] 预采样成点表,
/// 运行期查表二分插值;未预采样时 [`BezierCurve::eval`] 用默认采样方式即时生成
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BezierCurve {
    pub cx1: f32,
    pub cy1: f32,
    pub cx2: f32,
    pub cy2: f32,
}

/// 未做构建期预采样(fallback)时的默认采样方式:自适应细分,eps 解释为"帧段值域的比例"(1%)
pub const DEFAULT_CURVE_SAMPLING: CurveSampling = CurveSampling::Adaptive { eps: 0.01 };

/// 把 Adaptive 的 eps 从"绝对误差"转换为"帧段值域的比例":
/// 固定绝对 eps 会让小值域曲线(如 ScaleX 0.007)被判为平直而退化成 2 点直线,
/// 大值域曲线(如 Rotate 50°)又被过度细分到上百点。
/// 改为 `eps = sy * 比例` 后,各通道的相对精度一致。
fn scaled_sampling(method: CurveSampling, sy: f32) -> CurveSampling {
    match method {
        CurveSampling::Adaptive { eps } => CurveSampling::Adaptive {
            eps: sy.max(1e-6) * eps,
        },
        other => other,
    }
}

impl BezierCurve {
    pub fn new(cx1: f32, cy1: f32, cx2: f32, cy2: f32) -> Self {
        Self { cx1, cy1, cx2, cy2 }
    }
    /// 转成 cacl 的绝对坐标贝塞尔(P0=(time1,value1),控制点即 curve 数组,P3=(time2,value2))
    pub fn to_bezier(&self, time1: f32, value1: f32, time2: f32, value2: f32) -> Bezier {
        Bezier {
            p0: [time1, value1],
            p1: [self.cx1, self.cy1],
            p2: [self.cx2, self.cy2],
            p3: [time2, value2],
        }
    }
    /// 按指定方式把该曲线在帧段 `[time1,time2]` 上预采样成点表(端点取反求 τ 的上升分支)
    pub fn prebuild(
        &self,
        method: CurveSampling,
        time1: f32,
        value1: f32,
        time2: f32,
        value2: f32,
    ) -> Vec<Pt2> {
        prebuild_curve(&self.to_bezier(time1, value1, time2, value2), method)
    }
    /// 在帧段 [time1, time2] 上求值,返回 time 时刻的值(查预采样点表;未预采样时即时生成)
    pub fn eval(&self, time: f32, time1: f32, value1: f32, time2: f32, value2: f32) -> f32 {
        let method = scaled_sampling(DEFAULT_CURVE_SAMPLING, (value2 - value1).abs());
        let pts = self.prebuild(method, time1, value1, time2, value2);
        sample_curve(&pts, time)
    }
}

/// 两个关键帧之间的插值曲线
#[derive(Debug, Clone, PartialEq)]
pub enum Curve {
    /// 线性插值
    Linear,
    /// 保持前一帧的值,到下一帧跳变
    Step,
    /// 贝塞尔曲线(控制点为绝对 time/value 坐标);第二字段为构建期
    /// [`AnimationRT::prebuild_curves`] 生成的预采样点表(x 单调覆盖帧段,运行时二分查表),None = 未预采样
    Bezier(BezierCurve, Option<Vec<Pt2>>),
}

impl Curve {
    /// 在帧段 [time1, time2] 上求值,返回 time 时刻的值
    pub fn eval(&self, time: f32, time1: f32, value1: f32, time2: f32, value2: f32) -> f32 {
        match self {
            Curve::Linear => {
                let t = (time - time1) / (time2 - time1);
                value1 + (value2 - value1) * t
            }
            Curve::Step => value1,
            Curve::Bezier(_, Some(points)) => sample_curve(points, time),
            Curve::Bezier(curve, None) => curve.eval(time, time1, value1, time2, value2),
        }
    }
}

/// 一个关键帧
#[derive(Debug, Clone, PartialEq)]
pub struct Keyframe {
    pub time: f32,
    pub value: f32,
    /// 该帧到下一帧之间的曲线
    pub curve: Curve,
}

/// slot 关键帧
///
/// 一个时间轴内的所有帧类型一致(由 [SlotTimeline::channel] 决定)
#[derive(Debug, Clone, PartialEq)]
pub enum SlotKeyframe {
    /// 颜色帧,RGBA 分量 0-1,到下一帧之间按 curves 插值(每通道独立曲线,spine 4.1 语义)
    Color {
        time: f32,
        rgba: [f32; 4],
        curves: [Curve; 4],
    },
    /// attachment 帧,step 语义:命中帧立即切换,None 表示移除 attachment
    Attachment { time: f32, name: Option<AttachmentNameIdx> },
}

impl SlotKeyframe {
    pub fn time(&self) -> f32 {
        match self {
            SlotKeyframe::Color { time, .. } | SlotKeyframe::Attachment { time, .. } => *time,
        }
    }
}

/// 一个 slot 的时间轴,帧按 time 升序排列
#[derive(Debug, Clone, PartialEq)]
pub struct SlotTimeline {
    pub slot: crate::data::runtime::slot::SlotIdx,
    pub channel: SlotChannel,
    pub frames: Vec<SlotKeyframe>,
}

/// 一根骨骼的一个通道的时间轴,帧按 time 升序排列
#[derive(Debug, Clone, PartialEq)]
pub struct Timeline {
    pub bone: BoneIdx,
    pub channel: BoneChannel,
    pub frames: Vec<Keyframe>,
}

/// 约束参数关键帧(step 语义)
///
/// 帧内未出现的字段(None)表示不覆盖,保持骨架默认值或上一帧的值
#[derive(Debug, Clone, PartialEq)]
pub enum ConstraintKeyframe {
    Ik {
        time: f32,
        mix: Option<f32>,
        bend_positive: Option<bool>,
        compress: Option<bool>,
        stretch: Option<bool>,
    },
    Transform {
        time: f32,
        mix_rotate: Option<f32>,
        mix_x: Option<f32>,
        mix_y: Option<f32>,
        mix_scale_x: Option<f32>,
        mix_scale_y: Option<f32>,
        mix_shear_y: Option<f32>,
    },
}

impl ConstraintKeyframe {
    pub fn time(&self) -> f32 {
        match self {
            ConstraintKeyframe::Ik { time, .. } | ConstraintKeyframe::Transform { time, .. } => {
                *time
            }
        }
    }
}

/// 一个约束的时间轴,帧按 time 升序排列
#[derive(Debug, Clone, PartialEq)]
pub struct ConstraintTimeline {
    /// 指向 [crate::data::runtime::constraint::ConstraintSet] 中的约束
    pub index: crate::data::runtime::constraint::ConstraintIdx,
    pub frames: Vec<ConstraintKeyframe>,
}

/// deform 帧:完整顶点数组(每顶点 2 个分量),加权网格为 delta、非加权为绝对位置
#[derive(Debug, Clone, PartialEq)]
pub struct DeformFrame {
    pub time: f32,
    pub vertices: Vec<f32>,
    /// 该帧到下一帧之间的曲线(帧级:所有顶点共用)
    pub curve: Curve,
}

/// 网格顶点变形时间轴
///
/// deform 时间轴挂在具体 attachment(网格)上,运行时按 (slot, mesh) 匹配当前显示的网格,
/// 与官方 spine 的 `timelineAttachment` 语义一致(避免把别的 attachment 的形变应用到当前网格)
#[derive(Debug, Clone, PartialEq)]
pub struct DeformTimeline {
    pub slot: crate::data::runtime::slot::SlotIdx,
    /// 该 deform 时间轴所属的网格(解析期由 (skin, slot, attachment) 解析得到)
    pub mesh: crate::data::runtime::mesh::MeshIdx,
    pub frames: Vec<DeformFrame>,
}

/// draw order 帧:完整 setup slot 索引排列(第 i 个绘制位置的 slot setup 索引);None = setup 顺序
#[derive(Debug, Clone, PartialEq)]
pub struct DrawOrderFrame {
    pub time: f32,
    pub order: Option<Vec<i32>>,
}

/// 绘制顺序时间轴(step 语义)
#[derive(Debug, Clone, PartialEq)]
pub struct DrawOrderTimeline {
    pub frames: Vec<DrawOrderFrame>,
}

/// 运行时动画数据(静态不变,可 Arc 共享)
#[derive(Debug, Clone)]
pub struct AnimationRT {
    pub name: String,
    /// 动画总时长(最后一帧时间)
    pub duration: f32,
    pub timelines: Vec<Timeline>,
    /// slot 动画时间轴(颜色 / attachment 切换)
    pub slot_timelines: Vec<SlotTimeline>,
    /// 约束动画时间轴(ik / transform 参数覆盖)
    pub constraint_timelines: Vec<ConstraintTimeline>,
    /// 网格顶点变形时间轴
    pub deform_timelines: Vec<DeformTimeline>,
    /// 绘制顺序时间轴
    pub draw_order_timeline: Option<DrawOrderTimeline>,
}

impl AnimationRT {
    /// 构建期预采样:把时间轴里所有贝塞尔段生成点表(`Curve::Bezier(bc, None)` → `Curve::Bezier(bc, Some(pts))`),
    /// 运行期 `sample_curve` 二分查表,不再逐次计算。
    ///
    /// 每段曲线在帧段 `[time1,value1]` → `[time2,value2]` 上按 `method` 采样,
    /// 端点用反求 τ 的上升分支(回绕曲线不会取 τ=1 的 value2 终点分支)。
    /// 最后一帧的曲线没有下一帧,不会被求值,保持原样。
    pub fn prebuild_curves(&mut self, method: CurveSampling) {
        for tl in &mut self.timelines {
            let n = tl.frames.len();
            for i in 0..n.saturating_sub(1) {
                let (t0, v0) = (tl.frames[i].time, tl.frames[i].value);
                let (t1, v1) = (tl.frames[i + 1].time, tl.frames[i + 1].value);
                if let Curve::Bezier(bc, _) = tl.frames[i].curve {
                    let m = scaled_sampling(method, (v1 - v0).abs());
                    tl.frames[i].curve = Curve::Bezier(bc, Some(bc.prebuild(m, t0, v0, t1, v1)));
                }
            }
        }
        for tl in &mut self.slot_timelines {
            let n = tl.frames.len();
            for i in 0..n.saturating_sub(1) {
                let (t0, t1) = (tl.frames[i].time(), tl.frames[i + 1].time());
                let (SlotKeyframe::Color { rgba: c0, curves, .. }, SlotKeyframe::Color { rgba: c1, .. }) =
                    (&tl.frames[i], &tl.frames[i + 1])
                else {
                    continue;
                };
                let mut new_curves = [Curve::Linear, Curve::Linear, Curve::Linear, Curve::Linear];
                for k in 0..4 {
                    new_curves[k] = match &curves[k] {
                        Curve::Bezier(bc, _) => {
                            let m = scaled_sampling(method, (c1[k] - c0[k]).abs());
                            Curve::Bezier(*bc, Some(bc.prebuild(m, t0, c0[k], t1, c1[k])))
                        }
                        other => other.clone(),
                    };
                }
                if let SlotKeyframe::Color { curves: dest, .. } = &mut tl.frames[i] {
                    *dest = new_curves;
                }
            }
        }
        for tl in &mut self.deform_timelines {
            let n = tl.frames.len();
            for i in 0..n.saturating_sub(1) {
                let (t0, t1) = (tl.frames[i].time, tl.frames[i + 1].time);
                if let Curve::Bezier(bc, _) = &tl.frames[i].curve {
                    let m = scaled_sampling(method, 1.0); // deform 帧段值域为 0..1
                    tl.frames[i].curve =
                        Curve::Bezier(*bc, Some(bc.prebuild(m, t0, 0.0, t1, 1.0)));
                }
            }
        }
    }
}

/// 运行时动画集合(静态不变),通过名称一次性查索引,之后全走索引操作
#[derive(Debug, Clone)]
pub struct AnimateSet {
    data: NameMap<AnimIdx, AnimationRT>,
}

impl Default for AnimateSet {
    fn default() -> Self {
        Self::new()
    }
}

impl AnimateSet {
    pub fn new() -> Self {
        Self {
            data: NameMap::new(),
        }
    }
    pub fn insert(&mut self, name: impl Into<String>, animation: AnimationRT) -> AnimIdx {
        self.data.insert(name.into(), animation)
    }
    pub fn get_index(&self, name: &str) -> Option<AnimIdx> {
        self.data.get_index(name)
    }
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.data.keys()
    }
    /// 动画总时长(秒)
    pub fn duration(&self, anim: AnimIdx) -> f32 {
        self.data[anim].duration
    }
    /// slot 时间轴数量
    pub fn slot_timeline_count(&self, anim: AnimIdx) -> usize {
        self.data[anim].slot_timelines.len()
    }
    /// slot 时间轴(诊断/调试用)
    pub fn slot_timelines(&self, anim: AnimIdx) -> &[SlotTimeline] {
        &self.data[anim].slot_timelines
    }
    /// slot 时间轴可变访问(运行时注入/测试用)
    pub fn slot_timelines_mut(&mut self, anim: AnimIdx) -> &mut Vec<SlotTimeline> {
        &mut self.data[anim].slot_timelines
    }
    /// 采样指定动画在 t 时刻的值,结果不会直接修改 Pose
    ///
    /// t 会被裁剪到 [0, duration],超出部分取最后一帧的值
    pub fn sample(&self, anim: AnimIdx, config: &mut AnimateConfig, t: f32) -> SampledAnimate {
        let animation = &self.data[anim];
        if config.anim_idx != Some(anim) {
            config.anim_idx = Some(anim);
            config.last_frames.clear();
            config.last_frames.resize(
                animation.timelines.len() + animation.slot_timelines.len(),
                0,
            );
        }
        let mut values = Vec::with_capacity(animation.timelines.len());
        for (i, timeline) in animation.timelines.iter().enumerate() {
            // 官方语义:t 在首帧之前时间轴未生效(保持 setup),该通道不输出,不覆盖 Pose
            if let Some(value) = sample_frames(&timeline.frames, t, &mut config.last_frames[i]) {
                values.push((timeline.bone, timeline.channel, value));
            }
        }
        let mut slot_values = Vec::with_capacity(animation.slot_timelines.len());
        for (i, timeline) in animation.slot_timelines.iter().enumerate() {
            let cache = &mut config.last_frames[animation.timelines.len() + i];
            let value = sample_slot_frames(timeline, t, cache);
            slot_values.push((timeline.slot, timeline.channel, value));
        }
        let mut constraint_values = Vec::with_capacity(animation.constraint_timelines.len());
        for timeline in &animation.constraint_timelines {
            // step 语义:取 t 时刻之前(含)的最后一帧;无命中帧则不输出
            let frame = timeline.frames.iter().rev().find(|f| f.time() <= t);
            if let Some(frame) = frame {
                constraint_values.push((timeline.index, frame.clone()));
            }
        }
        // deform:帧间按曲线插值(帧级曲线,所有顶点共用),无命中帧不输出
        let mut deform_values = Vec::with_capacity(animation.deform_timelines.len());
        for timeline in &animation.deform_timelines {
            let Some(frame) = sample_deform_frames(&timeline.frames, t) else {
                continue;
            };
            deform_values.push((timeline.slot, timeline.mesh, frame));
        }
        // draw order:step 语义,无命中帧保持 setup 顺序
        let draw_order = animation
            .draw_order_timeline
            .as_ref()
            .and_then(|tl| {
                tl.frames
                    .iter()
                    .rev()
                    .find(|f| f.time <= t)
                    .map(|f| f.order.clone())
            })
            .flatten();
        SampledAnimate {
            values,
            slot_values,
            constraint_values,
            deform_values,
            draw_order,
        }
    }
}

/// deform 时间轴采样:返回 t 时刻的完整顶点数组(插值后),无命中帧返回 None
fn sample_deform_frames(frames: &[DeformFrame], t: f32) -> Option<Vec<f32>> {
    let (idx, _) = frames.iter().enumerate().rev().find(|(_, f)| f.time <= t)?;
    if idx + 1 >= frames.len() {
        return Some(frames[idx].vertices.clone());
    }
    let prev = &frames[idx];
    let next = &frames[idx + 1];
    // 帧级曲线:求插值百分比后应用到所有顶点
    let p = match &prev.curve {
        Curve::Linear => {
            let span = next.time - prev.time;
            if span <= 0.0 {
                0.0
            } else {
                (t - prev.time) / span
            }
        }
        Curve::Step => 0.0,
        Curve::Bezier(_, Some(points)) => sample_curve(points, t),
        Curve::Bezier(curve, None) => curve.eval(t, prev.time, 0.0, next.time, 1.0),
    };
    let len = prev.vertices.len().min(next.vertices.len());
    let mut out = Vec::with_capacity(len);
    for i in 0..len {
        out.push(prev.vertices[i] + (next.vertices[i] - prev.vertices[i]) * p);
    }
    Some(out)
}

/// 动画采样器实例状态
///
/// 一个实例对应一个动画的采样进度,切换动画时自动重置内部缓存
#[derive(Debug, Clone, Default)]
pub struct AnimateConfig {
    anim_idx: Option<AnimIdx>,
    /// 每个 timeline 上次命中的帧索引,用于连续时间采样加速
    last_frames: Vec<u32>,
}

impl AnimateConfig {
    pub fn new() -> Self {
        Self {
            anim_idx: None,
            last_frames: vec![],
        }
    }
}

/// 采样完成的动画数据,用于修改 Pose 等
#[derive(Debug, Clone, Default)]
pub struct SampledAnimate {
    /// 骨骼通道 delta(相对 setup pose 的修改):translate/rotate/shear 为加数、scale 为乘数,
    /// 顺序与 AnimationRT.timelines 一致,仅含 t 时已生效的通道
    pub values: Vec<(BoneIdx, BoneChannel, f32)>,
    /// slot 动画采样值(颜色 / attachment),顺序与 AnimationRT.slot_timelines 一致
    pub slot_values: Vec<(
        crate::data::runtime::slot::SlotIdx,
        SlotChannel,
        SampledSlotValue,
    )>,
    /// 约束动画采样值(step 语义:t 时刻命中的最后一帧),顺序与 AnimationRT.constraint_timelines 一致
    pub constraint_values: Vec<(
        crate::data::runtime::constraint::ConstraintIdx,
        ConstraintKeyframe,
    )>,
    /// deform 采样值:(slot, 所属网格, 完整顶点数组;加权 = 按 influence 展开的 delta,非加权 = 绝对位置)
    pub deform_values: Vec<(
        crate::data::runtime::slot::SlotIdx,
        crate::data::runtime::mesh::MeshIdx,
        Vec<f32>,
    )>,
    /// 该时刻的绘制顺序(setup slot 索引排列),None = setup 顺序
    pub draw_order: Option<Vec<i32>>,
}

/// slot 动画的采样结果
#[derive(Debug, Clone, PartialEq)]
pub enum SampledSlotValue {
    /// 颜色,RGBA 各分量 0-1;None = 时间轴尚未生效(t < 首帧),槽保持默认颜色
    Color(Option<[f32; 4]>),
    /// attachment 时间轴采样(官方:t < 首帧时保持 slot 默认 attachment)
    Attachment(SampledAttachment),
}

/// attachment 时间轴采样结果(step 语义)
#[derive(Debug, Clone, PartialEq)]
pub enum SampledAttachment {
    /// 时间轴尚未生效(t < 首帧):保持 slot 默认 attachment(皮肤默认)
    NotStarted,
    /// 已生效:设置 attachment,None 表示显式移除(隐藏该 slot)
    Set(Option<AttachmentNameIdx>),
}

impl SampledAnimate {
    /// 将采样结果应用到 Pose(`Pose + PoseApplier`)
    ///
    /// `values` 是相对 setup 的 delta:translate/rotate/shear 为加数、scale 为乘数,
    /// 叠加到 Pose 当前值(Pose 通常由 [`crate::data::runtime::skeleton::Skeleton::default_pose`]
    /// 以 setup 值初始化,叠加后即动画最终局部变换)。未命中通道的骨骼保持原值。
    ///
    /// 应用后 Pose 的世界变换缓存全局失效(全部骨骼):spine 角色动画的骨骼几乎每帧都会被采样,
    /// 所有骨骼的世界变换本就要重算,定向失效(只清受影响骨骼的子树)没有收益,反而增加复杂度
    pub fn apply_pose(&self, pose: &mut Pose) {
        if self.values.is_empty() {
            return;
        }
        for &(bone, channel, value) in &self.values {
            let data = &mut pose.bone_data[bone];
            match channel {
                BoneChannel::TranslateX => data.translate_x += value,
                BoneChannel::TranslateY => data.translate_y += value,
                BoneChannel::Rotate => data.rotation_deg += value,
                BoneChannel::ScaleX => data.scale_x *= value,
                BoneChannel::ScaleY => data.scale_y *= value,
                BoneChannel::ShearX => data.shear_x_deg += value,
                BoneChannel::ShearY => data.shear_y_deg += value,
            }
        }
        pose.dirty = true;
    }

    /// 将约束采样值应用到约束状态(覆盖显式出现的字段,None 字段保持原值)
    ///
    /// 调用时机:在 `apply_constraints` 之前,以骨架默认值初始化状态后再应用动画覆盖
    pub fn apply_constraints(&self, state: &mut crate::data::runtime::constraint::ConstraintState) {
        for (index, frame) in &self.constraint_values {
            use crate::data::runtime::constraint::ConstraintIdx;
            match (index, frame) {
                (
                    ConstraintIdx::Ik(i),
                    ConstraintKeyframe::Ik {
                        mix,
                        bend_positive,
                        compress,
                        stretch,
                        ..
                    },
                ) => {
                    let s = &mut state.ik[*i as usize];
                    if let Some(v) = mix {
                        s.mix = *v;
                    }
                    if let Some(v) = bend_positive {
                        s.bend_positive = *v;
                    }
                    if let Some(v) = compress {
                        s.compress = *v;
                    }
                    if let Some(v) = stretch {
                        s.stretch = *v;
                    }
                }
                (
                    ConstraintIdx::Transform(i),
                    ConstraintKeyframe::Transform {
                        mix_rotate,
                        mix_x,
                        mix_y,
                        mix_scale_x,
                        mix_scale_y,
                        mix_shear_y,
                        ..
                    },
                ) => {
                    let s = &mut state.transform[*i as usize];
                    if let Some(v) = mix_rotate {
                        s.mix_rotate = *v;
                    }
                    if let Some(v) = mix_x {
                        s.mix_x = *v;
                    }
                    if let Some(v) = mix_y {
                        s.mix_y = *v;
                    }
                    if let Some(v) = mix_scale_x {
                        s.mix_scale_x = *v;
                    }
                    if let Some(v) = mix_scale_y {
                        s.mix_scale_y = *v;
                    }
                    if let Some(v) = mix_shear_y {
                        s.mix_shear_y = *v;
                    }
                }
                // 索引类型与帧类型不匹配(数据构建错误,忽略)
                _ => {}
            }
        }
    }
}

/// 采样一根时间轴在 t 时刻的值
///
/// 官方语义:t 在首帧之前时间轴未生效(保持 setup),返回 None,调用方应跳过该通道。
/// frames 至少包含一帧;last 用于连续采样加速(t 单调递增时 O(1))
fn sample_frames(frames: &[Keyframe], t: f32, last: &mut u32) -> Option<f32> {
    debug_assert!(!frames.is_empty());
    if t < frames[0].time {
        return None;
    }
    if frames.len() == 1 {
        return Some(frames[0].value);
    }
    let last_time = frames.last().unwrap().time;
    let t = t.min(last_time);
    let mut idx = (*last as usize).min(frames.len() - 2);
    if t < frames[idx].time || t >= frames[idx + 1].time {
        // 缓存失效,二分查找第一个 time > t 的位置
        let pp = frames.partition_point(|f| f.time <= t);
        idx = pp.saturating_sub(1).min(frames.len() - 2);
        *last = idx as u32;
    }
    let f0 = &frames[idx];
    let f1 = &frames[idx + 1];
    let span = f1.time - f0.time;
    if span <= 0.0 {
        return Some(f1.value);
    }
    Some(f0.curve.eval(t, f0.time, f0.value, f1.time, f1.value))
}

/// 采样 slot 时间轴在 t 时刻的值
fn sample_slot_frames(timeline: &SlotTimeline, t: f32, last: &mut u32) -> SampledSlotValue {
    match timeline.channel {
        SlotChannel::Color => {
            SampledSlotValue::Color(sample_color_frames(&timeline.frames, t, last))
        }
        SlotChannel::Attachment => {
            SampledSlotValue::Attachment(sample_attachment_frames(&timeline.frames, t))
        }
    }
}

/// 颜色时间轴采样:定位帧段后 RGBA 四分量按同一曲线各自插值
///
/// spine 语义:t 在首帧之前时间轴未生效(槽保持默认颜色),t 在末帧之后取末帧值
fn sample_color_frames(frames: &[SlotKeyframe], t: f32, last: &mut u32) -> Option<[f32; 4]> {
    debug_assert!(!frames.is_empty());
    if t < frames[0].time() {
        *last = 0;
        return None;
    }
    if frames.len() == 1 {
        return Some(color_at(&frames[0]));
    }
    let last_time = frames.last().unwrap().time();
    let t = t.min(last_time);
    let mut idx = (*last as usize).min(frames.len() - 2);
    if t < frames[idx].time() || t >= frames[idx + 1].time() {
        let pp = frames.partition_point(|f| f.time() <= t);
        idx = pp.saturating_sub(1).min(frames.len() - 2);
        *last = idx as u32;
    }
    let (f0, f1) = (&frames[idx], &frames[idx + 1]);
    let (t0, c0) = (f0.time(), color_at(f0));
    let (t1, c1) = (f1.time(), color_at(f1));
    let span = t1 - t0;
    if span <= 0.0 {
        return Some(c1);
    }
    let mut out = [0.0f32; 4];
    for i in 0..4 {
        out[i] = curves_of(f0)[i].eval(t, t0, c0[i], t1, c1[i]);
    }
    Some(out)
}

/// attachment 时间轴采样:step 语义;t 在首帧之前时间轴未生效(保持 slot 默认 attachment)
fn sample_attachment_frames(frames: &[SlotKeyframe], t: f32) -> SampledAttachment {
    debug_assert!(!frames.is_empty());
    if t < frames[0].time() {
        return SampledAttachment::NotStarted;
    }
    let idx = frames.partition_point(|f| f.time() <= t);
    let SlotKeyframe::Attachment { name, .. } = &frames[idx.saturating_sub(1)] else {
        return SampledAttachment::Set(None);
    };
    SampledAttachment::Set(*name)
}

fn color_at(frame: &SlotKeyframe) -> [f32; 4] {
    let SlotKeyframe::Color { rgba, .. } = frame else {
        panic!("expected color frame");
    };
    *rgba
}

fn curves_of(frame: &SlotKeyframe) -> &[Curve; 4] {
    let SlotKeyframe::Color { curves, .. } = frame else {
        panic!("expected color frame");
    };
    curves
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::custom_index::AsIndex;

    fn simple_animation() -> AnimationRT {
        AnimationRT {
            name: "test".to_string(),
            duration: 1.0,
            slot_timelines: vec![],
            constraint_timelines: vec![],
            deform_timelines: vec![],
            draw_order_timeline: None,
            timelines: vec![Timeline {
                bone: unsafe { BoneIdx::from_index(0) },
                channel: BoneChannel::TranslateX,
                frames: vec![
                    Keyframe {
                        time: 0.0,
                        value: 0.0,
                        curve: Curve::Linear,
                    },
                    Keyframe {
                        time: 1.0,
                        value: 10.0,
                        curve: Curve::Linear,
                    },
                ],
            }],
        }
    }

    #[test]
    fn slot_color_sampling_interpolates() {
        use crate::data::runtime::slot::SlotIdx;
        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        anim.slot_timelines.push(SlotTimeline {
            slot: unsafe { SlotIdx::from_index(0) },
            channel: SlotChannel::Color,
            frames: vec![
                SlotKeyframe::Color {
                    time: 0.0,
                    rgba: [1.0, 0.0, 0.0, 1.0],
                    curves: [
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                ],
                },
                SlotKeyframe::Color {
                    time: 1.0,
                    rgba: [0.0, 1.0, 0.0, 1.0],
                    curves: [
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                ],
                },
            ],
        });
        let idx = set.insert("c", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.5);
        let SampledSlotValue::Color(Some(c)) = s.slot_values[0].2 else {
            panic!("expected color");
        };
        assert!((c[0] - 0.5).abs() < 1e-5);
        assert!((c[1] - 0.5).abs() < 1e-5);
        assert_eq!(c[2], 0.0);
        assert_eq!(c[3], 1.0);
    }

    #[test]
    fn slot_color_before_first_frame_is_none() {
        use crate::data::runtime::slot::SlotIdx;
        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        anim.slot_timelines.push(SlotTimeline {
            slot: unsafe { SlotIdx::from_index(0) },
            channel: SlotChannel::Color,
            frames: vec![SlotKeyframe::Color {
                time: 0.5,
                rgba: [1.0, 0.0, 0.0, 1.0],
                curves: [
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                ],
            }],
        });
        let idx = set.insert("c", anim);
        let mut config = AnimateConfig::new();
        // t < 首帧:时间轴未生效,保持槽默认颜色
        let s = set.sample(idx, &mut config, 0.0);
        assert_eq!(s.slot_values[0].2, SampledSlotValue::Color(None));
        // t >= 首帧:生效
        let s = set.sample(idx, &mut config, 0.5);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Color(Some([1.0, 0.0, 0.0, 1.0]))
        );
    }

    #[test]
    fn slot_color_out_of_range_clamps() {
        use crate::data::runtime::slot::SlotIdx;
        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        anim.slot_timelines.push(SlotTimeline {
            slot: unsafe { SlotIdx::from_index(0) },
            channel: SlotChannel::Color,
            frames: vec![SlotKeyframe::Color {
                time: 0.0,
                rgba: [0.2, 0.4, 0.6, 0.8],
                curves: [
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                    Curve::Linear,
                ],
            }],
        });
        let idx = set.insert("c", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 100.0);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Color(Some([0.2, 0.4, 0.6, 0.8]))
        );
    }

    #[test]
    fn slot_attachment_switching() {
        use crate::data::runtime::slot::SlotIdx;
        // 逻辑名 "open" / "closed" 的索引(解析期 intern 的等价物)
        let open = unsafe { AttachmentNameIdx::from_index(0) };
        let closed = unsafe { AttachmentNameIdx::from_index(1) };
        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        anim.slot_timelines.push(SlotTimeline {
            slot: unsafe { SlotIdx::from_index(0) },
            channel: SlotChannel::Attachment,
            frames: vec![
                SlotKeyframe::Attachment {
                    time: 0.0,
                    name: None,
                },
                SlotKeyframe::Attachment {
                    time: 0.5,
                    name: Some(open),
                },
                SlotKeyframe::Attachment {
                    time: 0.8,
                    name: Some(closed),
                },
            ],
        });
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.0);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Attachment(SampledAttachment::Set(None))
        );
        let s = set.sample(idx, &mut config, 0.5);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Attachment(SampledAttachment::Set(Some(open)))
        );
        let s = set.sample(idx, &mut config, 0.9);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Attachment(SampledAttachment::Set(Some(closed)))
        );
        let s = set.sample(idx, &mut config, 100.0);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Attachment(SampledAttachment::Set(Some(closed)))
        );
    }

    /// 官方语义:t < 首帧时 attachment 时间轴未生效(保持 slot 默认 attachment)
    #[test]
    fn slot_attachment_before_first_frame_is_not_started() {
        use crate::data::runtime::slot::SlotIdx;
        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        anim.slot_timelines.push(SlotTimeline {
            slot: unsafe { SlotIdx::from_index(0) },
            channel: SlotChannel::Attachment,
            frames: vec![SlotKeyframe::Attachment {
                time: 0.5,
                name: Some(unsafe { AttachmentNameIdx::from_index(0) }),
            }],
        });
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        // t < 首帧:时间轴未生效,保持 slot 默认 attachment
        let s = set.sample(idx, &mut config, 0.0);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Attachment(SampledAttachment::NotStarted)
        );
        // t >= 首帧:生效
        let s = set.sample(idx, &mut config, 0.5);
        assert_eq!(
            s.slot_values[0].2,
            SampledSlotValue::Attachment(SampledAttachment::Set(Some(unsafe {
                AttachmentNameIdx::from_index(0)
            })))
        );
    }

    /// 官方语义:t < 首帧时骨骼时间轴未生效(保持 setup),该通道不输出(不覆盖 Pose)
    #[test]
    fn bone_channel_before_first_frame_not_emitted() {
        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        // 首帧在 t=1.0:t<1 之前时间轴不生效
        anim.timelines[0].frames = vec![
            Keyframe {
                time: 1.0,
                value: 10.0,
                curve: Curve::Linear,
            },
            Keyframe {
                time: 2.0,
                value: 20.0,
                curve: Curve::Linear,
            },
        ];
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        // t=0.5 < 首帧:不输出(保持 setup)
        let s = set.sample(idx, &mut config, 0.5);
        assert!(s.values.is_empty());
        // t=1.0:生效,取首帧值
        let s = set.sample(idx, &mut config, 1.0);
        assert_eq!(
            s.values,
            vec![(
                unsafe { BoneIdx::from_index(0) },
                BoneChannel::TranslateX,
                10.0
            )]
        );
        // t=1.5:帧间插值
        let s = set.sample(idx, &mut config, 1.5);
        assert_eq!(s.values[0].2, 15.0);
    }

    #[test]
    fn linear_sample() {
        let mut set = AnimateSet::new();
        let idx = set.insert("a", simple_animation());
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.5);
        assert_eq!(
            s.values,
            vec![(
                unsafe { BoneIdx::from_index(0) },
                BoneChannel::TranslateX,
                5.0
            )]
        );
    }

    #[test]
    fn prebuild_curves_converts_bezier_to_sampled() {
        let mut anim = simple_animation();
        anim.timelines[0].frames[0].curve =
            Curve::Bezier(BezierCurve::new(0.3, 0.0, 0.7, 10.0), None);
        // 帧段 0.0->1.0 / 值 0->10,曲线控制点为绝对 time/value 坐标
        anim.prebuild_curves(DEFAULT_CURVE_SAMPLING);
        // 首帧曲线被预采样成点表
        assert!(matches!(
            anim.timelines[0].frames[0].curve,
            Curve::Bezier(_, Some(_))
        ));
        // 最后一帧没有下一帧,不会被求值,曲线保持原样
        assert!(matches!(
            anim.timelines[0].frames[1].curve,
            Curve::Linear
        ));
        let mut set = AnimateSet::new();
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        // 查表采样与 fallback(即时预采样)结果一致
        let curve = BezierCurve::new(0.3, 0.0, 0.7, 10.0);
        for t in [0.0, 0.1, 0.5, 0.9, 1.0] {
            let s = set.sample(idx, &mut config, t);
            let v = s.values[0].2;
            let exact = curve.eval(t, 0.0, 0.0, 1.0, 10.0);
            assert!((v - exact).abs() < 1e-5, "t={t} v={v} exact={exact}");
        }
    }

    #[test]
    fn step_curve() {
        let mut anim = simple_animation();
        anim.timelines[0].frames[0].curve = Curve::Step;
        let mut set = AnimateSet::new();
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.99);
        assert_eq!(s.values[0].2, 0.0);
    }

    #[test]
    fn clamp_out_of_range() {
        let mut set = AnimateSet::new();
        let idx = set.insert("a", simple_animation());
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 100.0);
        assert_eq!(s.values[0].2, 10.0);
    }

    #[test]
    fn single_frame() {
        let mut anim = simple_animation();
        anim.timelines[0].frames = vec![Keyframe {
            time: 0.0,
            value: 7.0,
            curve: Curve::Linear,
        }];
        anim.duration = 0.0;
        let mut set = AnimateSet::new();
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.0);
        assert_eq!(s.values[0].2, 7.0);
    }

    #[test]
    fn config_switch_animation() {
        let mut set = AnimateSet::new();
        let idx_a = set.insert("a", simple_animation());
        let idx_b = {
            let mut anim = simple_animation();
            anim.timelines[0].frames[1].value = 20.0;
            set.insert("b", anim)
        };
        let mut config = AnimateConfig::new();
        let s = set.sample(idx_a, &mut config, 0.5);
        assert_eq!(s.values[0].2, 5.0);
        let s = set.sample(idx_b, &mut config, 0.5);
        assert_eq!(s.values[0].2, 10.0);
        let s = set.sample(idx_a, &mut config, 0.5);
        assert_eq!(s.values[0].2, 5.0);
    }

    #[test]
    fn bezier_spine_coordinates() {
        // 自造曲线:帧0 (0, 0) -> 帧1 (1, 10),对称 ease-in-out(控制点 y 落在端点连线上)
        let curve = BezierCurve::new(0.3, 0.0, 0.7, 10.0);
        // 端点精确
        assert!((curve.eval(0.0, 0.0, 0.0, 1.0, 10.0) - 0.0).abs() < 1e-4);
        assert!((curve.eval(1.0, 0.0, 0.0, 1.0, 10.0) - 10.0).abs() < 1e-4);
        // 中间时刻单调插值(值从 0 到 10)
        let mid = curve.eval(0.5, 0.0, 0.0, 1.0, 10.0);
        assert!(mid > 0.0 && mid < 10.0, "mid={mid}");
        // 对称曲线中点应在值域中点附近
        assert!((mid - 5.0).abs() < 0.1, "mid={mid}");
    }

    #[test]
    fn bezier_monotonic_in_frame_space() {
        // 自造曲线:帧0 (0, 2) -> 帧1 (1, 0),先平后降(控制点保持起始值再回落)
        let curve = BezierCurve::new(0.3, 2.0, 0.7, 0.5);
        let mid = curve.eval(0.5, 0.0, 2.0, 1.0, 0.0);
        assert!(mid > 0.0 && mid < 2.0, "mid={mid}");
        let near_start = curve.eval(0.2, 0.0, 2.0, 1.0, 0.0);
        assert!((near_start - 2.0).abs() < 0.5, "near_start={near_start}");
    }

    #[test]
    fn apply_pose_adds_delta() {
        use crate::data::runtime::skeleton::BoneDataStatic;

        let mut skel = crate::data::runtime::skeleton::Skeleton::new();
        skel.insert_bone("root", BoneDataStatic::default()).unwrap();
        let mut pose = skel.default_pose();
        // 手动修改 Pose 后再应用动画 delta:translate 为加数叠加(100 + 0 = 100),非覆盖
        pose.bone_data[unsafe { BoneIdx::from_index(0) }].translate_x = 100.0;

        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        anim.timelines.push(Timeline {
            bone: unsafe { BoneIdx::from_index(0) },
            channel: BoneChannel::Rotate,
            frames: vec![Keyframe {
                time: 0.0,
                value: 45.0,
                curve: Curve::Linear,
            }],
        });
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.0);
        s.apply_pose(&mut pose);
        assert!(pose.dirty);
        // TranslateX delta = 0(simple_animation 首帧值 0):叠加后保持手动值 100
        assert_eq!(
            pose.bone_data[unsafe { BoneIdx::from_index(0) }].translate_x,
            100.0
        );
        // Rotate delta = 45:setup 0 + 45 = 45
        assert_eq!(
            pose.bone_data[unsafe { BoneIdx::from_index(0) }].rotation_deg,
            45.0
        );
        // 应用后可以直接求世界变换(缓存已被清空并惰性重建)
        let _ = pose.get_world_affine(&skel, unsafe { BoneIdx::from_index(0) });
    }

    #[test]
    fn apply_pose_scale_multiplies_delta() {
        use crate::data::runtime::skeleton::BoneDataStatic;

        let mut skel = crate::data::runtime::skeleton::Skeleton::new();
        skel.insert_bone("root", BoneDataStatic::default()).unwrap();
        let mut pose = skel.default_pose();
        pose.bone_data[unsafe { BoneIdx::from_index(0) }].scale_x = 2.0;
        pose.bone_data[unsafe { BoneIdx::from_index(0) }].scale_y = 3.0;

        let mut set = AnimateSet::new();
        let mut anim = simple_animation();
        anim.timelines.push(Timeline {
            bone: unsafe { BoneIdx::from_index(0) },
            channel: BoneChannel::ScaleY,
            frames: vec![Keyframe {
                time: 0.0,
                value: 1.5,
                curve: Curve::Linear,
            }],
        });
        let idx = set.insert("a", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.0);
        s.apply_pose(&mut pose);
        // ScaleX:未被动画命中,保持手动值 2.0
        assert_eq!(
            pose.bone_data[unsafe { BoneIdx::from_index(0) }].scale_x,
            2.0
        );
        // ScaleY:delta 为乘数,setup 3 * 1.5 = 4.5
        assert_eq!(
            pose.bone_data[unsafe { BoneIdx::from_index(0) }].scale_y,
            4.5
        );
    }
}