draco-io 0.3.0

Rust IO helpers for Draco geometry compression formats
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
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
//! FBX scene reader: a tree of [`FbxNode`](crate::fbx_container::FbxNode) in,
//! an [`FbxScene`] out.
//!
//! Supports reading:
//! - Vertex positions, normals, texture coordinates, colours, and tangents
//! - Polygon/face indices, edges, smoothing flags, and crease weights
//! - Model hierarchy and local transforms through [`FbxReader::read_scene`]
//! - Phong/Lambert materials, textures, and per-polygon material indices
//! - Skin clusters, bind poses, and blend-shape targets
//! - Node-TRS animation (`AnimationStack` / `AnimationLayer` /
//!   `AnimationCurveNode` / `AnimationCurve`) flattened into TRS channels
//! - Cameras and lights, read into [`crate::FbxScene`] but never written back
//!
//! FBX pivots and inheritance rules and arbitrary metadata are not
//! represented.
//!
//! This module reads only the node tree; the containers that produce it are
//! [`crate::fbx_container`] for binary and [`crate::fbx_ascii`] for text.
//! Nothing here knows which one it was given, which is what lets one scene
//! layer serve both.
//!
//! # Example
//!
//! ```no_run
//! use draco_io::fbx_reader::FbxReader;
//! use draco_io::Reader;
//!
//! let mut reader = FbxReader::open("model.fbx")?;
//! let meshes = reader.read_meshes()?;
//! for mesh in meshes {
//!     println!("Mesh has {} vertices", mesh.num_points());
//! }
//! # Ok::<(), std::io::Error>(())
//! ```

use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{self, BufReader, Cursor, Read, Seek};
use std::path::Path;

use draco_core::mesh::Mesh;

use crate::fbx_scene::push_warning;
use crate::fbx_templates::{ObjectProperties, PropertyTemplates};
use crate::fbx_transform::{
    collect_transform_warnings, identity_transform, parse_transform, transform_array,
};

/// The container types, re-exported so `draco_io::fbx_reader::FbxNode` keeps
/// resolving for callers written before the decoder moved out.
pub use crate::fbx_container::{FbxMemoryReader, FbxNode, FbxProperty, FbxReader};

#[derive(Debug)]
struct FbxGeometrySource {
    mesh: Mesh,
    material_indices: Vec<i32>,
    control_points: Vec<[f32; 3]>,
    polygon_vertex_indices: Vec<i32>,
    layers: FbxMeshLayers,
    edges: Vec<i32>,
}

#[doc(hidden)]
pub use crate::fbx_scene::{
    FbxAnimChannel, FbxAnimChannelPath, FbxAnimInterpolation, FbxAnimSampler, FbxAnimation,
    FbxBinormalSet, FbxColorSet, FbxCreaseKind, FbxCreaseLayer, FbxLayerSet, FbxMeshInstance,
    FbxMeshLayers, FbxNodeAttribute, FbxNodeId, FbxNormalSet, FbxScene, FbxSceneNode,
    FbxSmoothingLayer, FbxTangentSet, FbxTexture, FbxTextureBinding, FbxTextureSlot, FbxTransform,
    FbxUvSet, FbxWarning, FbxWarningCode,
};
// Implement the Reader trait for the concrete BufReader<File> specialization.
impl crate::traits::Reader for FbxReader<BufReader<File>> {
    fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
        FbxReader::open(path)
    }

    fn read_meshes(&mut self) -> io::Result<Vec<draco_core::mesh::Mesh>> {
        // Call the inherent method which already reads all meshes.
        // Use fully qualified syntax to avoid recursion.
        FbxReader::read_meshes(self)
    }
}

impl crate::traits::Reader for FbxReader<Cursor<Vec<u8>>> {
    fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
        Self::from_bytes(fs::read(path)?)
    }

    fn read_meshes(&mut self) -> io::Result<Vec<draco_core::mesh::Mesh>> {
        FbxReader::read_meshes(self)
    }
}
impl<R: Read + Seek> FbxReader<R> {
    /// Reads the supported hierarchy, materials, textures, and animation from FBX.
    ///
    /// The result retains model names, local transforms, materialized mesh
    /// geometry (positions, normals, UVs), per-polygon material indices,
    /// Phong/Lambert materials, textures, and node-TRS animation. It
    /// intentionally omits FBX pivots, pre/post rotations, inheritance rules,
    /// cameras, and arbitrary metadata. It retains skin clusters, bind poses,
    /// blend-shape deltas, and local TRS animation.
    ///
    /// ```no_run
    /// use draco_io::FbxMemoryReader;
    ///
    /// let bytes = std::fs::read("model.fbx")?;
    /// let mut reader = FbxMemoryReader::from_bytes(bytes)?;
    /// let scene = reader.read_scene()?;
    /// assert!(!scene.root_nodes.is_empty());
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn read_scene(&mut self) -> io::Result<FbxScene> {
        let nodes = self.read_nodes()?;
        let global_settings = parse_global_settings(&nodes);

        let index = FbxObjectIndex::build(&nodes);
        // Borrow the fields the rest of this function reads. `index` stays
        // whole so it can be handed to the animation pass as one argument.
        let FbxObjectIndex {
            model_map,
            model_order,
            geometry_map,
            attribute_map,
            material_map,
            texture_map,
            video_map,
            deformer_map,
            pose_map,
            connections,
            templates,
            ..
        } = &index;

        // Container-layout notices raised by `read_nodes` above ride along
        // with the semantic ones, so a caller sees every tolerated deviation.
        let mut warnings = self.warnings().to_vec();
        // A pre-7000 document keys its objects and connections by name rather
        // than by id, and puts geometry on the `Model` itself. None of that is
        // read, so the scene comes back structurally valid but empty. Saying so
        // is the difference between "this file has no meshes" and "this reader
        // did not look for them".
        if index.name_keyed_objects > 0 {
            let count = index.name_keyed_objects;
            push_warning(
                &mut warnings,
                FbxWarningCode::NameKeyedObjectModel,
                format!(
                    "FBX document identifies its {count} objects by name rather than by id, \
                     which is the pre-7000 layout; no geometry, materials or animation were \
                     imported from it"
                ),
                None,
            );
        }
        collect_transform_warnings(model_map, model_order, templates, &mut warnings);
        let node_attributes = parse_node_attributes(
            attribute_map,
            model_map,
            connections,
            templates,
            &mut warnings,
        );

        // ---- Materials and textures ---------------------------------------
        let (materials, material_index_by_id, textures) = parse_materials_and_textures(
            material_map,
            texture_map,
            video_map,
            connections,
            templates,
        );

        // ---- Model hierarchy + per-model materials -----------------------
        // Map each model id to the list of material indices connected to it.
        let mut model_material_ids: HashMap<i64, Vec<i32>> = HashMap::new();
        for conn in connections {
            if conn.kind == ConnectionKind::Oo
                && material_map.contains_key(&conn.child)
                && model_map.contains_key(&conn.parent)
            {
                let mat_index = material_index_by_id[&conn.child] as i32;
                model_material_ids
                    .entry(conn.parent)
                    .or_default()
                    .push(mat_index);
            }
        }

        // Build parent map for models (same as before but over FbxConnection).
        let mut model_children: HashMap<i64, Vec<i64>> = HashMap::new();
        for conn in connections.iter() {
            if model_map.contains_key(&conn.child) || model_map.contains_key(&conn.parent) {
                model_children
                    .entry(conn.parent)
                    .or_default()
                    .push(conn.child);
            }
        }

        let ordered_model_ids = model_order;
        let model_node_ids: HashMap<i64, FbxNodeId> = ordered_model_ids
            .iter()
            .copied()
            .enumerate()
            .map(|(index, id)| (id, FbxNodeId((index + 1) as u32)))
            .collect();

        // Map geometries to models and create mesh instances.
        let mut model_mesh_instances: std::collections::HashMap<i64, Vec<FbxMeshInstance>> =
            std::collections::HashMap::new();
        let mut geometry_ids: Vec<i64> = geometry_map.keys().copied().collect();
        geometry_ids.sort_unstable();
        for geom_id in geometry_ids {
            let geom_node = geometry_map[&geom_id];
            if let Some(source) = geometry_to_mesh(geom_node, &mut warnings)? {
                let mesh = &source.mesh;
                let material_indices = source.material_indices.clone();
                // find connection mapping geometry -> model
                for conn in connections.iter() {
                    if conn.child == geom_id && model_map.contains_key(&conn.parent) {
                        // If the geometry does not carry its own material layer,
                        // fall back to materials connected directly to the model.
                        let mut indices = material_indices.clone();
                        if let Some(model_mats) = model_material_ids.get(&conn.parent) {
                            if indices.is_empty() {
                                if !model_mats.is_empty() {
                                    let first = model_mats[0];
                                    // One entry per triangulated face.
                                    indices = vec![first; mesh.num_faces()];
                                }
                            } else {
                                // LayerElementMaterial values address the
                                // material slots attached to this Model. Map
                                // them back to the document-wide material
                                // indices exposed by FbxScene.
                                indices = indices
                                    .into_iter()
                                    .map(|slot| {
                                        usize::try_from(slot)
                                            .ok()
                                            .and_then(|slot| model_mats.get(slot).copied())
                                            .unwrap_or(model_mats[0])
                                    })
                                    .collect();
                            }
                        }
                        let mesh_instance = FbxMeshInstance {
                            name: object_name(geom_node),
                            mesh: source.mesh.clone(),
                            control_points: source.control_points.clone(),
                            polygon_vertex_indices: source.polygon_vertex_indices.clone(),
                            layers: source.layers.clone(),
                            edges: source.edges.clone(),
                            material_indices: indices,
                            skin: parse_skin_for_geometry(
                                geom_id,
                                deformer_map,
                                pose_map,
                                connections,
                                &model_node_ids,
                            ),
                            morph_targets: parse_morph_targets_for_geometry(
                                geom_id,
                                geometry_map,
                                deformer_map,
                                connections,
                            ),
                        };
                        model_mesh_instances
                            .entry(conn.parent)
                            .or_default()
                            .push(mesh_instance);
                    }
                }
            }
        }

        // ---- Animation ----------------------------------------------------
        let model_name_map: HashMap<i64, String> = model_map
            .iter()
            .filter_map(|(id, node)| object_name(node).map(|name| (*id, name)))
            .collect();

        let animations = self.parse_animations(
            &nodes,
            &index,
            &model_name_map,
            &model_node_ids,
            &morph_animation_targets(geometry_map, deformer_map, connections, model_map),
        );

        // Build root nodes: any model with parent 0 (or with no parent present)
        let mut root_nodes = Vec::new();
        // find top-level model ids
        let top_level: Vec<i64> = ordered_model_ids
            .iter()
            .copied()
            .filter(|id| {
                !connections
                    .iter()
                    .any(|conn| conn.child == *id && model_map.contains_key(&conn.parent))
            })
            .collect();

        let graph = ModelGraph {
            models: model_map,
            children: &model_children,
            mesh_instances: &model_mesh_instances,
            node_ids: &model_node_ids,
            attributes: &node_attributes,
            templates,
        };
        for id in top_level {
            root_nodes.push(build_model_node(id, &graph, &mut Vec::new()));
        }

        Ok(FbxScene {
            global_settings,
            root_nodes,
            materials,
            textures,
            animations,
            warnings,
        })
    }
}

