aada 0.1.0

纯 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
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
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
//! spine 导入层:JSON / atlas 解析与引擎构建入口。
//!
//! 引擎入口 [`build_rt`]:spine JSON + atlas 文本 -> [`RT`] 运行时数据 + 图集页列表,
//! 内部完成解析、索引化、网格去重、皮肤/附件组装、全部动画导入。
//! 单独可用的子步骤:`import_spine`(骨架/slots/皮肤/网格)、`parse_atlas`(4.x bounds/offsets 格式)、
//! `apply_atlas`(网格 UV 图集坐标转换)。

use std::collections::{HashMap, HashSet};

use serde_json::Value;

use crate::{
    data::{
        runtime::{
            animate::{AnimateSet, DEFAULT_CURVE_SAMPLING},
            constraint::ConstraintIdx,
            mesh::{MeshMetadata, MeshSet},
            rt::RT,
            skeleton::{InheritMode, Skeleton},
            skin::{AttachmentData, AttachmentNames, AttachmentSet, Skin, SkinSet},
            slot::SlotSet,
        },
        store::{
            animate::parse_spine_animation, mesh::MeshLocalDataStore, skeleton::BoneDataStore,
            slot::SlotDataStore,
        },
    },
    error::Error,
};

/// 皮肤中的一个 attachment 映射:逻辑附件名 -> 实际 attachment(含默认颜色)
#[derive(Debug, Clone)]
pub struct SkinAttachment {
    pub skin: String,
    pub slot: String,
    pub logical: String,
    pub actual: String,
    /// attachment 默认颜色(RGBA 0-1,spine 的 color 字段,缺省白色)
    pub color: [f32; 4],
}

/// 从 spine 导出文件解析出的全部数据(骨骼/slots/皮肤与网格)
///
/// 裁剪附件(clipping)与普通网格统一存放在 meshes 中(通过 clip_end_slot 标记区分)
pub struct SpineImport {
    pub bones: Vec<BoneDataStore>,
    pub slots: Vec<SlotDataStore>,
    /// 每个 attachment 转换出的网格(region 已转为矩形网格;clip 多边形也在其中,clip_end_slot 非空)
    pub meshes: Vec<MeshLocalDataStore>,
    /// 皮肤 attachment 映射(含默认颜色)
    pub skin_attachments: Vec<SkinAttachment>,
}

/// 解析 spine 导出 JSON 的骨架/slots/皮肤部分(动画单独使用 parse_spine_animation)
pub fn import_spine(root: &Value) -> Result<SpineImport, Error> {
    let bones = parse_bones(root)?;
    let slots = parse_slots(root)?;
    let mut meshes = Vec::new();
    let mut skin_attachments = Vec::new();

    if let Some(skins) = root.get("skins").and_then(|v| v.as_array()) {
        for skin in skins {
            let skin_name = skin
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| Error::InvalidData("skin missing name".to_string()))?;
            let attachments = skin.get("attachments").and_then(|v| v.as_object());
            if let Some(attachments) = attachments {
                for (slot_name, slot_attachments) in attachments {
                    let slot_attachments = slot_attachments.as_object().ok_or_else(|| {
                        Error::InvalidData(format!(
                            "skin '{skin_name}' slot '{slot_name}' attachments must be an object"
                        ))
                    })?;
                    for (logical_name, att_value) in slot_attachments {
                        let att_obj = match att_value.as_object() {
                            Some(o) => o,
                            None => continue, // 空 attachment 表示无附件
                        };
                        let att_color = attachment_color(att_obj)?;
                        let att_type = att_obj
                            .get("type")
                            .and_then(|v| v.as_str())
                            .unwrap_or("region");
                        match att_type {
                            "region" => {
                                let mesh = region_to_mesh(slot_name, logical_name, att_value)?;
                                meshes.push(mesh);
                                skin_attachments.push(SkinAttachment {
                                    skin: skin_name.to_string(),
                                    slot: slot_name.to_string(),
                                    logical: logical_name.clone(),
                                    actual: logical_name.clone(),
                                    color: att_color,
                                });
                            }
                            "mesh" => {
                                let actual = att_obj
                                    .get("name")
                                    .and_then(|v| v.as_str())
                                    .unwrap_or(logical_name);
                                let mesh = convert_spine_mesh_to_local(
                                    skin_name, slot_name, actual, att_value, &bones,
                                )?;
                                meshes.push(mesh);
                                skin_attachments.push(SkinAttachment {
                                    skin: skin_name.to_string(),
                                    slot: slot_name.to_string(),
                                    logical: logical_name.clone(),
                                    actual: actual.to_string(),
                                    color: att_color,
                                });
                            }
                            "clipping" => {
                                let actual = att_obj
                                    .get("name")
                                    .and_then(|v| v.as_str())
                                    .unwrap_or(logical_name);
                                let clip = convert_spine_clip_to_local(
                                    skin_name, slot_name, actual, att_value, &bones,
                                )?;
                                meshes.push(clip);
                                skin_attachments.push(SkinAttachment {
                                    skin: skin_name.to_string(),
                                    slot: slot_name.to_string(),
                                    logical: logical_name.clone(),
                                    actual: actual.to_string(),
                                    color: att_color,
                                });
                            }
                            // linkedmesh 等暂不支持,跳过
                            _ => {}
                        }
                    }
                }
            }
        }
    }

    Ok(SpineImport {
        bones,
        slots,
        meshes,
        skin_attachments,
    })
}

/// 从 spine 导出文件内容构建完整运行时数据(引擎构建入口)
///
/// 输入:spine JSON 文本、atlas 文本
/// 输出:(RT, atlas 页列表)。RT 包含全部动画,可按名称查询;
/// atlas 页列表供渲染层加载纹理(页名 = 纹理文件名)
///
/// 内部完成:解析 -> 骨骼/slots 索引化 -> 网格按 (slot, attachment 实际名) 去重 ->
/// 皮肤/attachment 组装 -> 全部动画导入(贝塞尔曲线在构建期按默认方式预采样)
pub fn build_rt(json: &str, atlas_text: &str) -> Result<(RT, Vec<AtlasPage>), Error> {
    let root: Value = serde_json::from_str(json)
        .map_err(|e| Error::InvalidData(format!("failed to parse spine json: {e}")))?;
    let mut import = import_spine(&root)?;
    let atlas = parse_atlas(atlas_text)?;
    apply_atlas(&mut import.meshes, &atlas)?;
    let skeleton = Skeleton::from_bone_data_list(&import.bones)?;

    // slots
    let mut slot_set = SlotSet::new();
    for s in &import.slots {
        let data = s.clone().to_rt(&skeleton)?;
        slot_set.insert(data.name.clone(), data);
    }
    // 附件逻辑名 intern 表:解析期把 (slot, 逻辑名) 映射为类型化索引,运行时零字符串查找
    let att_names = std::cell::RefCell::new(AttachmentNames::new(slot_set.data.len()));
    // 回填 slot 默认 attachment 的逻辑名索引
    for i in 0..slot_set.data.len() {
        let slot_idx = unsafe { crate::custom_index::AsIndex::from_index(i) };
        let default = slot_set.data[slot_idx].default_attachment.clone();
        slot_set.data[slot_idx].default_attachment_idx =
            default.as_deref().map(|n| att_names.borrow_mut().intern(slot_idx, n));
    }

    // meshes + attachments + skins
    // 网格按 (slot, attachment 实际名) 去重:同一 attachment 在不同皮肤下共享一个网格条目,
    // 这样 mesh_idx 唯一对应一个 attachment,渲染层可用它识别网格是否切换
    // (裁剪附件也在网格集合中,通过 clip_end_slot 标记区分)
    let mut mesh_set = MeshSet::new();
    let mut attachment_set = AttachmentSet::new();
    let mut skin_set = SkinSet::new();
    let mut by_skin: HashMap<&str, Vec<&SkinAttachment>> = HashMap::new();
    for entry in &import.skin_attachments {
        by_skin.entry(entry.skin.as_str()).or_default().push(entry);
    }
    for (skin_name, entries) in &by_skin {
        let mut skin = Skin::new();
        for entry in entries {
            // AttachmentData 按 (皮肤, slot, 实际名) 区分:spine 中同一附件名可在不同 slot 存在
            // 且内容不同(如 Sleeve_L_1_Front 槽与 Grab 槽的附件同名不同网格)
            let slot_name = &entry.slot;
            let actual = &entry.actual;
            let att_name = format!("{skin_name}_{slot_name}_{actual}");
            let att_idx = if let Some(idx) = attachment_set.get_index(&att_name) {
                idx
            } else {
                let mesh_name = format!("{slot_name}_{actual}");
                if mesh_set.get_index(&mesh_name).is_none() {
                    // 找到对应的网格数据并转换(clip 多边形同样在这里转换)
                    let mesh_store = import
                        .meshes
                        .iter()
                        .find(|m| {
                            m.meta.name.as_deref() == Some(actual.as_str())
                                && m.meta.slot.as_deref() == Some(slot_name.as_str())
                        })
                        .cloned();
                    if let Some(mesh_store) = mesh_store {
                        let rt = mesh_store.to_rt(&skeleton, &slot_set)?;
                        mesh_set.insert_mesh(mesh_name.clone(), rt);
                    }
                }
                let Some(mesh_idx) = mesh_set.get_index(&mesh_name) else {
                    continue;
                };
                attachment_set.insert(
                    att_name.clone(),
                    AttachmentData {
                        name: att_name,
                        mesh: Some(mesh_idx),
                        color: entry.color,
                    },
                )
            };
            let Some(slot_idx) = slot_set.get_index(slot_name) else {
                continue;
            };
            let name_idx = att_names.borrow_mut().intern(slot_idx, &entry.logical);
            skin.insert(slot_idx, name_idx, att_idx);
        }
        skin_set.insert((*skin_name).to_string(), skin);
    }
    // 约束:骨架级 ik / transform 定义
    let constraint_store: crate::data::store::constraint::ConstraintDataStore =
        serde_json::from_value({
            let mut v = serde_json::json!({});
            if let Some(ik) = root.get("ik") {
                v["ik"] = ik.clone();
            }
            if let Some(transform) = root.get("transform") {
                v["transform"] = transform.clone();
            }
            v
        })
        .map_err(|e| Error::InvalidData(format!("failed to parse constraints: {e}")))?;
    // 约束名 -> 运行时索引(动画约束时间轴按名称引用)
    let mut constraint_indices: HashMap<String, ConstraintIdx> = HashMap::new();
    for (i, c) in constraint_store.ik.iter().enumerate() {
        constraint_indices.insert(c.name.clone(), ConstraintIdx::Ik(i as u32));
    }
    for (i, c) in constraint_store.transform.iter().enumerate() {
        constraint_indices.insert(c.name.clone(), ConstraintIdx::Transform(i as u32));
    }
    let constraint_set = constraint_store.to_rt(&skeleton)?;

    // 动画:全部导入
    let mut anim_set = AnimateSet::new();
    if let Some(animations) = root.get("animations").and_then(|v| v.as_object()) {
        // deform 展开解析器:按 (皮肤, slot, attachment 逻辑名) 查网格信息
        let deform_resolver = |skin_name: &str,
                               slot_name: &str,
                               att_name: &str|
         -> Option<crate::data::store::animate::DeformMeshInfo> {
            let skin_idx = skin_set.get_index(skin_name)?;
            let slot_idx = slot_set.get_index(slot_name)?;
            let name_idx = att_names.borrow_mut().intern(slot_idx, att_name);
            let att = skin_set.data[skin_idx].get(slot_idx, name_idx)?;
            let mesh_idx = attachment_set.get_mesh(att)?;
            let m = &mesh_set.data_map[mesh_idx];
            Some(crate::data::store::animate::DeformMeshInfo {
                mesh_idx,
                vertex_count: m.vertex_count,
                weighted: m.bones.is_some(),
                setup: m.vertices_locals.clone(),
                // 官方 SkeletonJson:加权网格 deform 按 influence 展开(每 influence 2 个 float)
                deform_len: 2 * m
                    .influence_counts
                    .iter()
                    .map(|&c| c as usize)
                    .sum::<usize>(),
            })
        };
        for (name, anim) in animations {
            let store = parse_spine_animation(name, anim, &import.bones)?;
            let mut anim_rt =
                store.to_rt(&skeleton, &slot_set, &constraint_indices, &att_names, &deform_resolver)?;
            // 构建期预采样:贝塞尔段生成点表,运行期查表(自适应,误差 ≤ 0.01)
            anim_rt.prebuild_curves(DEFAULT_CURVE_SAMPLING);
            anim_set.insert(anim_rt.name.clone(), anim_rt);
        }
    }

    let rt = RT {
        skins: skin_set,
        meshs: mesh_set,
        skeleton,
        slots: slot_set,
        attachments: attachment_set,
        animates: anim_set,
        constraints: constraint_set,
    };
    Ok((rt, atlas.pages))
}