// Build nodes recursively
fn object_name(node: &FbxNode) -> Option<String> {
    match node.properties.get(1) {
        Some(FbxProperty::String(name)) => name
            .split('\0')
            .next()
            .filter(|name| !name.is_empty())
            .map(str::to_string),
        _ => None,
    }
}

/// Everything `build_model_node` needs about the document's model graph.
///
/// These six are only ever passed together, and passing them one by one put
/// the function at the argument limit before it had a resolver to carry.
struct ModelGraph<'a, 'n> {
    models: &'a std::collections::HashMap<i64, &'n FbxNode>,
    children: &'a std::collections::HashMap<i64, Vec<i64>>,
    mesh_instances: &'a std::collections::HashMap<i64, Vec<FbxMeshInstance>>,
    node_ids: &'a std::collections::HashMap<i64, FbxNodeId>,
    attributes: &'a std::collections::HashMap<i64, FbxNodeAttribute>,
    templates: &'a PropertyTemplates<'n>,
}

fn build_model_node(id: i64, graph: &ModelGraph<'_, '_>, ancestors: &mut Vec<i64>) -> FbxSceneNode {
    let node_src = graph.models.get(&id).unwrap();
    let mut node = FbxSceneNode::new(object_name(node_src));
    node.id = graph.node_ids[&id];
    if let Some((transform, transform_stack, has_complex_transform_stack)) =
        parse_transform(ObjectProperties::new(node_src, graph.templates))
    {
        node.transform = Some(transform);
        node.transform_stack = Some(transform_stack);
        node.has_complex_transform_stack = has_complex_transform_stack;
    }
    node.attribute = graph.attributes.get(&id).cloned();
    if let Some(mesh_instances) = graph.mesh_instances.get(&id) {
        node.mesh_instances.extend(mesh_instances.clone());
    }

    // The ancestor check below stops a plain cycle. This bounds the
    // rest: a document can chain models far deeper than any scene
    // graph needs, and the depth is the file's to choose.
    const MAX_MODEL_DEPTH: usize = 256;
    if ancestors.len() >= MAX_MODEL_DEPTH {
        return node;
    }
    if let Some(children) = graph.children.get(&id) {
        ancestors.push(id);
        for &cid in children {
            // A document may connect a Model to one of its own
            // ancestors -- `synthetic_id_collision_7500` in the ufbx
            // corpus does -- and following that cycle recurses until
            // the stack is gone. The scene simply stops there.
            if graph.models.contains_key(&cid) && !ancestors.contains(&cid) {
                node.children.push(build_model_node(cid, graph, ancestors));
            }
        }
        ancestors.pop();
    }
    node
}

fn parse_global_settings(nodes: &[FbxNode]) -> Option<crate::fbx_scene::FbxGlobalSettings> {
    let properties = nodes
        .iter()
        .find(|node| node.name == "GlobalSettings")?
        .children
        .iter()
        .find(|node| node.name == "Properties70")?;
    let integer = |property: &FbxNode| {
        property.properties.iter().find_map(|value| match value {
            FbxProperty::I16(value) => Some(*value as i32),
            FbxProperty::I32(value) => Some(*value),
            FbxProperty::I64(value) => i32::try_from(*value).ok(),
            _ => None,
        })
    };
    let number = |property: &FbxNode| {
        property.properties.iter().find_map(|value| match value {
            FbxProperty::F32(value) => Some(f64::from(*value)),
            FbxProperty::F64(value) => Some(*value),
            _ => None,
        })
    };
    let mut result = crate::fbx_scene::FbxGlobalSettings::default();
    for property in &properties.children {
        let Some(FbxProperty::String(name)) = property.properties.first() else {
            continue;
        };
        match name.as_str() {
            "UpAxis" => result.up_axis = integer(property),
            "UpAxisSign" => result.up_axis_sign = integer(property),
            "FrontAxis" => result.front_axis = integer(property),
            "FrontAxisSign" => result.front_axis_sign = integer(property),
            "CoordAxis" => result.coord_axis = integer(property),
            "CoordAxisSign" => result.coord_axis_sign = integer(property),
            "UnitScaleFactor" => result.unit_scale_factor = number(property),
            "OriginalUnitScaleFactor" => result.original_unit_scale_factor = number(property),
            "TimeMode" => result.time_mode = integer(property),
            _ => {}
        }
    }
    (result != crate::fbx_scene::FbxGlobalSettings::default()).then_some(result)
}

fn child_i32_array(node: &FbxNode, child_name: &str) -> Vec<i32> {
    node.children
        .iter()
        .find(|child| child.name == child_name)
        .and_then(|child| child.properties.first())
        .and_then(|value| match value {
            FbxProperty::I32Array(values) => Some(values.clone()),
            _ => None,
        })
        .unwrap_or_default()
}

fn child_f64_array(node: &FbxNode, child_name: &str) -> Vec<f64> {
    node.children
        .iter()
        .find(|child| child.name == child_name)
        .and_then(|child| child.properties.first())
        .and_then(|value| match value {
            FbxProperty::F64Array(values) => Some(values.clone()),
            FbxProperty::F32Array(values) => Some(values.iter().copied().map(f64::from).collect()),
            _ => None,
        })
        .unwrap_or_default()
}

fn parse_skin_for_geometry(
    geometry_id: i64,
    deformers: &std::collections::HashMap<i64, &FbxNode>,
    poses: &std::collections::HashMap<i64, &FbxNode>,
    connections: &[FbxConnection],
    model_node_ids: &std::collections::HashMap<i64, FbxNodeId>,
) -> Option<crate::fbx_scene::FbxSkin> {
    let skin_ids: Vec<i64> = connections
        .iter()
        .filter(|connection| {
            connection.kind == ConnectionKind::Oo && connection.parent == geometry_id
        })
        .map(|connection| connection.child)
        .filter(|id| {
            deformers
                .get(id)
                .and_then(|node| deformer_type(node).map(str::to_string))
                .as_deref()
                == Some("Skin")
        })
        .collect();
    if skin_ids.is_empty() {
        return None;
    }

    let mut clusters = Vec::new();
    for skin_id in skin_ids {
        for cluster_id in connections
            .iter()
            .filter(|connection| {
                connection.kind == ConnectionKind::Oo && connection.parent == skin_id
            })
            .map(|connection| connection.child)
        {
            let Some(cluster) = deformers.get(&cluster_id) else {
                continue;
            };
            if deformer_type(cluster) != Some("Cluster") {
                continue;
            }
            let Some(joint_model_id) = connections
                .iter()
                .find(|connection| {
                    connection.kind == ConnectionKind::Oo && connection.parent == cluster_id
                })
                .map(|connection| connection.child)
            else {
                continue;
            };
            let Some(&joint_node_id) = model_node_ids.get(&joint_model_id) else {
                continue;
            };
            let indices = child_i32_array(cluster, "Indexes")
                .into_iter()
                .filter_map(|index| u32::try_from(index).ok())
                .collect::<Vec<_>>();
            let mut weights = child_f64_array(cluster, "Weights")
                .into_iter()
                .map(|weight| weight as f32)
                .collect::<Vec<_>>();
            weights.truncate(indices.len());
            if weights.len() != indices.len() {
                continue;
            }
            clusters.push(crate::fbx_scene::FbxSkinCluster {
                joint_node_id,
                control_point_indices: indices,
                weights,
                mesh_bind_transform: transform_array(cluster, "Transform")
                    .unwrap_or_else(identity_transform),
                joint_bind_transform: transform_array(cluster, "TransformLink")
                    .unwrap_or_else(identity_transform),
                armature_bind_transform: transform_array(cluster, "TransformAssociateModel"),
            });
        }
    }

    let mut bind_pose = Vec::new();
    // Walk poses in id order. The dedup below is first-wins, so hash order
    // would decide which `Pose` supplies a node's matrix when a file has more
    // than one, and two reads of the same bytes could disagree.
    let mut pose_ids: Vec<i64> = poses.keys().copied().collect();
    pose_ids.sort_unstable();
    for pose in pose_ids.iter().map(|id| poses[id]) {
        let is_bind_pose = pose
            .children
            .iter()
            .find(|child| child.name == "Type")
            .and_then(|child| child.properties.first())
            .and_then(|value| match value {
                FbxProperty::String(value) => Some(value == "BindPose"),
                _ => None,
            })
            .unwrap_or(false);
        if !is_bind_pose {
            continue;
        }
        for pose_node in &pose.children {
            if pose_node.name != "PoseNode" {
                continue;
            }
            let model_id = pose_node
                .children
                .iter()
                .find(|child| child.name == "Node")
                .and_then(|child| child.properties.first())
                // Through `object_id`, because ASCII does not record an
                // integer's width: an id that fits in 32 bits comes back as an
                // `I32` there and the whole bind pose was dropped. Authored
                // exports use ids far above that range, so only a document
                // with small ids -- this crate's own output -- showed it.
                .and_then(object_id);
            let matrix = transform_array(pose_node, "Matrix");
            if let (Some(_model_id), Some(matrix), Some(&node_id)) = (
                model_id,
                matrix,
                model_id.and_then(|id| model_node_ids.get(&id)),
            ) {
                if !bind_pose.iter().any(|(existing, _)| *existing == node_id) {
                    bind_pose.push((node_id, matrix));
                }
            }
        }
    }
    Some(crate::fbx_scene::FbxSkin {
        clusters,
        bind_pose,
    })
}

fn child_f64(node: &FbxNode, name: &str) -> Option<f64> {
    node.children
        .iter()
        .find(|child| child.name == name)
        .and_then(|child| child.properties.first())
        .and_then(|value| match value {
            FbxProperty::F64(value) => Some(*value),
            FbxProperty::F32(value) => Some(*value as f64),
            // ASCII writes a whole-valued double without a decimal point, so a
            // `DeformPercent: 100` arrives as an integer and would otherwise
            // read as a missing weight.
            FbxProperty::I32(value) => Some(f64::from(*value)),
            FbxProperty::I64(value) => Some(*value as f64),
            _ => None,
        })
}

fn parse_morph_targets_for_geometry(
    geometry_id: i64,
    geometries: &std::collections::HashMap<i64, &FbxNode>,
    deformers: &std::collections::HashMap<i64, &FbxNode>,
    connections: &[FbxConnection],
) -> Vec<crate::fbx_scene::FbxMorphTarget> {
    let mut targets = Vec::new();
    for blend_shape_id in connections
        .iter()
        .filter(|connection| {
            connection.kind == ConnectionKind::Oo && connection.parent == geometry_id
        })
        .map(|connection| connection.child)
    {
        let Some(blend_shape) = deformers.get(&blend_shape_id) else {
            continue;
        };
        if deformer_type(blend_shape) != Some("BlendShape") {
            continue;
        }
        for channel_id in connections
            .iter()
            .filter(|connection| {
                connection.kind == ConnectionKind::Oo && connection.parent == blend_shape_id
            })
            .map(|connection| connection.child)
        {
            let Some(channel) = deformers.get(&channel_id) else {
                continue;
            };
            if deformer_type(channel) != Some("BlendShapeChannel") {
                continue;
            }
            for shape_id in connections
                .iter()
                .filter(|connection| {
                    connection.kind == ConnectionKind::Oo && connection.parent == channel_id
                })
                .map(|connection| connection.child)
            {
                let Some(shape) = geometries.get(&shape_id) else {
                    continue;
                };
                let indices = child_i32_array(shape, "Indexes")
                    .into_iter()
                    .filter_map(|index| u32::try_from(index).ok())
                    .collect::<Vec<_>>();
                let vertices = child_f64_array(shape, "Vertices");
                if vertices.len() != indices.len() * 3 {
                    continue;
                }
                let position_deltas = vertices
                    .chunks_exact(3)
                    .map(|values| [values[0] as f32, values[1] as f32, values[2] as f32])
                    .collect();
                let full_weight = child_f64_array(channel, "FullWeights")
                    .first()
                    .copied()
                    .unwrap_or(100.0) as f32;
                targets.push(crate::fbx_scene::FbxMorphTarget {
                    name: match shape.properties.get(1) {
                        Some(FbxProperty::String(name)) => {
                            name.split('\0').next().map(str::to_string)
                        }
                        _ => None,
                    },
                    control_point_indices: indices,
                    position_deltas,
                    normal_deltas: None,
                    default_weight: child_f64(channel, "DeformPercent").unwrap_or(0.0) as f32,
                    full_weight,
                });
            }
        }
    }
    targets
}

/// Resolve BlendShapeChannel object ids to their owning Model and target slot.
/// FBX animation curves target the channel deformer rather than the mesh
/// model, so this bridge is required to expose them through the scene API.
fn morph_animation_targets(
    geometries: &std::collections::HashMap<i64, &FbxNode>,
    deformers: &std::collections::HashMap<i64, &FbxNode>,
    connections: &[FbxConnection],
    models: &std::collections::HashMap<i64, &FbxNode>,
) -> std::collections::HashMap<i64, (i64, u32)> {
    let mut result = std::collections::HashMap::new();
    for geometry_id in geometries.keys().copied() {
        let Some(model_id) = connections.iter().find_map(|connection| {
            (connection.kind == ConnectionKind::Oo
                && connection.child == geometry_id
                && models.contains_key(&connection.parent))
            .then_some(connection.parent)
        }) else {
            continue;
        };
        for blend_shape_id in connections
            .iter()
            .filter(|connection| {
                connection.kind == ConnectionKind::Oo
                    && connection.parent == geometry_id
                    && deformers
                        .get(&connection.child)
                        .and_then(|node| deformer_type(node))
                        == Some("BlendShape")
            })
            .map(|connection| connection.child)
        {
            for (index, channel_id) in connections
                .iter()
                .filter(|connection| {
                    connection.kind == ConnectionKind::Oo
                        && connection.parent == blend_shape_id
                        && deformers
                            .get(&connection.child)
                            .and_then(|node| deformer_type(node))
                            == Some("BlendShapeChannel")
                })
                .map(|connection| connection.child)
                .enumerate()
            {
                result.insert(channel_id, (model_id, index as u32));
            }
        }
    }
    result
}

/// FBX object-to-object connection type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConnectionKind {
    /// `OO` object-to-object connection.
    Oo,
    /// `OP` object-to-property connection (carries a property name).
    Op,
}

/// Every `Objects` entry indexed by id, plus the `Connections` graph.
///
/// Built once per document. The maps are for lookup only: iterating a
/// `HashMap` would make node ids, root order and channel order depend on the
/// process rather than the file, so anything order-sensitive walks
/// [`Self::model_order`] or a sorted key list instead.
struct FbxObjectIndex<'a> {
    model_map: HashMap<i64, &'a FbxNode>,
    /// Authored `Model` order, which `model_map` cannot preserve.
    model_order: Vec<i64>,
    geometry_map: HashMap<i64, &'a FbxNode>,
    material_map: HashMap<i64, &'a FbxNode>,
    texture_map: HashMap<i64, &'a FbxNode>,
    video_map: HashMap<i64, &'a FbxNode>,
    astack_map: HashMap<i64, &'a FbxNode>,
    alayer_map: HashMap<i64, &'a FbxNode>,
    acnode_map: HashMap<i64, &'a FbxNode>,
    acurve_map: HashMap<i64, &'a FbxNode>,
    deformer_map: HashMap<i64, &'a FbxNode>,
    pose_map: HashMap<i64, &'a FbxNode>,
    attribute_map: HashMap<i64, &'a FbxNode>,
    connections: Vec<FbxConnection>,
    /// `Objects` children skipped because they are keyed by name, not by id.
    ///
    /// FBX 6100 and earlier identify objects by a name string ending in a
    /// class marker, and connect them by that string rather than by the `i64`
    /// id 7.x uses. Nothing in this index can hold them, so counting them is
    /// how the reader notices it decoded a document it does not understand.
    name_keyed_objects: usize,
    /// Class defaults the document states once, in `Definitions`.
    templates: PropertyTemplates<'a>,
}

impl<'a> FbxObjectIndex<'a> {
    fn build(nodes: &'a [FbxNode]) -> Self {
        let mut index = Self {
            model_map: HashMap::new(),
            model_order: Vec::new(),
            geometry_map: HashMap::new(),
            material_map: HashMap::new(),
            texture_map: HashMap::new(),
            video_map: HashMap::new(),
            astack_map: HashMap::new(),
            alayer_map: HashMap::new(),
            acnode_map: HashMap::new(),
            acurve_map: HashMap::new(),
            deformer_map: HashMap::new(),
            pose_map: HashMap::new(),
            attribute_map: HashMap::new(),
            connections: Vec::new(),
            name_keyed_objects: 0,
            templates: PropertyTemplates::build(nodes),
        };

        for node in nodes {
            if node.name == "Objects" {
                for child in &node.children {
                    let Some(id) = child.properties.first().and_then(object_id) else {
                        if matches!(child.properties.first(), Some(FbxProperty::String(_))) {
                            index.name_keyed_objects += 1;
                        }
                        continue;
                    };
                    let id = &id;
                    match child.name.as_str() {
                        "Model" => {
                            // Keep the authored order only for ids seen first.
                            let first_occurrence = index.model_map.insert(*id, child).is_none();
                            if first_occurrence {
                                index.model_order.push(*id);
                            }
                        }
                        "Geometry" => drop(index.geometry_map.insert(*id, child)),
                        "Material" => drop(index.material_map.insert(*id, child)),
                        "Texture" => drop(index.texture_map.insert(*id, child)),
                        "Video" => drop(index.video_map.insert(*id, child)),
                        "AnimationStack" => drop(index.astack_map.insert(*id, child)),
                        "AnimationLayer" => drop(index.alayer_map.insert(*id, child)),
                        "AnimationCurveNode" => drop(index.acnode_map.insert(*id, child)),
                        "AnimationCurve" => drop(index.acurve_map.insert(*id, child)),
                        "Pose" => drop(index.pose_map.insert(*id, child)),
                        "NodeAttribute" => drop(index.attribute_map.insert(*id, child)),
                        "Deformer" => drop(index.deformer_map.insert(*id, child)),
                        _ => {}
                    }
                }
            } else if node.name == "Connections" {
                index
                    .connections
                    .extend(node.children.iter().filter_map(FbxConnection::from_node));
            }
        }
        index
    }
}

/// Reads a float array, whatever precision it was stored at.
///
/// The binary container tags single and double precision separately, but ASCII
/// writes a bare number and cannot. A consumer that matched only one width
/// found nothing in an ASCII document, which is how animation curves came back
/// empty from files whose objects and connections had parsed perfectly.
fn float_array(property: &FbxProperty) -> Option<Vec<f32>> {
    match property {
        FbxProperty::F32Array(values) => Some(values.clone()),
        FbxProperty::F64Array(values) => Some(values.iter().map(|v| *v as f32).collect()),
        _ => None,
    }
}

/// Reads an FBX object id, whatever width it was stored at.
///
/// The binary container always writes these as `i64`. ASCII writes a bare
/// number, so an id small enough to fit in `i32` arrives as one -- matching
/// only `I64` skipped every object in such a document, and the scene came back
/// empty with nothing to explain it.
fn object_id(property: &FbxProperty) -> Option<i64> {
    match property {
        FbxProperty::I64(value) => Some(*value),
        FbxProperty::I32(value) => Some(i64::from(*value)),
        _ => None,
    }
}