// ==================== spine 纹理图集(.atlas)解析与 UV 转换 ====================

/// 图集页面(对应一张纹理图)
#[derive(Debug, Clone, PartialEq)]
pub struct AtlasPage {
    pub name: String,
    pub width: f32,
    pub height: f32,
    /// 纹理是否预乘 alpha(atlas 的 pma 字段,渲染时决定混合模式)
    pub pma: bool,
}

/// 图集中的一个 region(对应一个 attachment 的纹理区域)
///
/// 字段语义与 spine-runtimes 4.2 的 TextureAtlasRegion 一致:
/// - (x, y, width, height) 是裁剪后的实际图集矩形(bounds)
/// - (offset_x, offset_y, original_width, original_height) 是相对原始矩形的偏移与原始尺寸(offsets)
/// - degrees 为 region 在页内的旋转角(0/90/180/270)
#[derive(Debug, Clone, PartialEq)]
pub struct AtlasRegion {
    pub page: usize,
    pub name: String,
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub offset_x: f32,
    pub offset_y: f32,
    pub original_width: f32,
    pub original_height: f32,
    pub degrees: u16,
}

#[derive(Debug, Clone, Default)]
pub struct Atlas {
    pub pages: Vec<AtlasPage>,
    pub regions: Vec<AtlasRegion>,
}

/// 解析 spine 导出的 .atlas 文本(spine 4.x 格式,bounds/offsets 字段)
pub fn parse_atlas(text: &str) -> Result<Atlas, Error> {
    let mut atlas = Atlas::default();
    let mut lines = text.lines().map(|l| l.trim_end());
    let mut page: Option<usize> = None;
    let mut region: Option<AtlasRegion> = None;

    let mut next = || lines.next();
    // 跳过文件头部的空行
    let mut line = loop {
        match next() {
            Some(l) if l.trim().is_empty() => continue,
            other => break other,
        }
    };

    while let Some(l) = line {
        let l = l.trim();
        if l.is_empty() {
            // 空行:结束当前 region,回到页面/region 解析
            region = None;
            page = None;
            line = next();
            continue;
        }
        if page.is_none() {
            // 页面块:第一个非空行是页名
            let name = l.to_string();
            let mut page_data = AtlasPage {
                name,
                width: 0.0,
                height: 0.0,
                pma: false,
            };
            loop {
                line = next();
                match line {
                    Some(field) if field.contains(':') => {
                        let (key, value) = split_field(field)?;
                        match key {
                            "size" => {
                                let (w, h) = split_pair(value)?;
                                page_data.width = w;
                                page_data.height = h;
                            }
                            "pma" => page_data.pma = value == "true",
                            _ => {} // filter/repeat 等忽略
                        }
                    }
                    _ => break,
                }
            }
            atlas.pages.push(page_data);
            page = Some(atlas.pages.len() - 1);
            // 下一行是 region 名
            continue;
        }
        if region.is_none() {
            let mut r = AtlasRegion {
                page: page.unwrap(),
                name: l.to_string(),
                x: 0.0,
                y: 0.0,
                width: 0.0,
                height: 0.0,
                offset_x: 0.0,
                offset_y: 0.0,
                original_width: 0.0,
                original_height: 0.0,
                degrees: 0,
            };
            loop {
                line = next();
                match line {
                    Some(field) if field.contains(':') => {
                        let (key, value) = split_field(field)?;
                        match key {
                            "bounds" => {
                                let (x, y, w, h) = split_quad(value)?;
                                r.x = x;
                                r.y = y;
                                r.width = w;
                                r.height = h;
                            }
                            "offsets" => {
                                let (ox, oy, ow, oh) = split_quad(value)?;
                                r.offset_x = ox;
                                r.offset_y = oy;
                                r.original_width = ow;
                                r.original_height = oh;
                            }
                            "rotate" => {
                                r.degrees = if value == "true" {
                                    90
                                } else if value == "false" {
                                    0
                                } else {
                                    value.parse::<u16>().unwrap_or(0)
                                };
                            }
                            _ => {} // xy/size/index 等忽略(新格式用 bounds/offsets)
                        }
                    }
                    _ => break,
                }
            }
            if r.original_width == 0.0 && r.original_height == 0.0 {
                r.original_width = r.width;
                r.original_height = r.height;
            }
            atlas.regions.push(r);
            continue;
        }
        line = next();
    }
    Ok(atlas)
}

fn split_field(line: &str) -> Result<(&str, &str), Error> {
    let colon = line
        .find(':')
        .ok_or_else(|| Error::InvalidData(format!("atlas field missing ':' in line: {line}")))?;
    Ok((line[..colon].trim(), line[colon + 1..].trim()))
}

fn split_pair(value: &str) -> Result<(f32, f32), Error> {
    let mut parts = value.split(',');
    let a = parts
        .next()
        .and_then(|s| s.trim().parse::<f32>().ok())
        .ok_or_else(|| Error::InvalidData(format!("atlas expected pair, got: {value}")))?;
    let b = parts
        .next()
        .and_then(|s| s.trim().parse::<f32>().ok())
        .ok_or_else(|| Error::InvalidData(format!("atlas expected pair, got: {value}")))?;
    Ok((a, b))
}

fn split_quad(value: &str) -> Result<(f32, f32, f32, f32), Error> {
    let mut parts = value.split(',');
    let a = parts
        .next()
        .and_then(|s| s.trim().parse::<f32>().ok())
        .ok_or_else(|| Error::InvalidData(format!("atlas expected quad, got: {value}")))?;
    let b = parts
        .next()
        .and_then(|s| s.trim().parse::<f32>().ok())
        .ok_or_else(|| Error::InvalidData(format!("atlas expected quad, got: {value}")))?;
    let c = parts
        .next()
        .and_then(|s| s.trim().parse::<f32>().ok())
        .ok_or_else(|| Error::InvalidData(format!("atlas expected quad, got: {value}")))?;
    let d = parts
        .next()
        .and_then(|s| s.trim().parse::<f32>().ok())
        .ok_or_else(|| Error::InvalidData(format!("atlas expected quad, got: {value}")))?;
    Ok((a, b, c, d))
}