/// A parsed FBX connection entry.
#[derive(Debug, Clone)]
struct FbxConnection {
    kind: ConnectionKind,
    child: i64,
    parent: i64,
    property: Option<String>,
}

impl FbxConnection {
    /// Parses one `C` entry, skipping relation codes this reader ignores.
    fn from_node(node: &FbxNode) -> Option<Self> {
        let kind = match node.properties.first() {
            Some(FbxProperty::String(code)) if code == "OO" => ConnectionKind::Oo,
            Some(FbxProperty::String(code)) if code == "OP" => ConnectionKind::Op,
            _ => return None,
        };
        let child = node.properties.get(1).and_then(object_id)?;
        let parent = node.properties.get(2).and_then(object_id)?;
        let property = match node.properties.get(3) {
            Some(FbxProperty::String(name)) => Some(name.clone()),
            _ => None,
        };
        Some(Self {
            kind,
            child,
            parent,
            property,
        })
    }
}

/// Decodes every `Material` and `Texture` object, resolving each material's
/// texture bindings to indices into the returned texture list.
///
/// Both lists are ordered by FBX object id rather than hash order, so a
/// document always decodes to the same material and texture indices.
fn parse_materials_and_textures<'a>(
    material_map: &HashMap<i64, &'a FbxNode>,
    texture_map: &HashMap<i64, &FbxNode>,
    video_map: &HashMap<i64, &FbxNode>,
    connections: &[FbxConnection],
    templates: &PropertyTemplates<'a>,
) -> (
    Vec<crate::fbx_scene::FbxMaterial>,
    HashMap<i64, usize>,
    Vec<crate::fbx_scene::FbxTexture>,
) {
    let mut materials: Vec<crate::fbx_scene::FbxMaterial> = Vec::new();
    let mut material_index_by_id: HashMap<i64, usize> = HashMap::new();
    let mut material_ids: Vec<i64> = material_map.keys().copied().collect();
    material_ids.sort_unstable();
    for id in material_ids {
        let mut material = parse_material(ObjectProperties::new(material_map[&id], templates));
        material.textures = collect_material_texture_bindings(id, texture_map, connections);
        material_index_by_id.insert(id, materials.len());
        materials.push(material);
    }

    // Map each Texture to the Video that carries its bytes. FBX writes the
    // connection in either direction, so accept both.
    let mut texture_video: HashMap<i64, i64> = HashMap::new();
    for conn in connections {
        if conn.kind != ConnectionKind::Oo {
            continue;
        }
        if texture_map.contains_key(&conn.child) && video_map.contains_key(&conn.parent) {
            texture_video.entry(conn.child).or_insert(conn.parent);
        }
        if video_map.contains_key(&conn.child) && texture_map.contains_key(&conn.parent) {
            texture_video.entry(conn.parent).or_insert(conn.child);
        }
    }

    let mut textures: Vec<crate::fbx_scene::FbxTexture> = Vec::new();
    let mut texture_index_by_id: HashMap<i64, usize> = HashMap::new();
    let mut texture_ids: Vec<i64> = texture_map.keys().copied().collect();
    texture_ids.sort_unstable();
    for id in texture_ids {
        let mut texture = parse_texture(texture_map[&id]);
        if let Some(video) = texture_video.get(&id).and_then(|id| video_map.get(id)) {
            let from_video = parse_texture(video);
            texture.content = texture.content.or(from_video.content);
            texture.filename = texture.filename.or(from_video.filename);
            texture.name = texture.name.or(from_video.name);
        }
        texture_index_by_id.insert(id, textures.len());
        textures.push(texture);
    }

    // Bindings carry FBX texture ids until now; rewrite them as scene indices.
    for material in &mut materials {
        for binding in &mut material.textures {
            let fbx_id = binding.texture_index as i64;
            if let Some(&resolved) = texture_index_by_id.get(&fbx_id) {
                binding.texture_index = resolved;
            }
        }
    }

    (materials, material_index_by_id, textures)
}

/// FBX Deformer objects carry their effective kind in the third object
/// property; the second name component is merely `Deformer`/`SubDeformer`.
fn deformer_type(node: &FbxNode) -> Option<&str> {
    match node.properties.get(2) {
        Some(FbxProperty::String(value)) if !value.is_empty() => Some(value.as_str()),
        _ => None,
    }
}

/// Collects material property texture bindings as placeholders; the FBX
/// texture id is stored in `texture_index` and resolved to a scene index by
/// the caller after the texture list is finalized.
fn collect_material_texture_bindings(
    material_id: i64,
    texture_map: &std::collections::HashMap<i64, &FbxNode>,
    connections: &[FbxConnection],
) -> Vec<crate::fbx_scene::FbxTextureBinding> {
    let mut bindings = Vec::new();
    for conn in connections {
        if conn.kind != ConnectionKind::Op || conn.parent != material_id {
            continue;
        }
        let Some(slot_name) = conn.property.as_deref() else {
            continue;
        };
        let Some(slot) = crate::fbx_scene::FbxTextureSlot::from_property_name(slot_name) else {
            continue;
        };
        if !texture_map.contains_key(&conn.child) {
            continue;
        }
        bindings.push(crate::fbx_scene::FbxTextureBinding {
            slot,
            texture_index: conn.child as usize,
        });
    }
    bindings
}

/// Resolves each Model's `NodeAttribute`, keeping the classes this crate
/// represents and reporting the rest.
///
/// Attributes are attached to their Model by an ordinary object connection, so
/// this walks the connection list once rather than searching per node. Ids are
/// visited in sorted order so a document always produces the same warnings in
/// the same order.
fn parse_node_attributes<'a>(
    attribute_map: &HashMap<i64, &'a FbxNode>,
    model_map: &HashMap<i64, &FbxNode>,
    connections: &[FbxConnection],
    templates: &PropertyTemplates<'a>,
    warnings: &mut Vec<FbxWarning>,
) -> HashMap<i64, FbxNodeAttribute> {
    let mut by_model: Vec<(i64, i64)> = connections
        .iter()
        .filter(|conn| {
            attribute_map.contains_key(&conn.child) && model_map.contains_key(&conn.parent)
        })
        .map(|conn| (conn.parent, conn.child))
        .collect();
    by_model.sort_unstable();

    let mut resolved = HashMap::new();
    for (model_id, attribute_id) in by_model {
        let node = attribute_map[&attribute_id];
        let class = match node.properties.get(2) {
            Some(FbxProperty::String(class)) => class.as_str(),
            _ => continue,
        };
        match class {
            "Camera" => {
                let properties = ObjectProperties::new(node, templates);
                resolved.insert(model_id, FbxNodeAttribute::Camera(parse_camera(properties)));
            }
            "Light" => {
                let properties = ObjectProperties::new(node, templates);
                resolved.insert(model_id, FbxNodeAttribute::Light(parse_light(properties)));
            }
            // A skeleton attribute is consumed by the skin path and a `Null`
            // carries nothing but a transform, so neither is a loss worth
            // reporting. The rest describe something the scene will not have.
            "LimbNode" | "Limb" | "Null" | "Root" => {}
            other => push_warning(
                warnings,
                FbxWarningCode::DroppedNodeAttribute,
                format!(
                    "FBX NodeAttribute of class {other} is not represented, so its properties \
                     are absent from the scene"
                ),
                Some(other),
            ),
        }
    }
    resolved
}

fn parse_camera(properties: ObjectProperties<'_>) -> crate::fbx_scene::FbxCamera {
    let scalar = |name: &str| properties.get(name).and_then(property_scalar);
    let vector = |name: &str| properties.get(name).and_then(property_vec3);
    crate::fbx_scene::FbxCamera {
        position: vector("Position"),
        interest_position: vector("InterestPosition"),
        up_vector: vector("UpVector"),
        projection_type: scalar("CameraProjectionType").map(|v| v as i32),
        field_of_view: scalar("FieldOfView"),
        field_of_view_x: scalar("FieldOfViewX"),
        field_of_view_y: scalar("FieldOfViewY"),
        focal_length: scalar("FocalLength"),
        near_plane: scalar("NearPlane"),
        far_plane: scalar("FarPlane"),
        aspect_width: scalar("AspectWidth"),
        aspect_height: scalar("AspectHeight"),
        film_width: scalar("FilmWidth"),
        film_height: scalar("FilmHeight"),
        film_aspect_ratio: scalar("FilmAspectRatio"),
        aperture_mode: scalar("ApertureMode").map(|v| v as i32),
        ortho_zoom: scalar("OrthoZoom"),
    }
}

fn parse_light(properties: ObjectProperties<'_>) -> crate::fbx_scene::FbxLight {
    let scalar = |name: &str| properties.get(name).and_then(property_scalar);
    crate::fbx_scene::FbxLight {
        light_type: scalar("LightType").map(|v| v as i32),
        color: properties.get("Color").and_then(property_vec3),
        intensity: scalar("Intensity"),
        cast_light: scalar("CastLight").map(|v| v != 0.0),
        cast_shadows: scalar("CastShadows").map(|v| v != 0.0),
        decay_type: scalar("DecayType").map(|v| v as i32),
        decay_start: scalar("DecayStart"),
    }
}

fn property_scalar(prop: &FbxNode) -> Option<f32> {
    // Properties70 P node layout: [name, type, subtype, flags, value(s)...]
    // Scalar properties start at index 4.
    for value in prop.properties.iter().skip(4) {
        match value {
            FbxProperty::F64(v) => return Some(*v as f32),
            FbxProperty::F32(v) => return Some(*v),
            FbxProperty::I32(v) => return Some(*v as f32),
            FbxProperty::I64(v) => return Some(*v as f32),
            _ => {}
        }
    }
    None
}

fn property_vec3(prop: &FbxNode) -> Option<[f32; 3]> {
    let values: Vec<f32> = prop
        .properties
        .iter()
        .skip(4)
        .filter_map(|value| match value {
            FbxProperty::F64(v) => Some(*v as f32),
            FbxProperty::F32(v) => Some(*v),
            _ => None,
        })
        .take(3)
        .collect();
    (values.len() == 3).then(|| [values[0], values[1], values[2]])
}

fn parse_material(properties: ObjectProperties<'_>) -> crate::fbx_scene::FbxMaterial {
    let name = match properties.node().properties.get(1) {
        Some(FbxProperty::String(raw)) => raw
            .split('\0')
            .next()
            .filter(|s| !s.is_empty())
            .map(str::to_string),
        _ => None,
    };
    let shading_model = read_shading_model(properties);

    let get_color = |name: &str| properties.get(name).and_then(property_vec3);
    let get_scalar = |name: &str| properties.get(name).and_then(property_scalar);

    crate::fbx_scene::FbxMaterial {
        name,
        shading_model,
        diffuse: get_color("DiffuseColor"),
        specular: get_color("SpecularColor"),
        emissive: get_color("EmissiveColor"),
        ambient: get_color("AmbientColor"),
        diffuse_factor: get_scalar("DiffuseFactor"),
        specular_factor: get_scalar("SpecularFactor"),
        shininess: get_scalar("Shininess"),
        emissive_factor: get_scalar("EmissiveFactor"),
        reflection_factor: get_scalar("ReflectionFactor"),
        transparency_factor: get_scalar("TransparencyFactor"),
        opacity: get_scalar("Opacity"),
        bump_factor: get_scalar("BumpFactor"),
        textures: Vec::new(),
    }
}

/// Reads `ShadingModel`, which a document may state in any of four places.
///
/// In order, because they disagree: a `Properties70` entry on the material, a
/// `ShadingModel` node beside `Properties70`, the class template, and finally
/// the object record's own class string.
///
/// The middle two are what make the order matter. Maya writes the material's
/// real model -- `lambert`, `phong`, `unknown`, differing per material -- as
/// the sibling node, and 174 of the 188 materials in this crate's corpus get
/// theirs only from the template. Consulting the template before the sibling
/// would relabel every one of those Maya materials with the template's single
/// class default, which is how a rewrite turned a `phong` material into a
/// `Lambert` one.
fn read_shading_model(properties: ObjectProperties<'_>) -> Option<String> {
    let object = properties.node();
    let from_own_properties = properties
        .node()
        .children
        .iter()
        .filter(|child| child.name == "Properties70")
        .find_map(|block| crate::fbx_templates::find_property(block, "ShadingModel"))
        .and_then(string_value);
    let from_sibling_node = object
        .children
        .iter()
        .find(|child| child.name == "ShadingModel")
        .and_then(|child| match child.properties.first() {
            Some(FbxProperty::String(model)) if !model.is_empty() => Some(model.clone()),
            _ => None,
        });
    let from_template = properties
        .template()
        .and_then(|block| crate::fbx_templates::find_property(block, "ShadingModel"))
        .and_then(string_value);
    let from_class = match object.properties.get(2) {
        Some(FbxProperty::String(raw)) if !raw.is_empty() => Some(raw.clone()),
        _ => None,
    };

    from_own_properties
        .or(from_sibling_node)
        .or(from_template)
        .or(from_class)
}

/// The first string value of a `P` record, past its four name and type fields.
fn string_value(property: &FbxNode) -> Option<String> {
    property
        .properties
        .iter()
        .skip(4)
        .find_map(|value| match value {
            FbxProperty::String(text) => Some(text.clone()),
            _ => None,
        })
}

fn parse_texture(node: &FbxNode) -> crate::fbx_scene::FbxTexture {
    let name = match node.properties.get(1) {
        Some(FbxProperty::String(raw)) => raw
            .split('\0')
            .next()
            .filter(|s| !s.is_empty())
            .map(str::to_string),
        _ => None,
    };
    let mut filename = None;
    let mut content = None;
    for child in &node.children {
        match child.name.as_str() {
            "RelativeFilename" | "FileName" | "Filename" if filename.is_none() => {
                if let Some(FbxProperty::String(s)) = child.properties.first() {
                    if !s.is_empty() {
                        filename = Some(s.clone());
                    }
                }
            }
            "Content" => {
                if let Some(FbxProperty::Raw(bytes)) = child.properties.first() {
                    if !bytes.is_empty() {
                        content = Some(bytes.clone());
                    }
                }
            }
            _ => {}
        }
    }
    crate::fbx_scene::FbxTexture {
        name,
        content,
        filename,
    }
}
impl<R: Read + Seek> FbxReader<R> {
    /// Read meshes from the FBX file.
    pub fn read_meshes(&mut self) -> io::Result<Vec<Mesh>> {
        let nodes = self.read_nodes()?;
        let mut meshes = Vec::new();
        // Collected separately because `geometry_to_mesh` borrows `self`
        // immutably; merged back afterwards so this path reports the same
        // geometry notices `read_scene` does.
        let mut warnings = Vec::new();

        // Find Objects node
        for node in &nodes {
            if node.name == "Objects" {
                for child in &node.children {
                    if child.name == "Geometry" {
                        if let Some(source) = geometry_to_mesh(child, &mut warnings)? {
                            meshes.push(source.mesh);
                        }
                    }
                }
            }
        }

        self.extend_warnings(warnings);
        Ok(meshes)
    }
}

/// The `LayerElement*` children of one geometry node, bucketed by family.
///
/// Collecting them before parsing keeps the dispatch over node names -- which
/// has to be exhaustive so an unknown family raises a warning rather than
/// vanishing -- separate from the per-family decoding.
#[derive(Default)]
struct RawLayerNodes<'a> {
    normals: Vec<&'a FbxNode>,
    uvs: Vec<&'a FbxNode>,
    colors: Vec<&'a FbxNode>,
    tangents: Vec<&'a FbxNode>,
    binormals: Vec<&'a FbxNode>,
    smoothing: Vec<&'a FbxNode>,
    creases: Vec<(FbxCreaseKind, &'a FbxNode)>,
    material: Option<&'a FbxNode>,
}

/// The element counts a non-corner layer's length has to agree with.
#[derive(Clone, Copy)]
struct LayerDomains {
    edges: Option<usize>,
    polygons: usize,
    control_points: usize,
}

impl LayerDomains {
    /// Resolves what a mapping name claims about a layer's length.
    ///
    /// `ByEdge` with no `Edges` array is deliberately unverifiable rather than
    /// wrong: FBX does not require the array, and the layer then addresses the
    /// edges an importer would reconstruct from the faces. This crate does not
    /// reconstruct them, so it cannot check the length -- but it must not
    /// destroy the data either, since preserving it verbatim is what makes a
    /// rewrite lossless.
    fn check(self, mapping: Option<&str>) -> DomainCheck {
        match mapping {
            Some("ByEdge") => match self.edges {
                Some(count) => DomainCheck::Expect(count),
                None => DomainCheck::Unverifiable,
            },
            Some("ByPolygon") => DomainCheck::Expect(self.polygons),
            Some("ByVertice") | Some("ByVertex") | Some("ByControlPoint") => {
                DomainCheck::Expect(self.control_points)
            }
            _ => DomainCheck::Unknown,
        }
    }
}

/// Convert a Geometry node to a Mesh, plus per-triangle material indices.
///
/// The returned `material_indices` align with the fan-triangulated face
/// order of the Draco `Mesh` (one entry per triangle). The list is empty
/// when the geometry does not carry a `LayerElementMaterial` layer.
fn geometry_to_mesh(
    geometry: &FbxNode,
    warnings: &mut Vec<FbxWarning>,
) -> io::Result<Option<FbxGeometrySource>> {
    let mut vertices: Option<Vec<f64>> = None;
    let mut polygon_indices: Option<Vec<i32>> = None;
    let mut edges: Vec<i32> = Vec::new();
    let mut raw = RawLayerNodes::default();

    for child in &geometry.children {
        match child.name.as_str() {
            "Vertices" => {
                if let Some(FbxProperty::F64Array(arr)) = child.properties.first() {
                    vertices = Some(arr.clone());
                }
            }
            "Edges" => {
                if let Some(FbxProperty::I32Array(arr)) = child.properties.first() {
                    edges = arr.clone();
                }
            }
            "PolygonVertexIndex" => {
                if let Some(FbxProperty::I32Array(arr)) = child.properties.first() {
                    polygon_indices = Some(arr.clone());
                }
            }
            "LayerElementNormal" => raw.normals.push(child),
            "LayerElementColor" => raw.colors.push(child),
            "LayerElementUV" => raw.uvs.push(child),
            "LayerElementTangent" => raw.tangents.push(child),
            "LayerElementBinormal" => raw.binormals.push(child),
            "LayerElementSmoothing" => raw.smoothing.push(child),
            "LayerElementEdgeCrease" => raw.creases.push((FbxCreaseKind::Edge, child)),
            "LayerElementVertexCrease" => raw.creases.push((FbxCreaseKind::Vertex, child)),
            "LayerElementMaterial" if raw.material.is_none() => {
                raw.material = Some(child);
            }
            // Any layer family this crate does not import lands here. They
            // used to vanish without a trace; naming them makes the gap
            // visible to a caller instead of only to the source code.
            other if other.starts_with("LayerElement") => push_warning(
                warnings,
                FbxWarningCode::DroppedLayerElement,
                format!("FBX {other} is not imported, so its data is absent from the scene"),
                Some(other),
            ),
            _ => {}
        }
    }

    let vertices = match vertices {
        Some(v) => v,
        None => return Ok(None),
    };
    let polygon_indices = match polygon_indices {
        Some(p) => p,
        None => return Ok(None),
    };

    let control_points = vertices
        .chunks_exact(3)
        .map(|value| [value[0] as f32, value[1] as f32, value[2] as f32])
        .collect::<Vec<_>>();

    // Track the polygon each fan triangle came from, so `ByPolygon`
    // material indices can be remapped onto triangle order.
    let mut tri_polygon_index: Vec<usize> = Vec::new();
    let mut polygon_count = 0usize;
    let mut corners_in_polygon = 0usize;
    for &idx in &polygon_indices {
        corners_in_polygon += 1;
        if idx < 0 {
            for _ in 0..corners_in_polygon.saturating_sub(2) {
                tri_polygon_index.push(polygon_count);
            }
            corners_in_polygon = 0;
            polygon_count += 1;
        }
    }

    // Per-triangle material indices.
    let material_indices = raw
        .material
        .and_then(|layer| {
            let mapping = layer_string(layer, "MappingInformationType");
            let reference = layer_string(layer, "ReferenceInformationType");
            let data = layer_int_array(layer, "Materials");
            expand_material_indices(
                mapping.as_deref(),
                reference.as_deref(),
                data.as_deref(),
                polygon_count,
                &tri_polygon_index,
            )
        })
        .unwrap_or_default();

    let domains = LayerDomains {
        edges: (!edges.is_empty()).then_some(edges.len()),
        polygons: polygon_count,
        control_points: control_points.len(),
    };
    let layers = parse_geometry_layers(raw, domains, warnings);

    // Build the Draco mesh on the polygon-corner domain. Resolving layer
    // elements onto control points cannot represent a UV or hard-normal
    // seam, and silently averaged them away.
    let render = crate::fbx_render_mesh::expand_to_render_mesh(
        crate::fbx_render_mesh::FbxGeometryLayers::new(&control_points, &polygon_indices, &layers),
    );
    let mesh = crate::fbx_render_mesh::build_draco_mesh(&render);

    Ok(Some(FbxGeometrySource {
        mesh,
        material_indices,
        control_points,
        polygon_vertex_indices: polygon_indices,
        layers,
        edges,
    }))
}