/// 把 region 局部 UV(spine JSON mesh 的 uvs 字段)转换为图集坐标
///
/// 移植 spine-runtimes 4.2 MeshAttachment::updateRegion 的四个旋转分支:
/// 最终 UV = region 图集位置 + 局部 UV × region 尺寸(含裁剪偏移与旋转处理)
pub fn region_uvs_to_atlas(region: &AtlasRegion, page: &AtlasPage, local_uvs: &[f32]) -> Vec<f32> {
    let page_w = page.width;
    let page_h = page.height;
    let out: Vec<f32> = local_uvs
        .chunks_exact(2)
        .flat_map(|uv| {
            let (u, v) = match region.degrees {
                90 => {
                    let u = region.x / page_w
                        - (region.original_height - region.offset_y - region.height) / page_w;
                    let v = region.y / page_h
                        - (region.original_width - region.offset_x - region.width) / page_h;
                    let w = region.original_height / page_w;
                    let h = region.original_width / page_h;
                    (u + uv[1] * w, v + (1.0 - uv[0]) * h)
                }
                180 => {
                    let u = region.x / page_w
                        - (region.original_width - region.offset_x - region.width) / page_w;
                    let v = region.y / page_h - region.offset_y / page_h;
                    let w = region.original_width / page_w;
                    let h = region.original_height / page_h;
                    (u + (1.0 - uv[0]) * w, v + (1.0 - uv[1]) * h)
                }
                270 => {
                    let u = region.x / page_w - region.offset_y / page_w;
                    let v = region.y / page_h - region.offset_x / page_h;
                    let w = region.original_height / page_w;
                    let h = region.original_width / page_h;
                    (u + (1.0 - uv[1]) * w, v + uv[0] * h)
                }
                _ => {
                    let u = region.x / page_w - region.offset_x / page_w;
                    let v = region.y / page_h
                        - (region.original_height - region.offset_y - region.height) / page_h;
                    let w = region.original_width / page_w;
                    let h = region.original_height / page_h;
                    (u + uv[0] * w, v + uv[1] * h)
                }
            };
            [u, v]
        })
        .collect();
    out
}

/// 把导入网格的局部 UV 转换为图集坐标,并更新 texture_name 为图集页名
///
/// region 按 mesh 的纹理键(path/attachment 名)查找;找不到对应 region 的网格保持原样
pub fn apply_atlas(meshes: &mut [MeshLocalDataStore], atlas: &Atlas) -> Result<(), Error> {
    for mesh in meshes {
        let Some(uvs) = mesh.uvs.as_mut() else {
            continue;
        };
        let Some(region) = atlas.regions.iter().find(|r| r.name == mesh.texture_name) else {
            continue;
        };
        let page = atlas
            .pages
            .get(region.page)
            .ok_or_else(|| Error::InvalidData("atlas region page out of range".to_string()))?;
        *uvs = region_uvs_to_atlas(region, page, uvs);
        mesh.texture_name = page.name.clone();
    }
    Ok(())
}

/// 生成调试图集纹理像素(RGBA8,单个页面)
///
/// 每个 region 填一个确定性随机色块并画白色边框,深灰背景。
/// 用于没有原始纹理时验证 UV/蒙皮是否正确:每个网格应采样到其 region 的色块。
/// 只输出页面像素数据,纹理的创建/上传/材质由调用方决定
pub fn build_debug_atlas_pixels(
    atlas: &Atlas,
    page_index: usize,
    seed: u64,
) -> Result<Vec<u8>, Error> {
    let page = atlas
        .pages
        .get(page_index)
        .ok_or_else(|| Error::InvalidData(format!("atlas page index {page_index} out of range")))?;
    let w = page.width as usize;
    let h = page.height as usize;
    if w == 0 || h == 0 || w > 16384 || h > 16384 {
        return Err(Error::InvalidData(format!(
            "atlas page size {w}x{h} out of supported range"
        )));
    }
    // 深灰背景
    let mut pixels = vec![30u8, 30, 30, 255];
    pixels = pixels.repeat(w * h);
    // 确定性伪随机(固定 seed 生成结果一致)
    let mut state = seed;
    let mut rand = move || {
        state = state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (state >> 33) as u8
    };
    for r in &atlas.regions {
        if r.page != page_index {
            continue;
        }
        let x0 = r.x.max(0.0) as usize;
        let y0 = r.y.max(0.0) as usize;
        let x1 = ((r.x + r.width).min(page.width)) as usize;
        let y1 = ((r.y + r.height).min(page.height)) as usize;
        let cr = 80 + rand() % 176;
        let cg = 80 + rand() % 176;
        let cb = 80 + rand() % 176;
        for y in y0..y1 {
            for x in x0..x1 {
                let i = (y * w + x) * 4;
                let border = x == x0 || y == y0 || x + 1 == x1 || y + 1 == y1;
                if border {
                    pixels[i] = 255;
                    pixels[i + 1] = 255;
                    pixels[i + 2] = 255;
                } else {
                    pixels[i] = cr;
                    pixels[i + 1] = cg;
                    pixels[i + 2] = cb;
                }
            }
        }
    }
    Ok(pixels)
}

fn parse_bones(root: &Value) -> Result<Vec<BoneDataStore>, Error> {
    let bones_array = root
        .get("bones")
        .and_then(|v| v.as_array())
        .ok_or_else(|| Error::InvalidData("Spine JSON must contain 'bones' array".to_string()))?;
    bones_array.iter().map(spine_bone_to_bone_data).collect()
}

fn spine_bone_to_bone_data(spine_bone: &Value) -> Result<BoneDataStore, Error> {
    let obj = spine_bone
        .as_object()
        .ok_or_else(|| Error::InvalidData("bone must be an object".to_string()))?;
    Ok(BoneDataStore {
        name: obj
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::InvalidData("bone missing name".to_string()))?
            .to_string(),
        translate_x: obj.get("x").and_then(|v| v.as_f64()).map(|v| v as f32),
        translate_y: obj.get("y").and_then(|v| v.as_f64()).map(|v| v as f32),
        rotation_deg: obj
            .get("rotation")
            .and_then(|v| v.as_f64())
            .map(|v| v as f32),
        scale_x: obj.get("scaleX").and_then(|v| v.as_f64()).map(|v| v as f32),
        scale_y: obj.get("scaleY").and_then(|v| v.as_f64()).map(|v| v as f32),
        shear_x_deg: obj.get("shearX").and_then(|v| v.as_f64()).map(|v| v as f32),
        shear_y_deg: obj.get("shearY").and_then(|v| v.as_f64()).map(|v| v as f32),
        length: obj.get("length").and_then(|v| v.as_f64()).map(|v| v as f32),
        inherit_mode: match obj
            .get("transform")
            .or_else(|| obj.get("inherit"))
            .and_then(|v| v.as_str())
        {
            Some("normal") => Some(InheritMode::Normal),
            Some("onlyTranslation") => Some(InheritMode::OnlyTranslation),
            Some("noRotationOrReflection") => Some(InheritMode::NoRotationOrReflection),
            Some("noScale") => Some(InheritMode::NoScale),
            Some("noScaleOrReflection") => Some(InheritMode::NoScaleOrReflection),
            Some(other) => {
                return Err(Error::InvalidData(format!(
                    "unknown transform mode: {other}"
                )));
            }
            None => None,
        },
        default_active: obj.get("skin").and_then(|v| v.as_bool()).map(|b| !b),
        parent: obj
            .get("parent")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string()),
        debug_color: obj
            .get("color")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string()),
        shear_mode: None,
    })
}

fn parse_slots(root: &Value) -> Result<Vec<SlotDataStore>, Error> {
    let mut slots = Vec::new();
    if let Some(arr) = root.get("slots").and_then(|v| v.as_array()) {
        for slot in arr {
            let obj = slot
                .as_object()
                .ok_or_else(|| Error::InvalidData("slot must be an object".to_string()))?;
            let name = obj
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| Error::InvalidData("slot missing name".to_string()))?
                .to_string();
            let bone = obj
                .get("bone")
                .and_then(|v| v.as_str())
                .ok_or_else(|| Error::InvalidData(format!("slot '{name}' missing bone")))?
                .to_string();
            let default_attachment = obj
                .get("attachment")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());
            let color = slot_color(obj)?;
            slots.push(SlotDataStore {
                name,
                bone,
                default_attachment,
                color,
            });
        }
    }
    Ok(slots)
}

/// 解析 slot 的 color 字段(缺省白色)
fn slot_color(obj: &serde_json::Map<String, serde_json::Value>) -> Result<[f32; 4], Error> {
    match obj.get("color").and_then(|v| v.as_str()) {
        Some(s) => hex_color_to_4f32(s),
        None => Ok([1.0, 1.0, 1.0, 1.0]),
    }
}

/// 解析 attachment 的 color 字段(缺省白色)
fn attachment_color(obj: &serde_json::Map<String, serde_json::Value>) -> Result<[f32; 4], Error> {
    slot_color(obj)
}

/// 解析 "rrggbbaa" 颜色字符串(可带 # 前缀)为 RGBA 各分量 0-1
fn hex_color_to_4f32(s: &str) -> Result<[f32; 4], Error> {
    let s = s.trim_start_matches('#');
    if s.len() != 8 {
        return Err(Error::InvalidData(format!(
            "color must be 8 hex digits, got '{s}'"
        )));
    }
    let mut out = [0.0f32; 4];
    for (i, c) in out.iter_mut().enumerate() {
        let byte = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)
            .map_err(|_| Error::InvalidData(format!("invalid hex color '{s}'")))?;
        *c = byte as f32 / 255.0;
    }
    Ok(out)
}

/// region attachment 转矩形网格(4 顶点,绑定到 slot 的主骨骼)
fn region_to_mesh(
    slot_name: &str,
    attachment_name: &str,
    region: &Value,
) -> Result<MeshLocalDataStore, Error> {
    let obj = region
        .as_object()
        .ok_or_else(|| Error::InvalidData("region attachment must be an object".to_string()))?;
    let x = obj.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
    let y = obj.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
    let scale_x = obj.get("scaleX").and_then(|v| v.as_f64()).unwrap_or(1.0) as f32;
    let scale_y = obj.get("scaleY").and_then(|v| v.as_f64()).unwrap_or(1.0) as f32;
    let rotation = obj.get("rotation").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
    let width =
        obj.get("width").and_then(|v| v.as_f64()).ok_or_else(|| {
            Error::InvalidData(format!("region '{attachment_name}' missing width"))
        })? as f32;
    let height =
        obj.get("height").and_then(|v| v.as_f64()).ok_or_else(|| {
            Error::InvalidData(format!("region '{attachment_name}' missing height"))
        })? as f32;

    let hw = width * 0.5 * scale_x;
    let hh = height * 0.5 * scale_y;
    let (sin, cos) = rotation.to_radians().sin_cos();
    let corners = [(-hw, -hh), (hw, -hh), (hw, hh), (-hw, hh)];
    let vertices_locals: Vec<f32> = corners
        .iter()
        .flat_map(|&(cx, cy)| {
            // 旋转后平移到 (x, y)
            let rx = cx * cos - cy * sin + x;
            let ry = cx * sin + cy * cos + y;
            [rx, ry]
        })
        .collect();

    Ok(MeshLocalDataStore {
        meta: MeshMetadata {
            name: Some(attachment_name.to_string()),
            slot: Some(slot_name.to_string()),
            skin: None,
        },
        texture_name: obj
            .get("path")
            .and_then(|v| v.as_str())
            .unwrap_or(attachment_name)
            .to_string(),
        uvs: Some(vec![0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]),
        vertex_count: 4,
        triangles: vec![0, 1, 2, 0, 2, 3],
        bones: None,
        influence_counts: None,
        vertices_locals,
        influence_bone_indices: None,
        influence_weights: None,
        clip_end_slot: None,
    })
}