/// Decodes each layer-element family into the form the scene retains.
fn parse_geometry_layers(
    raw: RawLayerNodes<'_>,
    domains: LayerDomains,
    warnings: &mut Vec<FbxWarning>,
) -> FbxMeshLayers {
    let uv_sets: Vec<FbxUvSet> = raw
        .uvs
        .into_iter()
        .filter_map(|layer| {
            let values = chunk_layer_values(&read_layer_floats(layer, "UV")?);
            Some(layer_set(layer, values, &["UVIndex"]))
        })
        .collect();
    let normal_sets: Vec<FbxNormalSet> = raw
        .normals
        .into_iter()
        .filter_map(|layer| {
            let values = chunk_layer_values(&read_layer_floats(layer, "Normals")?);
            // Exporters disagree on the index node's name.
            Some(layer_set(layer, values, &["NormalsIndex", "NormalIndex"]))
        })
        .collect();
    for set in &uv_sets {
        warn_unsupported_layer_mapping("LayerElementUV", set, warnings);
    }
    for set in &normal_sets {
        warn_unsupported_layer_mapping("LayerElementNormal", set, warnings);
    }
    let color_sets: Vec<FbxColorSet> = raw
        .colors
        .into_iter()
        .filter_map(|layer| {
            let floats = read_layer_floats(layer, "Colors")?;
            // FBX writes RGBA here, but a three-component source is legal
            // in the wild; pad it opaque rather than dropping the layer.
            let values = if floats.len() % 4 == 0 {
                chunk_layer_values(&floats)
            } else {
                floats
                    .chunks_exact(3)
                    .map(|value| [value[0], value[1], value[2], 1.0])
                    .collect()
            };
            Some(layer_set(layer, values, &["ColorIndex"]))
        })
        .collect();
    for set in &color_sets {
        warn_unsupported_layer_mapping("LayerElementColor", set, warnings);
    }
    let tangent_sets: Vec<FbxTangentSet> = raw
        .tangents
        .into_iter()
        .filter_map(|layer| parse_tangent_like(layer, "Tangents", "TangentsW", "TangentIndex"))
        .collect();
    let binormal_sets: Vec<FbxBinormalSet> = raw
        .binormals
        .into_iter()
        .filter_map(|layer| parse_tangent_like(layer, "Binormals", "BinormalsW", "BinormalIndex"))
        .collect();
    for set in &tangent_sets {
        warn_unsupported_layer_mapping("LayerElementTangent", &set.layer, warnings);
    }
    for set in &binormal_sets {
        warn_unsupported_layer_mapping("LayerElementBinormal", &set.layer, warnings);
    }

    // Smoothing and crease layers address edges, polygons or control points --
    // never polygon corners -- so they are kept raw beside `edges` rather than
    // resolved onto the render mesh. A layer whose length disagrees with the
    // domain its mapping names is misaligned data, and keeping it would
    // silently sharpen the wrong edges.
    let mut smoothing_layers = Vec::new();
    for layer in raw.smoothing {
        let mapping = layer_string(layer, "MappingInformationType");
        let Some(values) = layer_int_array(layer, "Smoothing") else {
            continue;
        };
        if domains.check(mapping.as_deref()).accepts(values.len()) {
            smoothing_layers.push(FbxSmoothingLayer { mapping, values });
        } else {
            warn_misaligned_layer(
                "LayerElementSmoothing",
                mapping.as_deref(),
                values.len(),
                warnings,
            );
        }
    }
    let mut crease_layers = Vec::new();
    for (kind, layer) in raw.creases {
        let element = match kind {
            FbxCreaseKind::Edge => "LayerElementEdgeCrease",
            FbxCreaseKind::Vertex => "LayerElementVertexCrease",
        };
        let mapping = layer_string(layer, "MappingInformationType");
        let Some(values) = layer_f64_array(layer, element.trim_start_matches("LayerElement"))
        else {
            continue;
        };
        match domains.check(mapping.as_deref()) {
            domain if domain.accepts(values.len()) => {
                crease_layers.push(FbxCreaseLayer {
                    kind,
                    mapping,
                    values,
                });
            }
            _ => warn_misaligned_layer(element, mapping.as_deref(), values.len(), warnings),
        }
    }

    FbxMeshLayers {
        uv_sets,
        normal_sets,
        color_sets,
        tangent_sets,
        binormal_sets,
        smoothing_layers,
        crease_layers,
    }
}

impl<R: Read + Seek> FbxReader<R> {
    /// Flatten the FBX animation graph into one [`FbxAnimation`] per
    /// `AnimationStack` + first connected `AnimationLayer`.
    fn parse_animations(
        &self,
        nodes: &[FbxNode],
        index: &FbxObjectIndex<'_>,
        model_name_map: &HashMap<i64, String>,
        model_node_ids: &HashMap<i64, FbxNodeId>,
        morph_targets: &HashMap<i64, (i64, u32)>,
    ) -> Vec<FbxAnimation> {
        let FbxObjectIndex {
            connections,
            astack_map,
            alayer_map,
            acnode_map,
            acurve_map,
            model_map,
            ..
        } = index;
        let fbx_ktime = fbx_ktime_for(nodes, self.version());
        // Held as `f64`, and divided as `f64`, even though the sampler stores
        // seconds as `f32`. A tick count is around 2e10 for a one-second key,
        // where one `f32` step is 2048 ticks: narrowing either the count or
        // the divisor before the division quantizes the result to about
        // 4e-8 s, far coarser than the `f32` seconds can hold. Narrowing after
        // it costs nothing.
        let ktime_f = match fbx_ktime {
            0 => 1.0,
            v => v as f64,
        };

        // acnode_id -> (layer_id, model_id, path). The FBX convention (and
        // Blender's io_scene_fbx) wires the AnimationCurveNode as the *child*
        // of an OP connection whose parent is the animated Model, with the
        // animated property name ("Lcl Translation" etc.) as the 4th field.
        let mut acnode_targets: std::collections::HashMap<
            i64,
            (i64, i64, FbxAnimChannelPath, Option<u32>),
        > = std::collections::HashMap::new();
        for conn in connections {
            if conn.kind != ConnectionKind::Op {
                continue;
            }
            if !acnode_map.contains_key(&conn.child) {
                continue;
            }
            let Some(property) = conn.property.as_deref() else {
                continue;
            };
            let Some(path) = FbxAnimChannelPath::from_property_name(property) else {
                continue;
            };
            let (model_id, morph_target_index) = if model_map.contains_key(&conn.parent) {
                (conn.parent, None)
            } else if path == FbxAnimChannelPath::MorphWeight {
                let Some(&(model_id, target_index)) = morph_targets.get(&conn.parent) else {
                    continue;
                };
                (model_id, Some(target_index))
            } else {
                continue;
            };
            // Find the layer that owns this curve node (OO curvenode -> layer).
            let mut layer_id = None;
            for c2 in connections {
                if c2.kind == ConnectionKind::Oo
                    && c2.child == conn.child
                    && alayer_map.contains_key(&c2.parent)
                {
                    layer_id = Some(c2.parent);
                    break;
                }
            }
            if let Some(layer_id) = layer_id {
                acnode_targets.insert(conn.child, (layer_id, model_id, path, morph_target_index));
            }
        }

        // acnode_id -> { component -> (times, values, flags) }
        let mut acnode_curves: std::collections::HashMap<
            i64,
            std::collections::BTreeMap<u32, FbxAnimCurveData>,
        > = std::collections::HashMap::new();
        for conn in connections {
            if conn.kind != ConnectionKind::Op {
                continue;
            }
            if !acurve_map.contains_key(&conn.child) {
                continue;
            }
            if !acnode_targets.contains_key(&conn.parent) {
                continue;
            }
            let component = match conn.property.as_deref() {
                Some("d|X") => 0,
                Some("d|Y") => 1,
                Some("d|Z") => 2,
                _ => continue,
            };
            if let Some(curve) = parse_curve(acurve_map[&conn.child]) {
                acnode_curves
                    .entry(conn.parent)
                    .or_default()
                    .insert(component, curve);
            }
        }

        // Group curve nodes by (stack, layer, model, path).
        //
        // Every iteration below walks ids in sorted order rather than hash
        // order. FBX object ids are stable within a document, so this makes
        // the channel list a property of the file instead of the process --
        // otherwise two reads of the same bytes produce differently ordered
        // channels and any positional comparison comes out garbage.
        let mut stacks_layers: StacksLayers = std::collections::HashMap::new();
        let mut acnode_ids_sorted: Vec<i64> = acnode_targets.keys().copied().collect();
        acnode_ids_sorted.sort_unstable();
        for acnode_id in &acnode_ids_sorted {
            let (layer_id, model_id, path, morph_target_index) = &acnode_targets[acnode_id];
            // Find stacks owning this layer.
            let mut stack_ids = Vec::new();
            for c2 in connections {
                if c2.kind == ConnectionKind::Oo
                    && c2.child == *layer_id
                    && astack_map.contains_key(&c2.parent)
                {
                    stack_ids.push(c2.parent);
                }
            }
            for stack_id in stack_ids {
                stacks_layers
                    .entry(stack_id)
                    .or_default()
                    .entry(*layer_id)
                    .or_default()
                    .push((*acnode_id, *model_id, *path, *morph_target_index));
            }
        }

        let mut animations = Vec::new();
        let mut stack_ids_sorted: Vec<i64> = stacks_layers.keys().copied().collect();
        stack_ids_sorted.sort_unstable();
        for stack_id in stack_ids_sorted {
            let layers = &stacks_layers[&stack_id];
            let stack_node = astack_map.get(&stack_id);
            let name = stack_node.and_then(|n| match n.properties.get(1) {
                Some(FbxProperty::String(raw)) => raw
                    .split('\0')
                    .next()
                    .filter(|s| !s.is_empty())
                    .map(str::to_string),
                _ => None,
            });
            // One clip per layer, which is what Blender's importer does: it
            // "does not mix layers, each layer results in an independent set
            // of actions". Merging them instead produced several channels
            // driving the same node and path, and any consumer applying them
            // in order silently kept only the last.
            let mut layer_ids_sorted: Vec<i64> = layers.keys().copied().collect();
            layer_ids_sorted.sort_unstable();
            let multiple_layers = layer_ids_sorted.len() > 1;
            for (layer_index, layer_id) in layer_ids_sorted.iter().copied().enumerate() {
                let mut channels = Vec::new();
                let mut max_time = 0.0f32;
                let entries = &layers[&layer_id];
                // Group curve nodes by (model, path) before flattening.
                let mut groups: std::collections::HashMap<
                    (i64, FbxAnimChannelPath, Option<u32>),
                    Vec<i64>,
                > = std::collections::HashMap::new();
                for &(acnode_id, model_id, path, morph_target_index) in entries {
                    groups
                        .entry((model_id, path, morph_target_index))
                        .or_default()
                        .push(acnode_id);
                }
                let mut group_keys: Vec<(i64, FbxAnimChannelPath, Option<u32>)> =
                    groups.keys().copied().collect();
                group_keys.sort_unstable_by_key(|(model_id, path, morph_target_index)| {
                    (*model_id, *path as u8, *morph_target_index)
                });
                for (model_id, path, morph_target_index) in group_keys {
                    let acnode_ids = &groups[&(model_id, path, morph_target_index)];
                    // Combine the X/Y/Z curves across all matching curve nodes
                    // (Blender notes that each curve node has a unique set of
                    // channels, so in practice there is exactly one entry).
                    let mut by_component: std::collections::BTreeMap<u32, FbxAnimCurveData> =
                        std::collections::BTreeMap::new();
                    for acnode_id in acnode_ids {
                        if let Some(curves) = acnode_curves.get(acnode_id) {
                            for (component, curve) in curves {
                                by_component
                                    .entry(*component)
                                    .or_insert_with(|| curve.clone());
                            }
                        }
                    }
                    let Some(channel) = flatten_curve(&by_component, path, ktime_f) else {
                        continue;
                    };
                    if let (Some(node_name), Some(&node_id)) =
                        (model_name_map.get(&model_id), model_node_ids.get(&model_id))
                    {
                        max_time =
                            max_time.max(channel.sampler.input.last().copied().unwrap_or(0.0));
                        channels.push(FbxAnimChannel {
                            node_id,
                            node_name: node_name.clone(),
                            path,
                            morph_target_index,
                            sampler: channel.sampler,
                        });
                    }
                }
                if channels.is_empty() {
                    continue;
                }
                // Name extra layers so they stay distinguishable; a
                // single-layer stack keeps the stack name unchanged.
                let clip_name = if multiple_layers {
                    let layer_name = alayer_map
                        .get(&layer_id)
                        .and_then(|node| match node.properties.get(1) {
                            Some(FbxProperty::String(raw)) => raw
                                .split('\0')
                                .next()
                                .filter(|part| !part.is_empty())
                                .map(str::to_string),
                            _ => None,
                        })
                        .unwrap_or_else(|| format!("Layer{layer_index}"));
                    Some(match &name {
                        Some(stack) => format!("{stack}|{layer_name}"),
                        None => layer_name,
                    })
                } else {
                    name.clone()
                };
                animations.push(FbxAnimation {
                    name: clip_name,
                    duration: max_time,
                    channels,
                });
            }
        }
        animations
    }
}