/// 解析 spine 加权顶点数据
/// 返回:(位置坐标, 每顶点影响骨骼数, 权重, 骨骼索引)
type WeightedVertices = (Vec<(f32, f32)>, Vec<u8>, Vec<f32>, Vec<usize>);
fn parse_spine_weighted_vertices(vertices: &[f32]) -> WeightedVertices {
    let mut positions = Vec::new();
    let mut influence_counts = Vec::new();
    let mut influence_weights = Vec::new();
    let mut influence_bone_indices = Vec::new();

    let mut i = 0;
    while i < vertices.len() {
        let n = vertices[i] as u8;
        i += 1;
        influence_counts.push(n);
        for _ in 0..n {
            let bone_idx = vertices[i] as usize;
            let x = vertices[i + 1];
            let y = vertices[i + 2];
            let weight = vertices[i + 3];
            influence_bone_indices.push(bone_idx);
            positions.push((x, y));
            influence_weights.push(weight);
            i += 4;
        }
    }
    (
        positions,
        influence_counts,
        influence_weights,
        influence_bone_indices,
    )
}

/// spine mesh attachment 转自定义网格格式
fn convert_spine_mesh_to_local(
    skin_name: &str,
    slot_name: &str,
    attachment_name: &str,
    mesh_value: &Value,
    global_bones: &[BoneDataStore],
) -> Result<MeshLocalDataStore, Error> {
    use std::collections::HashSet;

    let mesh_obj = mesh_value
        .as_object()
        .ok_or_else(|| Error::InvalidData("Mesh attachment is not a JSON object".to_string()))?;

    let uvs = mesh_obj
        .get("uvs")
        .and_then(|v| v.as_array())
        .ok_or_else(|| Error::InvalidData("Missing or invalid 'uvs' field".to_string()))?;
    let triangles = mesh_obj
        .get("triangles")
        .and_then(|v| v.as_array())
        .ok_or_else(|| Error::InvalidData("Missing or invalid 'triangles' field".to_string()))?;
    let vertices = mesh_obj
        .get("vertices")
        .and_then(|v| v.as_array())
        .ok_or_else(|| Error::InvalidData("Missing or invalid 'vertices' field".to_string()))?;

    let texture_name = mesh_obj
        .get("path")
        .and_then(|v| v.as_str())
        .or_else(|| mesh_obj.get("name").and_then(|v| v.as_str()))
        .unwrap_or(attachment_name)
        .to_string();

    if uvs.len() % 2 != 0 {
        return Err(Error::InvalidData(
            "UV array length must be even".to_string(),
        ));
    }
    let vertex_count = (uvs.len() / 2) as u32;
    if triangles.len() % 3 != 0 {
        return Err(Error::InvalidData(
            "Triangle array length must be multiple of 3".to_string(),
        ));
    }
    let triangles: Vec<u16> = triangles
        .iter()
        .map(|v| {
            v.as_u64()
                .map(|i| i as u16)
                .ok_or_else(|| Error::InvalidData("Invalid triangle index".to_string()))
        })
        .collect::<Result<_, _>>()?;
    for &idx in &triangles {
        if idx as u32 >= vertex_count {
            return Err(Error::InvalidData(format!(
                "Triangle index {} out of range for {} vertices",
                idx, vertex_count
            )));
        }
    }

    let uv_vec: Vec<f32> = uvs
        .iter()
        .map(|v| {
            v.as_f64()
                .map(|f| f as f32)
                .ok_or_else(|| Error::InvalidData("Invalid UV coordinate".to_string()))
        })
        .collect::<Result<_, _>>()?;

    let meta = MeshMetadata {
        skin: Some(skin_name.to_string()),
        slot: Some(slot_name.to_string()),
        name: Some(attachment_name.to_string()),
    };

    let is_weighted = vertices.len() > uvs.len();
    if !is_weighted {
        if vertices.len() != uvs.len() {
            return Err(Error::InvalidData(
                "Non-weighted vertices count doesn't match UV count".to_string(),
            ));
        }
        let vertices_locals: Vec<f32> = vertices
            .iter()
            .map(|v| {
                v.as_f64()
                    .map(|f| f as f32)
                    .ok_or_else(|| Error::InvalidData("Invalid vertex coordinate".to_string()))
            })
            .collect::<Result<_, _>>()?;
        return Ok(MeshLocalDataStore {
            meta,
            texture_name,
            uvs: Some(uv_vec),
            vertex_count,
            triangles,
            bones: None,
            influence_counts: None,
            vertices_locals,
            influence_bone_indices: None,
            influence_weights: None,
            clip_end_slot: None,
        });
    }

    let vertices_f32: Vec<f32> = vertices
        .iter()
        .map(|v| {
            v.as_f64()
                .map(|f| f as f32)
                .ok_or_else(|| Error::InvalidData("Invalid vertex data".to_string()))
        })
        .collect::<Result<_, _>>()?;
    let (positions, influence_counts, influence_weights, influence_bone_indices) =
        parse_spine_weighted_vertices(&vertices_f32);
    if influence_counts.len() != vertex_count as usize {
        return Err(Error::InvalidData(format!(
            "Weighted vertex count ({}) doesn't match UV count ({})",
            influence_counts.len(),
            vertex_count
        )));
    }

    let mut unique_bone_indices = HashSet::new();
    for idx in &influence_bone_indices {
        if *idx >= global_bones.len() {
            return Err(Error::InvalidIndex(format!(
                "Bone index {} out of range ({} bones available)",
                idx,
                global_bones.len()
            )));
        }
        unique_bone_indices.insert(*idx);
    }
    let bones: Vec<String> = unique_bone_indices
        .iter()
        .map(|&idx| global_bones[idx].name.clone())
        .collect();
    let bone_index_map: Vec<usize> = (0..global_bones.len())
        .map(|i| {
            if unique_bone_indices.contains(&i) {
                bones
                    .iter()
                    .position(|b| &global_bones[i].name == b)
                    .unwrap()
            } else {
                usize::MAX
            }
        })
        .collect();

    let mut vertices_locals = Vec::with_capacity(positions.len() * 2);
    let mut new_influence_bone_indices = Vec::with_capacity(influence_bone_indices.len());
    let mut pos_index = 0;
    for &count in &influence_counts {
        for _ in 0..count {
            vertices_locals.push(positions[pos_index].0);
            vertices_locals.push(positions[pos_index].1);
            let global_bone_idx = influence_bone_indices[pos_index];
            new_influence_bone_indices.push(bone_index_map[global_bone_idx] as u8);
            pos_index += 1;
        }
    }

    Ok(MeshLocalDataStore {
        meta,
        texture_name,
        uvs: Some(uv_vec),
        vertex_count,
        triangles,
        bones: Some(bones),
        influence_counts: Some(influence_counts),
        vertices_locals,
        influence_bone_indices: Some(new_influence_bone_indices),
        influence_weights: Some(influence_weights),
        clip_end_slot: None,
    })
}

/// spine clipping attachment 转自定义网格格式(裁剪多边形,无 UV/三角形,clip_end_slot 标记)
///
/// vertices 支持两种 spine 顶点格式:
/// - 非加权:len == vertexCount * 2,每顶点 [x, y],绑定 slot 主骨骼(bones = None)
/// - 加权:每顶点 [影响骨骼数, (骨骼索引, x, y, 权重)*n](与 mesh 加权格式一致)
fn convert_spine_clip_to_local(
    skin_name: &str,
    slot_name: &str,
    attachment_name: &str,
    clip_value: &Value,
    global_bones: &[BoneDataStore],
) -> Result<MeshLocalDataStore, Error> {
    let clip_obj = clip_value
        .as_object()
        .ok_or_else(|| Error::InvalidData("Clip attachment is not a JSON object".to_string()))?;
    let vertex_count = clip_obj
        .get("vertexCount")
        .and_then(|v| v.as_u64())
        .ok_or_else(|| {
            Error::InvalidData(format!("clip '{attachment_name}' missing vertexCount"))
        })? as u32;
    let end_slot = clip_obj
        .get("end")
        .and_then(|v| v.as_str())
        .ok_or_else(|| Error::InvalidData(format!("clip '{attachment_name}' missing end slot")))?
        .to_string();
    let vertices: Vec<f32> = clip_obj
        .get("vertices")
        .and_then(|v| v.as_array())
        .ok_or_else(|| Error::InvalidData(format!("clip '{attachment_name}' missing vertices")))?
        .iter()
        .map(|v| {
            v.as_f64()
                .ok_or_else(|| {
                    Error::InvalidData(format!("clip '{attachment_name}' vertex must be a number"))
                })
                .map(|n| n as f32)
        })
        .collect::<Result<_, _>>()?;

    let meta = MeshMetadata {
        name: Some(attachment_name.to_string()),
        slot: Some(slot_name.to_string()),
        skin: Some(skin_name.to_string()),
    };

    // 非加权:顶点直接是 [x, y] 序列
    if vertices.len() == vertex_count as usize * 2 {
        return Ok(MeshLocalDataStore {
            meta,
            texture_name: attachment_name.to_string(),
            uvs: None,
            vertex_count,
            triangles: vec![],
            bones: None,
            influence_counts: None,
            vertices_locals: vertices,
            influence_bone_indices: None,
            influence_weights: None,
            clip_end_slot: Some(end_slot),
        });
    }

    // 加权:与 mesh 相同格式
    let (positions, influence_counts, influence_weights, influence_bone_indices) =
        parse_spine_weighted_vertices(&vertices);
    if influence_counts.len() != vertex_count as usize {
        return Err(Error::InvalidData(format!(
            "Weighted clip vertex count ({}) doesn't match vertexCount ({})",
            influence_counts.len(),
            vertex_count
        )));
    }

    // 全局骨骼索引 -> 本 clip 用到的骨骼列表 + 局部索引(与 mesh 转换一致)
    let mut unique_bone_indices = HashSet::new();
    for &idx in &influence_bone_indices {
        if idx >= global_bones.len() {
            return Err(Error::InvalidIndex(format!(
                "Bone index {} out of range ({} bones available)",
                idx,
                global_bones.len()
            )));
        }
        unique_bone_indices.insert(idx);
    }
    let bones: Vec<String> = unique_bone_indices
        .iter()
        .map(|&idx| global_bones[idx].name.clone())
        .collect();
    let bone_index_map: Vec<usize> = (0..global_bones.len())
        .map(|i| {
            if unique_bone_indices.contains(&i) {
                bones
                    .iter()
                    .position(|b| &global_bones[i].name == b)
                    .unwrap()
            } else {
                usize::MAX
            }
        })
        .collect();

    let mut vertices_locals = Vec::with_capacity(positions.len() * 2);
    let mut new_influence_bone_indices = Vec::with_capacity(influence_bone_indices.len());
    let mut pos_index = 0;
    for &count in &influence_counts {
        for _ in 0..count {
            vertices_locals.push(positions[pos_index].0);
            vertices_locals.push(positions[pos_index].1);
            let global_bone_idx = influence_bone_indices[pos_index];
            new_influence_bone_indices.push(bone_index_map[global_bone_idx] as u8);
            pos_index += 1;
        }
    }

    Ok(MeshLocalDataStore {
        meta,
        texture_name: attachment_name.to_string(),
        uvs: None,
        vertex_count,
        triangles: vec![],
        bones: Some(bones),
        influence_counts: Some(influence_counts),
        vertices_locals,
        influence_bone_indices: Some(new_influence_bone_indices),
        influence_weights: Some(influence_weights),
        clip_end_slot: Some(end_slot),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        custom_index::AsIndex,
        data::runtime::{animate::AnimateConfig, clip::Clip, payload::PayloadUsage},
    };

    /// slot color 解析:缺省白色,hex(可带#)转 RGBA 0-1
    #[test]
    fn parse_slot_default_color() {
        let root = serde_json::json!({
            "bones": [ { "name": "root" } ],
            "slots": [
                { "name": "plain", "bone": "root" },
                { "name": "tinted", "bone": "root", "color": "#ce3a3aff" }
            ]
        });
        let import = import_spine(&root).unwrap();
        assert_eq!(import.slots.len(), 2);
        assert_eq!(import.slots[0].color, [1.0, 1.0, 1.0, 1.0]);
        assert!((import.slots[1].color[0] - 0xce as f32 / 255.0).abs() < 1e-6);
        assert!((import.slots[1].color[1] - 0x3a as f32 / 255.0).abs() < 1e-6);
        assert_eq!(import.slots[1].color[2], 0x3a as f32 / 255.0);
        assert_eq!(import.slots[1].color[3], 1.0);
    }

    /// attachment color 解析:region / mesh 都读 color,缺省白色
    #[test]
    fn parse_attachment_default_color() {
        let root = serde_json::json!({
            "bones": [ { "name": "root" } ],
            "slots": [ { "name": "s", "bone": "root", "attachment": "plain" } ],
            "skins": [
                { "name": "default", "attachments": {
                    "s": {
                        "plain": { "type": "region", "path": "p", "width": 10, "height": 10 },
                        "tinted": { "type": "region", "path": "p", "width": 10, "height": 10, "color": "ff000080" }
                    }
                } }
            ]
        });
        let import = import_spine(&root).unwrap();
        let plain = import
            .skin_attachments
            .iter()
            .find(|a| a.logical == "plain")
            .unwrap();
        let tinted = import
            .skin_attachments
            .iter()
            .find(|a| a.logical == "tinted")
            .unwrap();
        assert_eq!(plain.color, [1.0, 1.0, 1.0, 1.0]);
        assert_eq!(tinted.color, [1.0, 0.0, 0.0, 0x80 as f32 / 255.0]);
    }

    /// 集成(资产):Heidi Camera_1 各网格三角形绕向检查(bevy 默认背面剔除 FrontFace::Ccw,
    /// y 向上坐标下 CCW=正绕向;混合/反向的网格在 bevy 会显示背面(翻转)或被剔除)
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_heidi_triangle_winding() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .join("assets");
        let json = std::fs::read_to_string(root.join("HeidiSkin1.skel.json")).unwrap();
        let atlas = std::fs::read_to_string(root.join("HeidiSkin1.atlas.txt")).unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();
        let skin_idx = rt.skins.get_index("default").unwrap();
        let anim_idx = rt.animates.get_index("Camera_1").unwrap();
        let mut config = AnimateConfig::new();
        let payloads = rt.render_frame(&[skin_idx], anim_idx, &mut config, 0.0);
        let mut mixed = Vec::new();
        let mut all_neg = Vec::new();
        for p in payloads
            .iter()
            .filter(|p| matches!(p.usage, PayloadUsage::Mesh(_)))
        {
            let mut neg = 0usize;
            let mut total = 0usize;
            for tri in p.indices.chunks_exact(3) {
                let a = p.positions[tri[0] as usize];
                let b = p.positions[tri[1] as usize];
                let c = p.positions[tri[2] as usize];
                let s = (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
                if s < 0.0 {
                    neg += 1;
                }
                total += 1;
            }
            let name = match p.usage {
                PayloadUsage::Mesh(idx) => rt.meshs.data_map[idx]
                    .meta
                    .name
                    .clone()
                    .unwrap_or_else(|| "?".into()),
                _ => unreachable!(),
            };
            if neg > 0 && neg < total {
                mixed.push((name, neg, total));
            } else if neg == total {
                all_neg.push((name, total));
            }
        }
        eprintln!("mixed winding: {mixed:?}");
        eprintln!("all-CW (reversed): {all_neg:?}");
        assert!(
            mixed.is_empty(),
            "混合绕向网格在 bevy 会被剔除一半: {mixed:?}"
        );
        assert!(
            all_neg.is_empty(),
            "全 CW 网格在 bevy 完全背面: {all_neg:?}"
        );
    }

    /// 集成(资产):HeidiSkin1 + Camera_1,验证 spine 4.1 "rgba" 键颜色时间轴被解析并在
    /// t=0.067~0.1s 变暗(拍照快门闪烁 8b8b8bff,官方运行时可见)
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_heidi_rgba_dark_flash() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .join("assets");
        let json = std::fs::read_to_string(root.join("HeidiSkin1.skel.json")).unwrap();
        let atlas = std::fs::read_to_string(root.join("HeidiSkin1.atlas.txt")).unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();
        let skin_idx = rt.skins.get_index("default").unwrap();
        let anim_idx = rt.animates.get_index("Camera_1").unwrap();
        // rgba 时间轴数(Camera_1 应有大量颜色时间轴,解析前为 0)
        let color_tl = rt
            .animates
            .slot_timelines(anim_idx)
            .iter()
            .filter(|t| t.channel == crate::data::runtime::animate::SlotChannel::Color)
            .count();
        eprintln!("Camera_1 color timelines: {color_tl}");
        assert!(color_tl > 30, "rgba 时间轴应被解析: {color_tl}");
        // t=0.0 白色;t=0.08(变暗区间 0.067~0.1)应有大量非白 tint(变暗)
        let mut config = AnimateConfig::new();
        let dark = rt
            .render_frame(&[skin_idx], anim_idx, &mut config, 0.08)
            .into_iter()
            .filter(|p| matches!(p.usage, PayloadUsage::Mesh(_)))
            .filter(|p| p.tint_color[0] < 0.9)
            .count();
        eprintln!("dark tint payloads at t=0.08: {dark}");
        assert!(dark > 20, "拍照变暗帧应使大量网格 tint 变暗: {dark}");
    }

    /// 集成(资产):HeidiSkin1 + Camera_1,验证 Head_Shadow 槽的半透明默认色流入 tint
    /// (文件里没有 color 时间轴,这是唯一的 tint 效果来源)
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_heidi_shadow_tint() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .join("assets");
        let json = std::fs::read_to_string(root.join("HeidiSkin1.skel.json")).unwrap();
        let atlas = std::fs::read_to_string(root.join("HeidiSkin1.atlas.txt")).unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();
        let skin_idx = rt.skins.get_index("default").unwrap();
        let anim_idx = rt.animates.get_index("Camera_1").unwrap();
        // 无 color 时间轴(确认前提)
        assert_eq!(rt.animates.slot_timeline_count(anim_idx), 40);
        let mut config = AnimateConfig::new();
        for t in [0.0, 0.5, 1.33] {
            let payloads = rt.render_frame(&[skin_idx], anim_idx, &mut config, t);
            let shadows: Vec<_> = payloads
                .iter()
                .filter(|p| matches!(p.usage, PayloadUsage::Mesh(_)))
                .map(|p| (rt.slots.data[p.slot].name.clone(), p.tint_color))
                .filter(|(n, _)| n.starts_with("Head_Shadow"))
                .collect();
            eprintln!("t={t}: shadow tints {shadows:?}");
            assert!(
                shadows.iter().any(|(_, c)| c[3] < 0.5),
                "t={t}: 阴影槽应带半透明默认色: {shadows:?}"
            );
        }
    }

    /// 集成(资产):1.json 里 2 个 attachment 带 color ce3a3aff(都是 clipping 多边形,
    /// 官方语义 clip 色仅调试绘制用,不影响裁剪)——验证颜色被解析并流入 AttachmentData
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_attachment_color_flow() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .join("assets");
        let json = std::fs::read_to_string(root.join("1.json")).unwrap();
        let atlas = std::fs::read_to_string(root.join("1.atlas")).unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();
        let skin_idx = rt.skins.get_index("default").unwrap();
        let slot_idx = rt.slots.get_index("Eye_L_Clip").unwrap();
        let name_idx = AttachmentNames::new(rt.slots.data.len()).intern(slot_idx, "Eye_L_Clip");
        let att = rt.skins.data[skin_idx].get(slot_idx, name_idx).unwrap();
        let c = rt.attachments.data[att].color;
        assert!((c[0] - 0xce as f32 / 255.0).abs() < 1e-6, "{c:?}");
        assert!((c[1] - 0x3a as f32 / 255.0).abs() < 1e-6, "{c:?}");
        assert_eq!(c[3], 1.0);
        // 渲染:所有普通 mesh payload 保持白 tint(clip 色不参与渲染,正确语义)
        let anim_idx = rt.animates.get_index("Touch_Idle").unwrap();
        let mut config = AnimateConfig::new();
        let payloads = rt.render_frame(&[skin_idx], anim_idx, &mut config, 0.0);
        for p in payloads
            .iter()
            .filter(|p| matches!(p.usage, PayloadUsage::Mesh(_)))
        {
            assert_eq!(
                p.tint_color,
                [1.0, 1.0, 1.0, 1.0],
                "{:?}",
                rt.slots.data[p.slot].name
            );
        }
    }

    /// 集成:真实文件构建 RT,验证 clip 解析与 ClipStart/ClipEnd 配对
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_render_frame_clips() {
        let json = std::fs::read_to_string("assets/1.json").unwrap();
        let atlas = std::fs::read_to_string("assets/1.atlas").unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();

        let clip_count = rt
            .meshs
            .data_map
            .iter()
            .filter(|(_, _, m)| m.clip_end_slot.is_some())
            .count();
        eprintln!(
            "clip meshes: {clip_count} (total {} meshes)",
            rt.meshs.data_map.len()
        );
        assert!(clip_count >= 2, "Aya 应有 2 个眼睛裁剪");

        // 诊断:clip 网格的 end 槽与 slot 顺序
        for (_, _, m) in rt.meshs.data_map.iter() {
            if let Some(end) = m.clip_end_slot {
                eprintln!(
                    "clip '{}' -> end slot '{}' (idx {})",
                    m.meta.name.as_deref().unwrap_or("?"),
                    rt.slots.data[end].name,
                    end.as_index(),
                );
            }
        }

        let skins: Vec<_> = ["default", "Normal"]
            .iter()
            .filter_map(|n| rt.skins.get_index(n))
            .collect();
        let anim_idx = rt.animates.get_index("Angry_1").unwrap();
        let dur = rt.animates.duration(anim_idx);
        let mut config = AnimateConfig::new();
        let mut total_starts = 0usize;
        let mut total_ends = 0usize;
        for i in 0..=40 {
            let t = i as f32 / 40.0 * dur;
            let payloads = rt.render_frame(&skins, anim_idx, &mut config, t);
            let starts = payloads
                .iter()
                .filter(|p| matches!(p.usage, PayloadUsage::ClipStart { .. }))
                .count();
            let ends = payloads
                .iter()
                .filter(|p| matches!(p.usage, PayloadUsage::ClipEnd { .. }))
                .count();
            assert_eq!(
                starts, ends,
                "t={t:.2}: ClipStart({starts}) != ClipEnd({ends})"
            );
            total_starts += starts;
            total_ends += ends;
            // 每个 clip 多边形都有顶点交付
            for p in payloads
                .iter()
                .filter(|p| matches!(p.usage, PayloadUsage::ClipStart { .. }))
            {
                assert!(p.positions.len() >= 3, "clip 多边形至少 3 个顶点");
            }
        }
        eprintln!("clip frames checked: starts={total_starts} ends={total_ends} over 41 samples");
    }

    /// 集成:真实文件约束解析 + 应用验证(IK/transform 生效、动画覆盖、腿/脚跟随)
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_constraints_effect() {
        use crate::data::runtime::constraint::{ConstraintIdx, apply_constraints};

        let json = std::fs::read_to_string("assets/1.json").unwrap();
        let atlas = std::fs::read_to_string("assets/1.atlas").unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();

        // 约束解析数量
        eprintln!(
            "constraints: {} ik, {} transform (order {} items)",
            rt.constraints.ik.len(),
            rt.constraints.transform.len(),
            rt.constraints.order.len()
        );
        assert_eq!(rt.constraints.ik.len(), 4, "Aya 应有 4 个 IK 约束");
        assert!(!rt.constraints.transform.is_empty());

        // 骨架默认状态:IK mix(Leg_L_IK 默认 1 生效,Arm_L_Grab_IK 默认 0 不生效)
        let state = rt.constraints.new_state();
        for (i, c) in rt.constraints.ik.iter().enumerate() {
            let name0 = rt.skeleton.data_static.get_name(c.bones[0]).unwrap_or("?");
            eprintln!("ik[{i}] '{name0}' 默认 mix = {}", state.ik[i].mix);
        }

        // 应用约束到默认姿势:腿 IK 应让脚(Thigh_L 链末端)朝向 Leg_L_IK 目标
        let mut pose = rt.skeleton.default_pose();
        apply_constraints(&mut pose, &rt.skeleton, &rt.constraints, &state);

        // 动画约束时间轴:Angry_1 的 ik/transform
        let anim_idx = rt.animates.get_index("Angry_1").unwrap();
        let anim = rt.animates.slot_timelines(anim_idx); // 仅确认动画可采样
        let _ = anim;
        let mut config = crate::data::runtime::animate::AnimateConfig::new();
        let sampled = rt.animates.sample(anim_idx, &mut config, 0.5);
        eprintln!(
            "Angry_1 t=0.5 constraint values: {}",
            sampled.constraint_values.len()
        );
        for (idx, frame) in &sampled.constraint_values {
            match (idx, frame) {
                (
                    ConstraintIdx::Ik(i),
                    crate::data::runtime::animate::ConstraintKeyframe::Ik {
                        mix,
                        bend_positive,
                        ..
                    },
                ) => {
                    eprintln!(
                        "  ik[{}] mix={:?} bend_positive={:?}",
                        i, mix, bend_positive
                    );
                }
                (
                    ConstraintIdx::Transform(i),
                    crate::data::runtime::animate::ConstraintKeyframe::Transform {
                        mix_rotate,
                        mix_x,
                        ..
                    },
                ) => {
                    eprintln!(
                        "  transform[{}] mix_rotate={:?} mix_x={:?}",
                        i, mix_rotate, mix_x
                    );
                }
                _ => {}
            }
        }

        // 应用动画约束覆盖后重新求解:验证 IK 链(Upperarm_L_Grab)末端更接近目标
        let mut state = rt.constraints.new_state();
        sampled.apply_constraints(&mut state);
        let mut pose = rt.skeleton.default_pose();
        apply_constraints(&mut pose, &rt.skeleton, &rt.constraints, &state);
        eprintln!("constraints applied ok (no panic)");

        // 约束静态数据明细(骨骼 scale / 约束 mix / offset / order / local / relative)
        for (i, c) in rt.constraints.ik.iter().enumerate() {
            let names: Vec<String> = c
                .bones
                .iter()
                .map(|b| {
                    rt.skeleton
                        .data_static
                        .get_name(*b)
                        .unwrap_or("?")
                        .to_string()
                })
                .collect();
            let tgt = rt
                .skeleton
                .data_static
                .get_name(c.target)
                .unwrap_or("?")
                .to_string();
            eprintln!(
                "ik[{i}] bones={names:?} target={tgt} mix={} bendPositive={} order={}",
                c.mix, c.bend_positive, c.order
            );
        }
        for (i, c) in rt.constraints.transform.iter().enumerate() {
            let names: Vec<String> = c
                .bones
                .iter()
                .map(|b| {
                    rt.skeleton
                        .data_static
                        .get_name(*b)
                        .unwrap_or("?")
                        .to_string()
                })
                .collect();
            let tgt = rt
                .skeleton
                .data_static
                .get_name(c.target)
                .unwrap_or("?")
                .to_string();
            eprintln!(
                "transform[{i}] bones={names:?} target={tgt} mixR={} mixX={} mixY={} mixSX={} mixSY={} mixShY={} offR={} offX={} offY={} offSX={} offSY={} order={}",
                c.mix_rotate,
                c.mix_x,
                c.mix_y,
                c.mix_scale_x,
                c.mix_scale_y,
                c.mix_shear_y,
                c.offset_rotation,
                c.offset_x,
                c.offset_y,
                c.offset_scale_x,
                c.offset_scale_y,
                c.order
            );
        }
        // 骨骼 scale 异常(非 1):IK 与 transform 约束受影响
        let mut bad = 0;
        for i in 0..rt.skeleton.data_static.len() {
            let d = &rt.skeleton.data_static
                [unsafe { crate::data::runtime::skeleton::BoneIdx::from_index(i) }];
            bad += 1;
            if bad <= 8 {
                eprintln!(
                    "non-unit scale bone '{}' sx={} sy={}",
                    rt.skeleton
                        .data_static
                        .get_name(unsafe { crate::data::runtime::skeleton::BoneIdx::from_index(i) })
                        .unwrap_or("?"),
                    d.scale_x,
                    d.scale_y
                );
            }
        }
        eprintln!("non-unit scale bones total: {bad}");
    }

    /// 集成:与官方 spine-ts 数值对照 —— 采样 Angry_1 t=0.5,dump 骨骼世界位置到文件
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn dump_bones_for_official_comparison() {
        let json = std::fs::read_to_string("assets/1.json").unwrap();
        let atlas = std::fs::read_to_string("assets/1.atlas").unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();
        let anim_idx = rt.animates.get_index("Angry_1").unwrap();
        let mut config = crate::data::runtime::animate::AnimateConfig::new();
        let mut pose = rt.skeleton.default_pose();
        let t = std::env::var("DUMP_T")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(0.5);
        let sampled = rt.animates.sample(anim_idx, &mut config, t);
        sampled.apply_pose(&mut pose);
        let mut state = rt.constraints.new_state();
        sampled.apply_constraints(&mut state);
        crate::data::runtime::constraint::apply_constraints(
            &mut pose,
            &rt.skeleton,
            &rt.constraints,
            &state,
        );

        let mut out = String::from("[\n");
        for i in 0..rt.skeleton.data_static.len() {
            let w = pose.get_world_affine(&rt.skeleton, unsafe {
                crate::data::runtime::skeleton::BoneIdx::from_index(i)
            });
            let name = rt
                .skeleton
                .data_static
                .get_name(unsafe { crate::data::runtime::skeleton::BoneIdx::from_index(i) })
                .unwrap_or("?");
            let rot = w.matrix2.x_axis.y.atan2(w.matrix2.x_axis.x).to_degrees();
            out.push_str(&format!(
                "  {{\"name\":\"{name}\",\"x\":{:.3},\"y\":{:.3},\"rotation\":{:.3}}},\n",
                w.translation.x, w.translation.y, rot
            ));
        }
        out.push_str("]\n");
        std::fs::write("R:/Temp/opencode/our_dump.json", out).unwrap();
        // draw order 对照:找出所有带 drawOrder 的动画,采样并输出绘制顺序(slot 名)
        let mut do_map = serde_json::Map::new();
        for name in rt.animates.keys() {
            let anim_idx = rt.animates.get_index(name).unwrap();
            let mut config = crate::data::runtime::animate::AnimateConfig::new();
            let mut orders = serde_json::Map::new();
            for t in [0.0f32, 0.5, 1.0] {
                let sampled = rt.animates.sample(anim_idx, &mut config, t);
                let order = sampled.draw_order.map(|o| {
                    o.iter()
                        .map(|&i| {
                            rt.slots
                                .data
                                .get_name(unsafe {
                                    crate::data::runtime::slot::SlotIdx::from_index(i as usize)
                                })
                                .unwrap_or("?")
                                .to_string()
                        })
                        .collect::<Vec<_>>()
                });
                orders.insert(format!("{t}"), serde_json::json!(order));
            }
            if orders.values().any(|v| v.as_array().is_some()) {
                do_map.insert(name.to_string(), serde_json::Value::Object(orders));
            }
        }
        std::fs::write(
            "R:/Temp/opencode/our_draworder.json",
            serde_json::to_string_pretty(&serde_json::Value::Object(do_map)).unwrap(),
        )
        .unwrap();
        eprintln!("dumped to R:/Temp/opencode/our_dump.json");
    }

    /// 集成:deform 与官方 spine-ts 对照(构造数据,非加权网格 + 曲线插值)
    #[test]
    #[ignore = "requires external test data"]
    fn diagnose_deform_matches_official() {
        let json = std::fs::read_to_string("R:/Temp/opencode/deform_test.json").unwrap();
        let atlas = "m.png\nsize: 8, 8\nformat: RGBA8888\nfilter: Linear, Linear\nrepeat: none\nm\n  rotate: false\n  xy: 0, 0\n  size: 8, 8\n  orig: 8, 8\n  offset: 0, 0\n  index: -1\n";
        let (rt, _pages) = build_rt(&json, atlas).unwrap();
        let anim_idx = rt.animates.get_index("deform_anim").unwrap();
        let skin_idx = rt.skins.get_index("default").unwrap();
        let mut config = crate::data::runtime::animate::AnimateConfig::new();
        // 官方 t=0.5: 5,10,115,20,125,130,35,140(线性插值中点)
        for (t, expect) in [
            (
                0.0f32,
                vec![10.0, 20.0, 130.0, 40.0, 150.0, 160.0, 70.0, 180.0],
            ),
            (0.5, vec![5.0, 10.0, 115.0, 20.0, 125.0, 130.0, 35.0, 140.0]),
            (1.0, vec![0.0, 0.0, 100.0, 0.0, 100.0, 100.0, 0.0, 100.0]),
        ] {
            let payloads = rt.render_frame(&[skin_idx], anim_idx, &mut config, t);
            // 找到 slot s 的 mesh payload
            let slot_idx = rt.slots.get_index("s").unwrap();
            let pos = payloads
                .iter()
                .find(|p| p.slot == slot_idx)
                .map(|p| p.positions.clone())
                .unwrap();
            for (i, b) in expect.iter().enumerate() {
                if i % 2 != 0 {
                    continue;
                }
                let (x, y) = (pos[i / 2].x, pos[i / 2].y);
                let (ex, ey) = (b, expect[i + 1]);
                assert!(
                    (x - ex).abs() < 0.01 && (y - ey).abs() < 0.01,
                    "t={t} vertex {}: ours ({x},{y}), official ({ex},{ey})",
                    i / 2
                );
            }
        }
        eprintln!("deform matches official (unweighted, curve interpolation)");
    }

    /// 诊断:Grab 槽(Sleeve_L_1_Front_Grab2 等)的实际渲染结果——皮肤附件查找缺 slot 维度的验证
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_grab_slot_rendering() {
        let json = std::fs::read_to_string("assets/1.json").unwrap();
        let atlas = std::fs::read_to_string("assets/1.atlas").unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();

        // 皮肤里 "(slot, 逻辑名)" 对应的附件(带 slot 维度,各槽查各的)
        let skins: Vec<_> = ["default", "Normal"]
            .iter()
            .filter_map(|n| rt.skins.get_index(n))
            .collect();
        let mut names = AttachmentNames::new(rt.slots.data.len());
        for &sk in &skins {
            for (slot_name, logical) in [
                ("Sleeve_L_1_Front", "Sleeve_L_1_Front"),
                ("Sleeve_L_1_Front_Grab", "Sleeve_L_1_Front"),
                ("Sleeve_L_1_Front_Grab2", "Sleeve_L_1_Front"),
            ] {
                let Some(slot_idx) = rt.slots.get_index(slot_name) else {
                    continue;
                };
                let name_idx = names.intern(slot_idx, logical);
                if let Some(att) = rt.skins.data[sk].get(slot_idx, name_idx) {
                    let mesh_idx = rt.attachments.get_mesh(att).unwrap();
                    let m = &rt.meshs.data_map[mesh_idx];
                    eprintln!(
                        "skin get('{slot_name}','{logical}') -> mesh slot='{}' name='{}'",
                        m.meta.slot.as_deref().unwrap_or("?"),
                        m.meta.name.as_deref().unwrap_or("?"),
                    );
                }
            }
        }

        // 渲染帧:Grab 相关槽输出的网格
        let anim_idx = rt.animates.get_index("Angry_1").unwrap();
        let mut config = AnimateConfig::new();
        let payloads = rt.render_frame(&skins, anim_idx, &mut config, 0.0);
        for p in &payloads {
            let slot_name = &rt.slots.data[p.slot].name;
            if slot_name.contains("Sleeve") {
                let mesh_name = match p.usage {
                    PayloadUsage::Mesh(idx) => {
                        let m = &rt.meshs.data_map[idx];
                        format!(
                            "slot='{}' name='{}'",
                            m.meta.slot.as_deref().unwrap_or("?"),
                            m.meta.name.as_deref().unwrap_or("?")
                        )
                    }
                    PayloadUsage::ClipStart { id } => format!(
                        "CLIP slot='{}' name='{:?}'",
                        rt.meshs.data_map[id].meta.slot.as_deref().unwrap_or("?"),
                        rt.meshs.data_map[id].meta.name
                    ),
                    PayloadUsage::ClipEnd { .. } => "ClipEnd".to_string(),
                };
                eprintln!("slot '{slot_name}' -> mesh '{mesh_name}'");
            }
        }
    }

    /// 集成:软件裁剪后,眼睛网格(Eye_*)的顶点应全部落在 clip 多边形内,且至少一个被切碎
    #[test]
    #[ignore = "requires assets files, not in repo"]
    fn diagnose_software_clipping_effect() {
        use glam::Vec2;

        // 射线法:点是否在多边形内(边界上的点视为在内,SH 裁剪会输出边界交点)
        fn point_in_polygon(p: Vec2, poly: &[Vec2]) -> bool {
            let n = poly.len();
            for i in 0..n {
                let a = poly[i];
                let b = poly[(i + 1) % n];
                let ab = b - a;
                let len2 = ab.dot(ab);
                if len2 < 1e-12 {
                    continue;
                }
                // 投影参数 t ∈ [0,1] 且到线段距离在容差内 → 边上
                let t = (p - a).dot(ab) / len2;
                if (0.0..=1.0).contains(&t) {
                    let d = (a + ab * t - p).length();
                    if d <= 1e-2 {
                        return true;
                    }
                }
            }
            let mut inside = false;
            for i in 0..n {
                let a = poly[i];
                let b = poly[(i + 1) % n];
                if (a.y > p.y) != (b.y > p.y) {
                    let x = a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y);
                    if p.x < x {
                        inside = !inside;
                    }
                }
            }
            inside
        }

        let json = std::fs::read_to_string("assets/1.json").unwrap();
        let atlas = std::fs::read_to_string("assets/1.atlas").unwrap();
        let (rt, _pages) = build_rt(&json, &atlas).unwrap();

        let skins: Vec<_> = ["default", "Normal"]
            .iter()
            .filter_map(|n| rt.skins.get_index(n))
            .collect();
        let anim_idx = rt.animates.get_index("Angry_1").unwrap();
        let dur = rt.animates.duration(anim_idx);
        let mut config = AnimateConfig::new();

        let mut cut_meshes = 0usize;
        let mut max_verts = 0usize;
        let mut clipped_meshes_seen = 0usize;
        let mut names_seen: Vec<String> = Vec::new();
        for i in 0..=40 {
            let t = i as f32 / 40.0 * dur;
            let raw = rt.render_frame(&skins, anim_idx, &mut config, t);
            // 裁剪前解析指令流:按 payload 顺序记录每个 Mesh 对应的裁剪多边形
            let mut mesh_polys: Vec<Option<Vec<Vec2>>> = Vec::new();
            let mut stack: Vec<Vec<Vec2>> = Vec::new();
            for p in &raw {
                match p.usage {
                    PayloadUsage::ClipStart { .. } => stack.push(p.positions.clone()),
                    PayloadUsage::ClipEnd { .. } => {
                        stack.pop();
                    }
                    PayloadUsage::Mesh(_) => mesh_polys.push(stack.last().cloned()),
                }
            }
            let mut clipped = raw;
            clipped.clip_software();
            let mut mi = 0usize;
            for p in &clipped {
                let PayloadUsage::Mesh(mesh_idx) = p.usage else {
                    continue;
                };
                let Some(Some(clip_poly)) = mesh_polys.get(mi) else {
                    mi += 1;
                    continue;
                };
                mi += 1;
                let meta = &rt.meshs.data_map[mesh_idx].meta;
                let name = meta.name.as_deref().unwrap_or("");
                if !names_seen.contains(&name.to_string()) {
                    names_seen.push(name.to_string());
                }
                if name.contains("Eye") {
                    clipped_meshes_seen += 1;
                    // 裁剪后所有顶点必须落在裁剪多边形内(严格裁剪生效)
                    for v in &p.positions {
                        assert!(
                            point_in_polygon(*v, clip_poly),
                            "t={t:.2} Eye mesh '{name}' 顶点 {v:?} 在裁剪区域外"
                        );
                    }
                    // 与裁剪边界相交的网格会被切碎(顶点数增多);完全在内则保持
                    if p.positions.len() > 4 {
                        cut_meshes += 1;
                        max_verts = max_verts.max(p.positions.len());
                    }
                }
            }
        }
        assert!(
            clipped_meshes_seen > 0,
            "未找到 Eye mesh payload;裁剪区间的网格: {names_seen:?}"
        );
        assert!(cut_meshes > 0, "没有任何 Eye mesh 被裁剪切碎");
        eprintln!(
            "software clipping effect: {clipped_meshes_seen} eye meshes clipped, {cut_meshes} cut, max verts {max_verts} (original 4)"
        );
    }

    #[test]
    #[ignore = "requires assets/1.json (spine export), not in repo"]
    fn import_real_spine_file() {
        let file = std::fs::read_to_string("assets/1.json").unwrap();
        let root: Value = serde_json::from_str(&file).unwrap();
        let import = import_spine(&root).unwrap();
        assert!(!import.bones.is_empty());
        assert!(!import.slots.is_empty());
        assert!(!import.meshes.is_empty());
        assert!(!import.skin_attachments.is_empty());
        eprintln!(
            "bones={} slots={} meshes={} skin_attachments={}",
            import.bones.len(),
            import.slots.len(),
            import.meshes.len(),
            import.skin_attachments.len()
        );
        // 网格数据基本一致性
        for m in &import.meshes {
            assert!(
                m.vertex_count as usize * 2 == m.vertices_locals.len()
                    || m.influence_counts.is_some()
            );
        }
    }

    #[test]
    #[ignore = "requires assets/1.atlas (spine export), not in repo"]
    fn parse_real_atlas() {
        let file = std::fs::read_to_string("assets/1.atlas").unwrap();
        let atlas = parse_atlas(&file).unwrap();
        assert!(!atlas.pages.is_empty());
        assert!(!atlas.regions.is_empty());
        // Ball_L: bounds 1771,726,85,73 offsets 1,0,87,73(真实数据)
        let ball = atlas.regions.iter().find(|r| r.name == "Ball_L").unwrap();
        assert_eq!(ball.x, 1771.0);
        assert_eq!(ball.y, 726.0);
        assert_eq!(ball.width, 85.0);
        assert_eq!(ball.height, 73.0);
        assert_eq!(ball.offset_x, 1.0);
        assert_eq!(ball.offset_y, 0.0);
        assert_eq!(ball.original_width, 87.0);
        assert_eq!(ball.original_height, 73.0);
        assert_eq!(ball.degrees, 0);
        assert_eq!(atlas.pages[ball.page].name, "Aya.png");
        assert_eq!(atlas.pages[ball.page].width, 2048.0);
        assert_eq!(atlas.pages[ball.page].height, 1024.0);
        assert!(
            atlas.pages[ball.page].pma,
            "1.atlas 的 Aya.png 页是 pma:true"
        );
    }

    #[test]
    #[ignore = "requires assets/1.json + 1.atlas (spine export), not in repo"]
    fn apply_atlas_converts_uvs_to_atlas_coords() {
        let json = std::fs::read_to_string("assets/1.json").unwrap();
        let root: Value = serde_json::from_str(&json).unwrap();
        let atlas = parse_atlas(&std::fs::read_to_string("assets/1.atlas").unwrap()).unwrap();
        let mut import = import_spine(&root).unwrap();
        apply_atlas(&mut import.meshes, &atlas).unwrap();
        // Ball_L mesh:转换后 UV 必须落在其图集区域 [x/w, (x+w)/w] × [y/h, (y+h)/h]
        let ball = atlas.regions.iter().find(|r| r.name == "Ball_L").unwrap();
        let page = &atlas.pages[ball.page];
        let u_min = ball.x / page.width;
        let u_max = (ball.x + ball.width) / page.width;
        let v_min = ball.y / page.height;
        let v_max = (ball.y + ball.height) / page.height;
        let mesh = import
            .meshes
            .iter()
            .find(|m| m.texture_name == page.name && m.uvs.is_some())
            .expect("no converted Ball_L mesh");
        for uv in mesh.uvs.as_ref().unwrap().chunks_exact(2) {
            assert!(
                uv[0] >= u_min - 1e-4 && uv[0] <= u_max + 1e-4,
                "u={}",
                uv[0]
            );
            assert!(
                uv[1] >= v_min - 1e-4 && uv[1] <= v_max + 1e-4,
                "v={}",
                uv[1]
            );
        }
        eprintln!(
            "atlas: pages={} regions={}, converted meshes={}",
            atlas.pages.len(),
            atlas.regions.len(),
            import.meshes.len()
        );
    }

    #[test]
    fn atlas_uv_rotation_branches() {
        // 构造一个 90 度旋转的 region,验证 UV 交换与翻转
        let page = AtlasPage {
            name: "p.png".into(),
            width: 100.0,
            height: 100.0,
            pma: false,
        };
        let region = AtlasRegion {
            page: 0,
            name: "r".into(),
            x: 10.0,
            y: 20.0,
            width: 30.0,
            height: 40.0,
            offset_x: 0.0,
            offset_y: 0.0,
            original_width: 40.0,
            original_height: 30.0,
            degrees: 90,
        };
        // 90 度:u = 0.1 - (30-40)/100 = 0.2, v = 0.2 - (40-30)/100 = 0.1
        // width = 30/100, height = 40/100
        // 局部 (0,0) -> u = 0.2 + 0*0.3 = 0.2, v = 0.1 + (1-0)*0.4 = 0.5
        // 局部 (1,1) -> u = 0.2 + 1*0.3 = 0.5, v = 0.1 + 0 = 0.1
        let out = region_uvs_to_atlas(&region, &page, &[0.0, 0.0, 1.0, 1.0]);
        assert!((out[0] - 0.2).abs() < 1e-4 && (out[1] - 0.5).abs() < 1e-4);
        assert!((out[2] - 0.5).abs() < 1e-4 && (out[3] - 0.1).abs() < 1e-4);
        // 0 度无偏移:u=0.1, v=0.2, w=0.3, h=0.4
        // 局部 (0,0) -> (0.1, 0.2),(1,1) -> (0.1+0.3, 0.2+0.4) = (0.4, 0.6)
        let region0 = AtlasRegion {
            degrees: 0,
            width: 30.0,
            height: 40.0,
            original_width: 30.0,
            original_height: 40.0,
            ..region
        };
        let out = region_uvs_to_atlas(&region0, &page, &[0.0, 0.0, 1.0, 1.0]);
        assert!((out[0] - 0.1).abs() < 1e-4 && (out[1] - 0.2).abs() < 1e-4);
        assert!((out[2] - 0.4).abs() < 1e-4 && (out[3] - 0.6).abs() < 1e-4);
    }

    #[test]
    fn debug_atlas_pixels_shape_and_colors() {
        let page = AtlasPage {
            name: "p.png".into(),
            width: 100.0,
            height: 100.0,
            pma: false,
        };
        let atlas = Atlas {
            pages: vec![page],
            regions: vec![AtlasRegion {
                page: 0,
                name: "r".into(),
                x: 10.0,
                y: 20.0,
                width: 30.0,
                height: 40.0,
                offset_x: 0.0,
                offset_y: 0.0,
                original_width: 30.0,
                original_height: 40.0,
                degrees: 0,
            }],
        };
        let pixels = build_debug_atlas_pixels(&atlas, 0, 42).unwrap();
        assert_eq!(pixels.len(), 100 * 100 * 4);
        let px = |x: usize, y: usize| -> [u8; 4] {
            let i = (y * 100 + x) * 4;
            [pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
        };
        // 区域外:深灰背景
        assert_eq!(px(0, 0), [30, 30, 30, 255]);
        // 白色边框
        assert_eq!(px(10, 20), [255, 255, 255, 255]);
        assert_eq!(px(39, 59), [255, 255, 255, 255]);
        // 色块内部:非背景非白色(确定性随机色)
        let inner = px(25, 40);
        assert_ne!(inner, [30, 30, 30, 255]);
        assert_ne!(inner, [255, 255, 255, 255]);
        assert_eq!(inner[3], 255);
        // 固定 seed 结果稳定
        let again = build_debug_atlas_pixels(&atlas, 0, 42).unwrap();
        assert_eq!(pixels, again);
    }
}