/// Curve nodes grouped by `AnimationStack` id, then by `AnimationLayer` id.
///
/// Each entry is `(curve_node_id, model_id, path, morph_target_index)`.
type StacksLayers = std::collections::HashMap<
    i64,
    std::collections::HashMap<i64, Vec<(i64, i64, FbxAnimChannelPath, Option<u32>)>>,
>;

#[derive(Debug, Clone)]
struct FbxAnimCurveData {
    key_times: Vec<i64>,
    key_values: Vec<f32>,
    key_attr_flags: Vec<i32>,
    in_tangents: Vec<f32>,
    out_tangents: Vec<f32>,
}

fn parse_curve(node: &FbxNode) -> Option<FbxAnimCurveData> {
    let mut key_times = None;
    let mut key_values = None;
    let mut key_attr_flags = None;
    let mut key_attr_data = None;
    let mut key_attr_ref_count = None;
    for child in &node.children {
        match child.name.as_str() {
            "KeyTime" => {
                if let Some(FbxProperty::I64Array(arr)) = child.properties.first() {
                    key_times = Some(arr.clone());
                }
            }
            "KeyValueFloat" => {
                key_values = child.properties.first().and_then(float_array);
            }
            "KeyAttrFlags" => {
                if let Some(FbxProperty::I32Array(arr)) = child.properties.first() {
                    key_attr_flags = Some(arr.clone());
                }
            }
            "KeyAttrDataFloat" => {
                key_attr_data = child.properties.first().and_then(float_array);
            }
            "KeyAttrRefCount" => {
                if let Some(FbxProperty::I32Array(arr)) = child.properties.first() {
                    key_attr_ref_count = Some(arr.clone());
                }
            }
            _ => {}
        }
    }
    let key_times = key_times?;
    let key_values = key_values?;
    if key_times.is_empty() || key_values.len() != key_times.len() {
        return None;
    }
    let mut expanded_flags = Vec::with_capacity(key_times.len());
    let mut expanded_attrs = Vec::with_capacity(key_times.len());
    if let (Some(flags), Some(data), Some(refs)) =
        (key_attr_flags, key_attr_data, key_attr_ref_count)
    {
        if flags.len() == refs.len() && data.len() == refs.len() * 4 {
            for ((flag, count), attrs) in flags.into_iter().zip(refs).zip(data.chunks_exact(4)) {
                for _ in 0..count.max(0) {
                    expanded_flags.push(flag);
                    expanded_attrs.push([attrs[0], attrs[1]]);
                }
            }
        }
    }
    if expanded_flags.len() != key_times.len() {
        expanded_flags = vec![0x4; key_times.len()];
        expanded_attrs = vec![[0.0, 0.0]; key_times.len()];
    }
    let mut in_tangents = vec![0.0; key_times.len()];
    let mut out_tangents = vec![0.0; key_times.len()];
    for (index, attrs) in expanded_attrs.iter().enumerate() {
        out_tangents[index] = attrs[0];
        if index + 1 < in_tangents.len() {
            in_tangents[index + 1] = attrs[1];
        }
    }
    Some(FbxAnimCurveData {
        key_times,
        key_values,
        key_attr_flags: expanded_flags,
        in_tangents,
        out_tangents,
    })
}

/// Combine per-component curves into a single TRS channel sampler.
///
/// Times are taken from the X (component 0) curve when available, then Y, then
/// Z. Missing components default to 0. Interpolation is read from the first
/// `KeyAttrFlags` entry of the chosen time axis.
fn flatten_curve(
    by_component: &std::collections::BTreeMap<u32, FbxAnimCurveData>,
    path: FbxAnimChannelPath,
    ktime_f: f64,
) -> Option<FbxAnimChannel> {
    let time_axis = by_component
        .get(&0)
        .or_else(|| by_component.get(&1))
        .or_else(|| by_component.get(&2))?;
    let n = time_axis.key_times.len();
    let mut input = Vec::with_capacity(n);
    let component_count = path.component_count();
    let mut output = Vec::with_capacity(n * component_count);
    let mut in_tangents = Vec::with_capacity(n * component_count);
    let mut out_tangents = Vec::with_capacity(n * component_count);
    let flags = time_axis.key_attr_flags.first().copied().unwrap_or(0);
    let interpolation = FbxAnimInterpolation::from_key_attr_flags(flags);
    for i in 0..n {
        input.push((time_axis.key_times[i] as f64 / ktime_f) as f32);
        for component in 0..component_count as u32 {
            let value = by_component.get(&component).and_then(|curve| {
                if i < curve.key_values.len() {
                    Some(curve.key_values[i])
                } else {
                    None
                }
            });
            output.push(value.unwrap_or(0.0));
            in_tangents.push(
                by_component
                    .get(&component)
                    .and_then(|curve| curve.in_tangents.get(i))
                    .copied()
                    .unwrap_or(0.0),
            );
            out_tangents.push(
                by_component
                    .get(&component)
                    .and_then(|curve| curve.out_tangents.get(i))
                    .copied()
                    .unwrap_or(0.0),
            );
        }
    }
    // FBX stores Euler rotations in degrees; convert to radians so the JS
    // viewer's Euler→quaternion helper matches expectations. Translation and
    // scale are passed through unchanged.
    //
    // Through `f64`, and narrowing once at the end. `f32::to_radians` rounds
    // its own factor and then rounds the product, so composing it with the
    // writer's inverse moved an angle by a bit on every rewrite.
    let radians = |value: f32| f64::from(value).to_radians() as f32;
    if path == FbxAnimChannelPath::Rotation {
        for chunk in output.chunks_mut(3) {
            for value in chunk.iter_mut() {
                *value = radians(*value);
            }
        }
        for chunk in in_tangents.chunks_mut(3) {
            for value in chunk.iter_mut() {
                *value = radians(*value);
            }
        }
        for chunk in out_tangents.chunks_mut(3) {
            for value in chunk.iter_mut() {
                *value = radians(*value);
            }
        }
    }
    Some(FbxAnimChannel {
        node_id: FbxNodeId(0),
        node_name: String::new(),
        path,
        morph_target_index: None,
        sampler: FbxAnimSampler {
            input,
            output,
            interpolation,
            in_tangents: (interpolation == FbxAnimInterpolation::Cubic).then_some(in_tangents),
            out_tangents: (interpolation == FbxAnimInterpolation::Cubic).then_some(out_tangents),
        },
    })
}

/// Determine the FBX KTime ticks-per-second value.
///
/// Pre-7.7 files use `46186158000`. FBX 2019.5+ (version 7700+) introduced an
/// opt-in `141120000` ticks/second default; the legacy value is selected by
/// `FBXHeaderExtension/OtherFlags/TCDefinition == 127`. See Blender's
/// `io_scene_fbx` `FBX_KTIME` constants for the canonical encoding.
fn fbx_ktime_for(nodes: &[FbxNode], version: u32) -> u64 {
    const KTIME_V7: u64 = 46_186_158_000;
    const KTIME_V8: u64 = 141_120_000;
    if version >= 8000 {
        return KTIME_V8;
    }
    if version >= 7700 {
        // Inspect OtherFlags/TCDefinition. 127 selects the legacy V7 value;
        // anything else (or missing) opts into V8.
        for n in nodes {
            if n.name != "FBXHeaderExtension" {
                continue;
            }
            let mut header_version = 0;
            let mut other_flags: Option<&FbxNode> = None;
            for child in &n.children {
                if child.name == "FBXHeaderVersion" {
                    if let Some(FbxProperty::I32(v)) = child.properties.first() {
                        header_version = *v;
                    }
                } else if child.name == "OtherFlags" && other_flags.is_none() {
                    other_flags = Some(child);
                }
            }
            if header_version >= 1004 {
                if let Some(flags) = other_flags {
                    for flag in &flags.children {
                        if flag.name == "TCDefinition" {
                            if let Some(FbxProperty::I32(v)) = flag.properties.first() {
                                return if *v == 127 { KTIME_V7 } else { KTIME_V8 };
                            }
                        }
                    }
                }
            }
        }
        // Pre-8000 default for 7.7+ files without an explicit TCDefinition is V7.
        return KTIME_V7;
    }
    KTIME_V7
}

fn layer_string(layer: &FbxNode, name: &str) -> Option<String> {
    for child in &layer.children {
        if child.name == name {
            if let Some(FbxProperty::String(s)) = child.properties.first() {
                return Some(s.clone());
            }
        }
    }
    None
}

fn layer_int_array(layer: &FbxNode, name: &str) -> Option<Vec<i32>> {
    for child in &layer.children {
        if child.name == name {
            if let Some(FbxProperty::I32Array(arr)) = child.properties.first() {
                return Some(arr.clone());
            }
        }
    }
    None
}

/// Reports a layer element whose mapping or reference mode this crate does not
/// recognize.
///
/// The value is still resolved on the control-point domain, which is the most
/// likely intent and what the reader has always done. The warning exists so a
/// caller learns the substitution happened rather than inferring it from
/// unexpected geometry.
fn warn_unsupported_layer_mapping<const N: usize>(
    element: &str,
    set: &FbxLayerSet<N>,
    warnings: &mut Vec<FbxWarning>,
) {
    const KNOWN_MAPPINGS: [&str; 7] = [
        "ByPolygonVertex",
        "ByPolygon",
        "ByVertice",
        "ByVertex",
        "ByControlPoint",
        "AllSame",
        "AllSameOrPolygon",
    ];
    if let Some(mapping) = set.mapping.as_deref() {
        if !KNOWN_MAPPINGS.contains(&mapping) {
            let subject = format!("{element}/{mapping}");
            push_warning(
                warnings,
                FbxWarningCode::UnsupportedLayerMapping,
                format!(
                    "FBX {element} uses mapping {mapping}, which was resolved on the \
                     control-point domain"
                ),
                Some(&subject),
            );
        }
    }
    if let Some(reference) = set.reference.as_deref() {
        if reference != "Direct" && reference != "IndexToDirect" {
            let subject = format!("{element}/{reference}");
            push_warning(
                warnings,
                FbxWarningCode::UnsupportedLayerMapping,
                format!("FBX {element} uses reference mode {reference}, which was read as Direct"),
                Some(&subject),
            );
        }
    }
}

/// What can be said about the length a non-corner layer element should have.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DomainCheck {
    /// The domain has a known size, and the layer must match it exactly.
    Expect(usize),
    /// The domain exists but its size is not known here, so the layer is kept
    /// as authored rather than judged.
    Unverifiable,
    /// The mapping names no domain this crate recognizes.
    Unknown,
}

impl DomainCheck {
    fn accepts(self, len: usize) -> bool {
        match self {
            DomainCheck::Expect(expected) => expected == len,
            DomainCheck::Unverifiable => true,
            DomainCheck::Unknown => false,
        }
    }
}

/// Reports a smoothing or crease layer whose length disagrees with the domain
/// its mapping names, and which was therefore dropped.
fn warn_misaligned_layer(
    element: &str,
    mapping: Option<&str>,
    len: usize,
    warnings: &mut Vec<FbxWarning>,
) {
    let mapping = mapping.unwrap_or("no mapping");
    let subject = format!("{element}/{mapping}");
    push_warning(
        warnings,
        FbxWarningCode::UnsupportedLayerMapping,
        format!(
            "FBX {element} has {len} values, which does not match the domain \
             {mapping} addresses, so the layer was dropped"
        ),
        Some(&subject),
    );
}

/// Reads a layer element's `f64` payload, for the crease weights that are not
/// vectors and so do not go through [`chunk_layer_values`].
fn layer_f64_array(layer: &FbxNode, name: &str) -> Option<Vec<f64>> {
    for child in &layer.children {
        if child.name == name {
            return match child.properties.first() {
                Some(FbxProperty::F64Array(arr)) => Some(arr.clone()),
                Some(FbxProperty::F32Array(arr)) => {
                    Some(arr.iter().map(|v| f64::from(*v)).collect())
                }
                _ => None,
            };
        }
    }
    None
}

/// Reads a `LayerElementTangent` or `LayerElementBinormal`.
///
/// The handedness sign is a separate sibling array present only from FBX 7500
/// on; when it is missing, or disagrees with the vector count, `w` defaults to
/// `+1.0` and the set records that it was synthesized.
fn parse_tangent_like(
    layer: &FbxNode,
    values_node: &str,
    handedness_node: &str,
    index_node: &str,
) -> Option<FbxTangentSet> {
    let vectors: Vec<[f32; 3]> = chunk_layer_values(&read_layer_floats(layer, values_node)?);
    let handedness = read_layer_floats(layer, handedness_node)
        .filter(|signs| signs.len() == vectors.len())
        .unwrap_or_default();
    let has_handedness = !handedness.is_empty();
    let values = vectors
        .iter()
        .enumerate()
        .map(|(index, v)| {
            let sign = handedness.get(index).copied().unwrap_or(1.0);
            [v[0], v[1], v[2], sign]
        })
        .collect();
    Some(FbxTangentSet {
        layer: layer_set(layer, values, &[index_node]),
        has_handedness,
    })
}

/// Reads the parts every float layer element shares.
///
/// `index_nodes` lists the names the index array may appear under, tried in
/// order: exporters disagree on some of them.
fn layer_set<const N: usize>(
    layer: &FbxNode,
    values: Vec<[f32; N]>,
    index_nodes: &[&str],
) -> FbxLayerSet<N> {
    FbxLayerSet {
        name: layer_string(layer, "Name"),
        mapping: layer_string(layer, "MappingInformationType"),
        reference: layer_string(layer, "ReferenceInformationType"),
        values,
        indices: index_nodes
            .iter()
            .find_map(|name| layer_int_array(layer, name))
            .unwrap_or_default(),
    }
}

/// Groups a flat float payload into `N`-component values, dropping a trailing
/// partial value.
fn chunk_layer_values<const N: usize>(raw: &[f32]) -> Vec<[f32; N]> {
    raw.chunks_exact(N)
        .map(|value| std::array::from_fn(|i| value[i]))
        .collect()
}

/// Reads a layer element's flat float payload, whatever its component count.
///
/// FBX writes these as `f64` arrays; some exporters use `f32`.
fn read_layer_floats(layer: &FbxNode, name: &str) -> Option<Vec<f32>> {
    for child in &layer.children {
        if child.name == name {
            if let Some(FbxProperty::F64Array(arr)) = child.properties.first() {
                return Some(arr.iter().map(|v| *v as f32).collect());
            }
            if let Some(FbxProperty::F32Array(arr)) = child.properties.first() {
                return Some(arr.clone());
            }
        }
    }
    None
}

/// Expand a `LayerElementMaterial` data array to per-triangle material indices.
fn expand_material_indices(
    mapping: Option<&str>,
    reference: Option<&str>,
    data: Option<&[i32]>,
    polygon_count: usize,
    tri_polygon_index: &[usize],
) -> Option<Vec<i32>> {
    let mapping = mapping.unwrap_or("AllSame");
    let data = data?;
    // `IndexToDirect` semantics: each entry of `Materials` is itself the
    // absolute material index (FBX rarely uses a separate index array for
    // materials, but we honour `IndexToDirect` by treating `data` as the
    // direct list when no separate index exists).
    let _ = reference;
    let per_polygon: Vec<i32> = match mapping {
        "AllSame" => {
            let value = data.first().copied().unwrap_or(0);
            vec![value; polygon_count.max(1)]
        }
        "ByPolygon" | "ByPolygonSide" => data.to_vec(),
        "ByPolygonVertex" => {
            // We do not retain per-vertex polygon order here; pick the first
            // vertex entry of each polygon. The caller passes
            // `tri_polygon_index` keyed by polygon index.
            // Without polygon-vertex correspondence we fall back to AllSame.
            let value = data.first().copied().unwrap_or(0);
            vec![value; polygon_count.max(1)]
        }
        _ => return None,
    };
    if per_polygon.is_empty() {
        return Some(Vec::new());
    }
    let mut out = Vec::with_capacity(tri_polygon_index.len());
    for &polygon_index in tri_polygon_index {
        let value = per_polygon
            .get(polygon_index)
            .copied()
            .unwrap_or(per_polygon[0]);
        out.push(value);
    }
    Some(out)
}