animsmith-fbx 0.4.2

FBX ingestion into the animsmith core model, via the official ufbx bindings
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
//! Conservative ufbx-side scale capability inventory.

use animsmith_core::scale::{ScaleCapabilityCoverage, ScaleCapabilityFacts};
use animsmith_core::{
    DependencyClosureV1, Document, LoadedSource, SourceConstructKindV1, SourceFactsViewV1,
    SourceResourceLocatorV1, SourceSetCoverageStateV1,
};
use serde::Serialize;

/// How one Appendix D.4 domain reaches the normalized FBX document.
///
/// These values describe semantic ingestion only. None claims raw FBX byte,
/// object-property, curve-key, or payload-span preservation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FbxScaleDomainStatus {
    /// The source inspection proved that the domain is absent.
    Absent,
    /// ufbx normalized the source representation before it reached the core model.
    Normalized,
    /// ufbx evaluated source animation into resampled linear TRS tracks.
    Baked,
    /// The value is derived from another normalized domain.
    Derived,
    /// The loader rebuilt the domain into a different normalized representation.
    Rebuilt,
    /// The source domain is present but not completely represented.
    Unsupported,
    /// ufbx exposes no raw-span relationship with which to prove this domain.
    Unverifiable,
}

/// Explicit status for every current domain row in DESIGN.md Appendix D.4.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FbxScaleDomainInventory {
    /// Rest hierarchy and local transforms.
    pub rest_hierarchy: FbxScaleDomainStatus,
    /// Translation animation values and tangents.
    pub translation_animation: FbxScaleDomainStatus,
    /// Rotation and scale animation values and tangents.
    pub rotation_and_scale_animation: FbxScaleDomainStatus,
    /// Root-motion and velocity evidence derived from translation tracks.
    pub root_motion_and_velocity: FbxScaleDomainStatus,
    /// Base mesh positions and normals.
    pub base_mesh_geometry: FbxScaleDomainStatus,
    /// Morph targets and morph-weight animation.
    pub morphs: FbxScaleDomainStatus,
    /// Per-skin inverse-bind matrices.
    pub skin_binds: FbxScaleDomainStatus,
    /// Cameras and lights.
    pub cameras_and_lights: FbxScaleDomainStatus,
    /// Collision, custom properties, constraints, and unknown elements.
    pub collision_and_custom_data: FbxScaleDomainStatus,
    /// Other vertex attributes, deformers, and source geometry kinds.
    pub other_vertex_and_source_data: FbxScaleDomainStatus,
    /// Source transform-stack state outside the normalized TRS model.
    pub out_of_contract_node_transforms: FbxScaleDomainStatus,
    /// Animation targeting source transform-stack or matrix state.
    pub animation_targeting_matrix_nodes: FbxScaleDomainStatus,
    /// Shared raw payload spans corresponding to glTF accessors.
    pub shared_raw_accessor_payloads: FbxScaleDomainStatus,
    /// Raw payload spans corresponding to unreferenced glTF accessors.
    pub unreferenced_accessor_payloads: FbxScaleDomainStatus,
    /// Image payload spans that could alias scale-bearing source bytes.
    pub image_payload_aliases: FbxScaleDomainStatus,
}

impl FbxScaleDomainInventory {
    /// Every Appendix D.4 row in table order with its current FBX status.
    ///
    /// This is the mechanical bridge between the public named fields and the
    /// design table. Tests compare these names with the table so adding a row
    /// to either authority cannot silently leave the other incomplete.
    pub fn named_rows(&self) -> [(&'static str, FbxScaleDomainStatus); 15] {
        [
            ("Rest hierarchy", self.rest_hierarchy),
            ("Translation animation", self.translation_animation),
            (
                "Rotation and scale animation",
                self.rotation_and_scale_animation,
            ),
            ("Root motion and velocity", self.root_motion_and_velocity),
            ("Base mesh geometry", self.base_mesh_geometry),
            ("Morphs", self.morphs),
            ("Skin binds", self.skin_binds),
            ("Cameras/lights", self.cameras_and_lights),
            ("Collision/custom data", self.collision_and_custom_data),
            (
                "Other vertex/source data",
                self.other_vertex_and_source_data,
            ),
            (
                "Out-of-contract node transforms",
                self.out_of_contract_node_transforms,
            ),
            (
                "Animation targeting a matrix node",
                self.animation_targeting_matrix_nodes,
            ),
            (
                "Shared raw accessor payloads",
                self.shared_raw_accessor_payloads,
            ),
            (
                "Unreferenced accessor payloads",
                self.unreferenced_accessor_payloads,
            ),
            ("Image payload aliases", self.image_payload_aliases),
        ]
    }

    /// Semantic domains whose normalized representation must be complete
    /// before the narrow FBX rest/bind bridge may stage a GLB.
    ///
    /// The three raw-span rows are deliberately excluded: the bridge never
    /// rewrites FBX bytes, so it serializes a private GLB and proves that
    /// GLB's raw spans instead. Keeping this as typed fields rather than
    /// display labels makes a newly added semantic domain fail closed until
    /// this policy is deliberately updated.
    fn rest_bind_semantic_statuses(&self) -> [(&'static str, FbxScaleDomainStatus); 11] {
        [
            ("rest_hierarchy", self.rest_hierarchy),
            ("translation_animation", self.translation_animation),
            (
                "rotation_and_scale_animation",
                self.rotation_and_scale_animation,
            ),
            ("root_motion_and_velocity", self.root_motion_and_velocity),
            ("base_mesh_geometry", self.base_mesh_geometry),
            ("morphs", self.morphs),
            ("skin_binds", self.skin_binds),
            ("cameras_and_lights", self.cameras_and_lights),
            (
                "other_vertex_and_source_data",
                self.other_vertex_and_source_data,
            ),
            (
                "out_of_contract_node_transforms",
                self.out_of_contract_node_transforms,
            ),
            (
                "animation_targeting_matrix_nodes",
                self.animation_targeting_matrix_nodes,
            ),
        ]
    }

    /// The raw-span rows whose FBX status is expected to be unverifiable.
    fn rest_bind_raw_span_statuses(&self) -> [(&'static str, FbxScaleDomainStatus); 3] {
        [
            (
                "shared_raw_accessor_payloads",
                self.shared_raw_accessor_payloads,
            ),
            (
                "unreferenced_accessor_payloads",
                self.unreferenced_accessor_payloads,
            ),
            ("image_payload_aliases", self.image_payload_aliases),
        ]
    }
}

/// A format-independent spelling of one FBX coordinate axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FbxCoordinateAxis {
    /// Positive X.
    PositiveX,
    /// Negative X.
    NegativeX,
    /// Positive Y.
    PositiveY,
    /// Negative Y.
    NegativeY,
    /// Positive Z.
    PositiveZ,
    /// Negative Z.
    NegativeZ,
    /// ufbx could not determine the axis.
    Unknown,
}

impl From<ufbx::CoordinateAxis> for FbxCoordinateAxis {
    fn from(value: ufbx::CoordinateAxis) -> Self {
        match value {
            ufbx::CoordinateAxis::PositiveX => Self::PositiveX,
            ufbx::CoordinateAxis::NegativeX => Self::NegativeX,
            ufbx::CoordinateAxis::PositiveY => Self::PositiveY,
            ufbx::CoordinateAxis::NegativeY => Self::NegativeY,
            ufbx::CoordinateAxis::PositiveZ => Self::PositiveZ,
            ufbx::CoordinateAxis::NegativeZ => Self::NegativeZ,
            ufbx::CoordinateAxis::Unknown => Self::Unknown,
        }
    }
}

/// Coordinate and unit normalization applied by the loader.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FbxCoordinateNormalization {
    /// Advisory `OriginalUpAxis` value reported by ufbx.
    ///
    /// This is not the effective `UpAxis`/`FrontAxis`/`CoordAxis` basis.
    pub original_up_axis: FbxCoordinateAxis,
    /// Advisory `OriginalUnitScaleFactor` value in metres reported by ufbx.
    ///
    /// This is not the effective `UnitScaleFactor` source unit.
    pub original_unit_meters: f64,
    /// Target is right-handed, +Y up, and -Z forward.
    pub target_right_handed_y_up: bool,
    /// Target unit in metres.
    pub target_unit_meters: f64,
    /// ufbx adjusted transforms rather than preserving raw transform members.
    pub adjust_transforms: bool,
}

/// Stable source identity retained beside one normalized ufbx element.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FbxSourceIdentity {
    /// Stable index in the relevant ufbx typed list.
    pub source_index: usize,
    /// ufbx's typed id, which addresses that typed list.
    pub ufbx_typed_id: u32,
    /// ufbx's scene-wide element id, or zero for its generated root.
    ///
    /// This is deliberately not described as the raw FBX object id: ufbx
    /// assigns its own stable scene identity after parsing and normalization.
    pub ufbx_element_id: u32,
}

/// Provenance of inverse-bind matrices projected into the source sidecar.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FbxBindMatrixProvenance {
    /// ufbx converted cluster bind matrices into target coordinates, then the
    /// loader derived `bind_to_world^-1 * geometry_to_world` per cluster.
    UfbxConvertedClusterMatrices,
}

/// Deterministic capability inventory captured from one successfully parsed FBX scene.
///
/// Every current Appendix D.4 row has a status, but those statuses deliberately
/// include unsupported and unverifiable states. Call
/// [`capability_facts`] to project those states into the format-neutral core
/// gate; #286-A never turns them into operation support. This is also the
/// frozen source projection serialized by scale-evidence v5: a new inventory
/// fact requires a new evidence version rather than silently changing v5.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FbxScaleCapabilityInventory {
    /// Every Appendix D.4 domain, in named fields rather than an absence-based map.
    pub domains: FbxScaleDomainInventory,
    /// Coordinate and unit normalization applied before model construction.
    pub coordinate_normalization: FbxCoordinateNormalization,
    /// Every animation take is evaluated through `ufbx::bake_anim`.
    pub animation_takes_baked: bool,
    /// Authored FBX curve keys and interpolation are not retained.
    pub authored_curve_keys_preserved: bool,
    /// Number of source animation takes.
    pub animation_take_count: usize,
    /// Number of source animation curves discarded after baking.
    pub source_animation_curve_count: usize,
    /// Number of ufbx-generated geometry-transform helper nodes.
    pub generated_geometry_helper_node_count: usize,
    /// Number of ufbx-generated scale-compensation helper nodes.
    pub generated_scale_helper_node_count: usize,
    /// Whether the load boundary asks ufbx to compensate FBX inherit modes.
    pub inherit_modes_compensated: bool,
    /// Number of nodes whose original inherit mode or helper state required compensation.
    pub compensated_inherit_node_count: usize,
    /// Number of meshes for which ufbx generated missing normals.
    pub generated_normal_mesh_count: usize,
    /// Number of meshes still lacking normals after generation was requested.
    pub missing_normal_mesh_count: usize,
    /// Number of source skin deformers.
    pub skin_deformer_count: usize,
    /// Number of source skin clusters.
    pub skin_cluster_count: usize,
    /// Number of source skin deformers that declare no clusters or bind matrices.
    pub empty_skin_deformer_count: usize,
    /// Provenance of every available projected inverse-bind matrix.
    pub bind_matrix_provenance: FbxBindMatrixProvenance,
    /// Number of clusters missing a bone or a finite converted bind matrix.
    pub incomplete_bind_cluster_count: usize,
    /// Number of times multiple successfully projected clusters target one bone and overwrite its
    /// lossy convenience bind. Unreadable clusters are skipped, not counted as writes.
    pub bone_convenience_bind_overwrite_count: usize,
    /// Whether the loader invented identity matrices for missing bind evidence.
    pub identity_bind_defaults_invented: bool,
    /// Number of normalized vertices whose source influence list exceeded four entries.
    pub truncated_influence_vertex_count: usize,
    /// Number of source influences discarded by the four-slot limit.
    pub discarded_influence_count: usize,
    /// Number of normalized vertices whose retained weights changed during renormalization.
    pub renormalized_influence_vertex_count: usize,
    /// Number of non-finite, negative, or unrepresentable source influences rejected.
    pub rejected_influence_count: usize,
    /// Number of emitted skinned corners whose source vertex had no influence record.
    pub missing_skin_influence_corner_count: usize,
    /// Number of source faces that are not triangles.
    pub non_triangle_face_count: usize,
    /// Number of polygon faces with more than three corners that were triangulated.
    pub triangulated_face_count: usize,
    /// Number of point/line faces omitted from triangle output.
    pub omitted_non_polygon_face_count: usize,
    /// Number of source mesh definitions that declare no faces.
    pub empty_mesh_definition_count: usize,
    /// Stable identities of the zero-face source mesh definitions counted above.
    pub empty_source_meshes: Vec<FbxSourceIdentity>,
    /// Number of unindexed corners submitted to exact-bit welding.
    pub pre_weld_vertex_count: usize,
    /// Number of normalized vertices retained after exact-bit welding.
    pub post_weld_vertex_count: usize,
    /// Number of source meshes with more than one skin deformer.
    pub multiple_skin_deformer_mesh_count: usize,
    /// Number of dual-quaternion skin deformers not represented by the normalized model.
    pub dual_quaternion_skin_count: usize,
    /// Number of blend deformers (morph domains) not represented by the normalized model.
    pub blend_deformer_count: usize,
    /// Number of blend channels not represented by the normalized model.
    pub blend_channel_count: usize,
    /// Number of blend shapes not represented by the normalized model.
    pub blend_shape_count: usize,
    /// Number of geometry cache deformers not represented by the normalized model.
    pub cache_deformer_count: usize,
    /// Number of meshes carrying unsupported modeled-vertex payloads.
    pub unsupported_vertex_payload_mesh_count: usize,
    /// Number of cameras.
    pub camera_count: usize,
    /// Number of lights.
    pub light_count: usize,
    /// Number of shared mesh definitions with more than one node instance.
    pub shared_mesh_definition_count: usize,
    /// Number of source mesh definitions with no node instance and no normalized output mesh.
    pub uninstanced_mesh_definition_count: usize,
    /// Stable identities of the uninstanced source mesh definitions counted above.
    pub uninstanced_source_meshes: Vec<FbxSourceIdentity>,
    /// Number of user-defined source properties.
    pub user_defined_property_count: usize,
    /// Number of unknown or otherwise unmodeled source elements/scene records.
    pub unsupported_source_element_count: usize,
    /// Number of referenced external texture/video payloads.
    pub external_resource_count: usize,
    /// Node identities in stable ufbx source order.
    pub source_nodes: Vec<FbxSourceIdentity>,
    /// Mesh identities in stable ufbx source order.
    pub source_meshes: Vec<FbxSourceIdentity>,
    /// Skin-deformer identities in stable ufbx source order.
    pub source_skins: Vec<FbxSourceIdentity>,
}

/// One immutable FBX source/document owner and scale capability inventory
/// captured from the same parse.
#[derive(Debug)]
pub struct FbxScaleSource {
    pub(crate) source: LoadedSource,
    pub(crate) inventory: FbxScaleCapabilityInventory,
    /// Same-parse breakdown behind the aggregate construct inventory.
    ///
    /// This parser-side distinction is intentionally not part of the frozen
    /// scale-evidence v5 inventory. It is same-load admission evidence for the
    /// normalized GLB bridge, where the texture/video declarations have their
    /// own bounded resource facts and cannot affect rest/bind transforms.
    pub(crate) rest_bind_construct_counts: crate::source_facts::RestBindSourceConstructCounts,
    /// Same-parse meshes whose unsupported public payload aggregate consists
    /// entirely of enumerated scale-invariant conversion-fidelity facts.
    pub(crate) rest_bind_scale_invariant_payload_mesh_count: usize,
}

impl FbxScaleSource {
    /// The normalized document carrying the documented ufbx source projection.
    pub fn document(&self) -> &Document {
        self.source.document()
    }

    /// The bounded importer-sensitive facts retained from the same ufbx parse.
    pub fn source_facts(&self) -> SourceFactsViewV1<'_> {
        self.source.source_facts()
    }

    /// The bounded dependency closure captured with the same ufbx parse.
    pub fn dependency_closure(&self) -> &DependencyClosureV1 {
        self.source.dependency_closure()
    }

    /// The conservative ufbx-side inventory.
    pub fn inventory(&self) -> &FbxScaleCapabilityInventory {
        &self.inventory
    }

    /// Consume the source wrapper and retain its normalized document.
    pub fn into_document(self) -> Document {
        self.source.into_document()
    }

    pub(crate) fn into_source(self) -> LoadedSource {
        self.source
    }
}

/// Project an FBX inventory into the format-neutral core capability gate.
///
/// `coverage` means every Appendix D.4 domain has an explicit status, not that
/// any domain is preserved losslessly. Support remains false: normalized transform stacks, baked
/// curves, rebuilt meshes, and unverifiable raw payload relationships are
/// recorded as unsupported facts rather than hidden behind absent flags.
pub fn capability_facts(inventory: &FbxScaleCapabilityInventory) -> ScaleCapabilityFacts {
    let mut facts = ScaleCapabilityFacts::default();
    facts.coverage = ScaleCapabilityCoverage::Complete;
    let morph_source_present = inventory.blend_deformer_count > 0
        || inventory.blend_channel_count > 0
        || inventory.blend_shape_count > 0;
    facts.morphs_present = morph_source_present;
    facts.morph_weights_present = morph_source_present;
    facts.cameras_present = inventory.camera_count > 0;
    facts.lights_present = inventory.light_count > 0;
    facts.instancing_present = inventory.shared_mesh_definition_count > 0;
    facts.unregistered_extensions_present = inventory.unsupported_source_element_count > 0;
    facts.extras_present = inventory.user_defined_property_count > 0;
    // FBX transform stacks and authored animation curves are normalized or
    // baked before Document construction, so their raw members are not in
    // the model even for the smallest accepted scene.
    facts.unknown_source_members_present = true;
    facts.non_triangle_primitives_present = inventory.non_triangle_face_count > 0;
    facts.unsupported_vertex_attributes_present = inventory.unsupported_vertex_payload_mesh_count
        > 0
        || inventory.uninstanced_mesh_definition_count > 0
        || inventory.empty_mesh_definition_count > 0
        || inventory.multiple_skin_deformer_mesh_count > 0
        || inventory.dual_quaternion_skin_count > 0
        || inventory.cache_deformer_count > 0
        || inventory.missing_skin_influence_corner_count > 0
        || inventory.rejected_influence_count > 0
        || inventory.pre_weld_vertex_count != inventory.post_weld_vertex_count;
    facts.secondary_skin_influences_present = inventory.truncated_influence_vertex_count > 0;
    facts.inverse_bind_issues_present =
        inventory.incomplete_bind_cluster_count > 0 || inventory.empty_skin_deformer_count > 0;
    // ufbx exposes normalized objects, not accessor/image byte spans. A future
    // FBX writer must discharge this preservation obligation through the full
    // inventory route; #286-A cannot declare the source layout rewrite-safe.
    facts.unsafe_accessor_layout_present = true;
    facts.external_resources_present = inventory.external_resource_count > 0;
    facts
}

/// Project scale capabilities from one immutable captured FBX source.
///
/// The operation inventory keeps its detailed normalization/bake ledger. The
/// shared raw-source facts independently supply custom/unknown construct and
/// resource presence, and partial shared coverage always fails closed.
pub fn capability_facts_for_source(source: &FbxScaleSource) -> ScaleCapabilityFacts {
    join_source_facts(source, capability_facts(source.inventory()))
}

fn join_source_facts(
    source: &FbxScaleSource,
    mut facts: ScaleCapabilityFacts,
) -> ScaleCapabilityFacts {
    let source_facts = source.source_facts();
    if [
        source_facts.constructs().coverage().state(),
        source_facts.resources().coverage().state(),
    ]
    .into_iter()
    .any(|state| state != SourceSetCoverageStateV1::Complete)
    {
        facts.coverage = ScaleCapabilityCoverage::Unavailable;
    }
    for row in source_facts.constructs().rows() {
        match row.kind() {
            SourceConstructKindV1::CustomProperty => facts.extras_present = true,
            SourceConstructKindV1::UnknownElement => {
                facts.unknown_source_members_present = true;
            }
            SourceConstructKindV1::Extension => facts.unregistered_extensions_present = true,
        }
    }
    if source_facts.resources().rows().iter().any(|row| {
        !matches!(
            row.locator(),
            SourceResourceLocatorV1::Embedded | SourceResourceLocatorV1::DataUri
        )
    }) {
        facts.external_resources_present = true;
    }
    facts
}

/// Project the narrow FBX subset that can enter rest/bind scaling.
///
/// The accepted operation rewrites a freshly serialized GLB rather than the
/// FBX container, so the three raw-span rows are intentionally
/// [`FbxScaleDomainStatus::Unverifiable`]. Every semantic domain must still
/// be complete when it can affect the normalized document. User-defined FBX
/// properties are already explicitly discarded by the loader, and external
/// image declarations require the source-aware companion so their same-load
/// resource classification and capture can be validated before staging. The
/// frozen inventory alone remains conservative for external references because
/// it cannot prove that boundary. Neither known class is a scale-bearing
/// ambiguity. The source-aware form may also admit enumerated scale-invariant
/// conversion-fidelity facts while retaining them in the inventory. Unknown
/// source elements, missing effective influence coverage, incomplete bind
/// evidence, or an incomplete coordinate projection remain stable refusals
/// before the producer can stage any output.
pub fn rest_bind_capability_facts(
    inventory: &FbxScaleCapabilityInventory,
) -> Result<ScaleCapabilityFacts, String> {
    if inventory.external_resource_count != 0 {
        return Err(format_rest_bind_violations(
            "capability inventory",
            &[format!(
                "external_resource_count={}",
                inventory.external_resource_count
            )],
        ));
    }
    rest_bind_capability_facts_with_context(inventory, RestBindCapabilityContext::InventoryOnly)
}

#[derive(Debug, Clone, Copy)]
enum RestBindCapabilityContext<'a> {
    InventoryOnly,
    CapturedSource {
        counts: &'a crate::source_facts::RestBindSourceConstructCounts,
        scale_invariant_payload_mesh_count: usize,
    },
}

fn rest_bind_capability_facts_with_context(
    inventory: &FbxScaleCapabilityInventory,
    context: RestBindCapabilityContext<'_>,
) -> Result<ScaleCapabilityFacts, String> {
    let captured_source = match context {
        RestBindCapabilityContext::InventoryOnly => None,
        RestBindCapabilityContext::CapturedSource {
            counts,
            scale_invariant_payload_mesh_count,
        } => Some((counts, scale_invariant_payload_mesh_count)),
    };
    let mut violations = Vec::new();
    for (domain, status) in inventory.domains.rest_bind_semantic_statuses() {
        if domain == "other_vertex_and_source_data" && captured_source.is_some() {
            continue;
        }
        if matches!(
            status,
            FbxScaleDomainStatus::Unsupported | FbxScaleDomainStatus::Unverifiable
        ) {
            violations.push(format!(
                "domain.{domain}={}",
                fbx_scale_domain_status_name(status)
            ));
        }
    }
    for (domain, status) in inventory.domains.rest_bind_raw_span_statuses() {
        if status != FbxScaleDomainStatus::Unverifiable {
            violations.push(format!(
                "domain.{domain}={} (expected unverifiable)",
                fbx_scale_domain_status_name(status)
            ));
        }
    }

    let expected_custom_status = if inventory.unsupported_source_element_count == 0
        && inventory.user_defined_property_count == 0
    {
        FbxScaleDomainStatus::Absent
    } else {
        FbxScaleDomainStatus::Unsupported
    };
    if inventory.domains.collision_and_custom_data != expected_custom_status {
        violations.push(format!(
            "domain.collision_and_custom_data={} (expected {})",
            fbx_scale_domain_status_name(inventory.domains.collision_and_custom_data),
            fbx_scale_domain_status_name(expected_custom_status)
        ));
    }
    if let Some((source_counts, _)) = captured_source {
        if inventory.user_defined_property_count != source_counts.user_defined_property_count {
            violations.push(format!(
                "user_defined_property_count={}!=source:{}",
                inventory.user_defined_property_count, source_counts.user_defined_property_count
            ));
        }
        let source_unmodeled_count = source_counts.total_unmodeled_element_count();
        if inventory.unsupported_source_element_count != source_unmodeled_count {
            violations.push(format!(
                "unsupported_source_element_count={}!=source:{}",
                inventory.unsupported_source_element_count, source_unmodeled_count
            ));
        }
        push_unmodeled_element_violation(&mut violations, *source_counts);
    } else {
        push_nonzero_violation(
            &mut violations,
            "unsupported_source_element_count",
            inventory.unsupported_source_element_count,
        );
    }

    if !inventory.coordinate_normalization.target_right_handed_y_up {
        violations.push("coordinate_normalization.target_right_handed_y_up=false".into());
    }
    if inventory.coordinate_normalization.target_unit_meters != 1.0 {
        violations.push(format!(
            "coordinate_normalization.target_unit_meters={}",
            inventory.coordinate_normalization.target_unit_meters
        ));
    }
    if !inventory.coordinate_normalization.adjust_transforms {
        violations.push("coordinate_normalization.adjust_transforms=false".into());
    }
    if !inventory.animation_takes_baked {
        violations.push("animation_takes_baked=false".into());
    }
    if inventory.authored_curve_keys_preserved {
        violations.push("authored_curve_keys_preserved=true".into());
    }
    if !inventory.inherit_modes_compensated {
        violations.push("inherit_modes_compensated=false".into());
    }
    if inventory.identity_bind_defaults_invented {
        violations.push("identity_bind_defaults_invented=true".into());
    }
    for (name, value) in [
        ("blend_deformer_count", inventory.blend_deformer_count),
        ("blend_channel_count", inventory.blend_channel_count),
        ("blend_shape_count", inventory.blend_shape_count),
        ("camera_count", inventory.camera_count),
        ("light_count", inventory.light_count),
        (
            "shared_mesh_definition_count",
            inventory.shared_mesh_definition_count,
        ),
        (
            "uninstanced_mesh_definition_count",
            inventory.uninstanced_mesh_definition_count,
        ),
        (
            "empty_mesh_definition_count",
            inventory.empty_mesh_definition_count,
        ),
        (
            "multiple_skin_deformer_mesh_count",
            inventory.multiple_skin_deformer_mesh_count,
        ),
        (
            "dual_quaternion_skin_count",
            inventory.dual_quaternion_skin_count,
        ),
        ("cache_deformer_count", inventory.cache_deformer_count),
        (
            "incomplete_bind_cluster_count",
            inventory.incomplete_bind_cluster_count,
        ),
        (
            "empty_skin_deformer_count",
            inventory.empty_skin_deformer_count,
        ),
        (
            "missing_normal_mesh_count",
            inventory.missing_normal_mesh_count,
        ),
        (
            "bone_convenience_bind_overwrite_count",
            inventory.bone_convenience_bind_overwrite_count,
        ),
        (
            "missing_skin_influence_corner_count",
            inventory.missing_skin_influence_corner_count,
        ),
        (
            "omitted_non_polygon_face_count",
            inventory.omitted_non_polygon_face_count,
        ),
    ] {
        push_nonzero_violation(&mut violations, name, value);
    }
    if let Some((_, scale_invariant_payload_mesh_count)) = captured_source {
        if inventory.unsupported_vertex_payload_mesh_count != scale_invariant_payload_mesh_count {
            violations.push(format!(
                "unsupported_vertex_payload_mesh_count={}!=scale_invariant_source:{}",
                inventory.unsupported_vertex_payload_mesh_count, scale_invariant_payload_mesh_count
            ));
        }
    } else {
        for (name, value) in [
            (
                "unsupported_vertex_payload_mesh_count",
                inventory.unsupported_vertex_payload_mesh_count,
            ),
            (
                "truncated_influence_vertex_count",
                inventory.truncated_influence_vertex_count,
            ),
            (
                "discarded_influence_count",
                inventory.discarded_influence_count,
            ),
            (
                "renormalized_influence_vertex_count",
                inventory.renormalized_influence_vertex_count,
            ),
            (
                "rejected_influence_count",
                inventory.rejected_influence_count,
            ),
            ("non_triangle_face_count", inventory.non_triangle_face_count),
            ("triangulated_face_count", inventory.triangulated_face_count),
        ] {
            push_nonzero_violation(&mut violations, name, value);
        }
        if inventory.pre_weld_vertex_count != inventory.post_weld_vertex_count {
            violations.push(format!(
                "weld_vertex_count={}!=post:{}",
                inventory.pre_weld_vertex_count, inventory.post_weld_vertex_count
            ));
        }
    }
    if !violations.is_empty() {
        return Err(format_rest_bind_violations(
            "capability inventory",
            &violations,
        ));
    }

    // Reuse the complete conservative projection for every counter and
    // source-domain fact. These flags are discharged by the private GLB
    // staging/proof boundary: raw FBX members are not preserved, while the
    // already-validated texture-linkage aggregate, custom properties, and
    // external locator spellings cannot carry scale-bearing state into the
    // normalized document. Every other fact continues to gate the operation.
    let mut facts = capability_facts(inventory);
    facts.unknown_source_members_present = false;
    facts.unregistered_extensions_present = false;
    facts.unsafe_accessor_layout_present = false;
    facts.extras_present = false;
    facts.external_resources_present = false;
    if captured_source.is_some() {
        facts.non_triangle_primitives_present = false;
        facts.unsupported_vertex_attributes_present = false;
        facts.secondary_skin_influences_present = false;
    }
    if !facts.is_supported_for(
        animsmith_core::scale::ScaleOperation::RestBindUniformScale {
            source_skin_index: 0,
            source_root_node_index: 0,
            expected_factor: 1.0,
        },
    ) {
        return Err(format_rest_bind_violations(
            "projected capability",
            &scale_capability_violations(&facts),
        ));
    }
    Ok(facts)
}

/// Project the narrow FBX rest/bind subset from one captured source.
///
/// Shared construct/resource coverage is checked before the older
/// operation-specific inventory. This prevents a truncated positive-only raw
/// projection from being treated as proof of absence.
///
/// # Errors
///
/// Returns a stable refusal naming each incomplete shared-raw coverage domain,
/// unsupported construct row, semantic status, or inventory counter that
/// prevents proof of the selected domain.
pub fn rest_bind_capability_facts_for_source(
    source: &FbxScaleSource,
) -> Result<ScaleCapabilityFacts, String> {
    let source_facts = source.source_facts();
    let source_counts = source.rest_bind_construct_counts;
    let mut violations = Vec::new();
    for (domain, state) in [
        ("constructs", source_facts.constructs().coverage().state()),
        ("resources", source_facts.resources().coverage().state()),
    ] {
        if state != SourceSetCoverageStateV1::Complete {
            violations.push(format!(
                "raw_source.{domain}.coverage={}",
                source_set_coverage_state_name(state)
            ));
        }
    }
    let mut saw_custom_properties = false;
    let mut saw_unmodeled_elements = false;
    for row in source_facts.constructs().rows() {
        match row.kind() {
            SourceConstructKindV1::CustomProperty
                if row.name().as_str() == "fbx:user-defined-properties" =>
            {
                saw_custom_properties = true;
                if row.count()
                    != u64::try_from(source_counts.user_defined_property_count).unwrap_or(u64::MAX)
                {
                    violations.push(format!(
                        "raw_source.construct=custom_property({}; count={})!=source:{}",
                        row.name().as_str(),
                        row.count(),
                        source_counts.user_defined_property_count
                    ));
                }
            }
            SourceConstructKindV1::CustomProperty => violations.push(format!(
                "raw_source.construct=custom_property({}; count={})",
                row.name().as_str(),
                row.count()
            )),
            SourceConstructKindV1::UnknownElement
                if row.name().as_str() == "fbx:unmodeled-elements" =>
            {
                saw_unmodeled_elements = true;
                let total_count = u64::try_from(source_counts.total_unmodeled_element_count())
                    .unwrap_or(u64::MAX);
                if row.count() != total_count {
                    violations.push(format!(
                        "raw_source.construct=unknown_element({}; count={})!=source:{}",
                        row.name().as_str(),
                        row.count(),
                        total_count
                    ));
                } else if source_counts.unsupported_unmodeled_element_count() > 0 {
                    violations.push(format!(
                        "raw_source.construct=unknown_element({}; {})",
                        row.name().as_str(),
                        unmodeled_element_details(source_counts)
                    ));
                }
            }
            SourceConstructKindV1::UnknownElement => violations.push(format!(
                "raw_source.construct=unknown_element({}; count={})",
                row.name().as_str(),
                row.count()
            )),
            SourceConstructKindV1::Extension => violations.push(format!(
                "raw_source.construct=extension({}; count={})",
                row.name().as_str(),
                row.count()
            )),
        }
    }
    if source_counts.user_defined_property_count > 0 && !saw_custom_properties {
        violations.push(format!(
            "raw_source.construct=custom_property(fbx:user-defined-properties; count=0)!=source:{}",
            source_counts.user_defined_property_count
        ));
    }
    if source_counts.total_unmodeled_element_count() > 0 && !saw_unmodeled_elements {
        violations.push(format!(
            "raw_source.construct=unknown_element(fbx:unmodeled-elements; count=0)!=source:{}",
            source_counts.total_unmodeled_element_count()
        ));
    }
    if !violations.is_empty() {
        return Err(format_rest_bind_violations("raw-source facts", &violations));
    }

    let mut facts = join_source_facts(
        source,
        rest_bind_capability_facts_with_context(
            source.inventory(),
            RestBindCapabilityContext::CapturedSource {
                counts: &source_counts,
                scale_invariant_payload_mesh_count: source
                    .rest_bind_scale_invariant_payload_mesh_count,
            },
        )?,
    );
    facts.unknown_source_members_present = false;
    facts.unregistered_extensions_present = false;
    facts.extras_present = false;
    facts.external_resources_present = false;
    if facts.is_supported_for(
        animsmith_core::scale::ScaleOperation::RestBindUniformScale {
            source_skin_index: 0,
            source_root_node_index: 0,
            expected_factor: 1.0,
        },
    ) {
        Ok(facts)
    } else {
        Err(format_rest_bind_violations(
            "joined capability",
            &scale_capability_violations(&facts),
        ))
    }
}

fn push_unmodeled_element_violation(
    violations: &mut Vec<String>,
    counts: crate::source_facts::RestBindSourceConstructCounts,
) {
    if counts.unsupported_unmodeled_element_count() > 0 {
        violations.push(format!(
            "unsupported_source_element_count; {}",
            unmodeled_element_details(counts)
        ));
    }
}

fn unmodeled_element_details(counts: crate::source_facts::RestBindSourceConstructCounts) -> String {
    let mut details = format!("count={}", counts.unsupported_unmodeled_element_count());
    for (kind, count) in counts.unsupported_kind_counts() {
        details.push_str("; ");
        details.push_str(kind);
        details.push('=');
        details.push_str(&count.to_string());
    }
    details
}

fn fbx_scale_domain_status_name(status: FbxScaleDomainStatus) -> &'static str {
    match status {
        FbxScaleDomainStatus::Absent => "absent",
        FbxScaleDomainStatus::Normalized => "normalized",
        FbxScaleDomainStatus::Baked => "baked",
        FbxScaleDomainStatus::Derived => "derived",
        FbxScaleDomainStatus::Rebuilt => "rebuilt",
        FbxScaleDomainStatus::Unsupported => "unsupported",
        FbxScaleDomainStatus::Unverifiable => "unverifiable",
    }
}

fn source_set_coverage_state_name(state: SourceSetCoverageStateV1) -> &'static str {
    match state {
        SourceSetCoverageStateV1::Complete => "complete",
        SourceSetCoverageStateV1::Partial => "partial",
        SourceSetCoverageStateV1::Unavailable => "unavailable",
    }
}

fn push_nonzero_violation(violations: &mut Vec<String>, name: &'static str, value: usize) {
    if value > 0 {
        violations.push(format!("{name}={value}"));
    }
}

fn format_rest_bind_violations(authority: &str, violations: &[String]) -> String {
    format!(
        "FBX rest/bind {authority} rejected: {}",
        violations.join("; ")
    )
}

fn scale_capability_violations(facts: &ScaleCapabilityFacts) -> Vec<String> {
    let mut violations = Vec::new();
    if facts.coverage != ScaleCapabilityCoverage::Complete {
        violations.push("coverage=unavailable".into());
    }
    for (name, present) in [
        ("morphs_present", facts.morphs_present),
        ("morph_weights_present", facts.morph_weights_present),
        ("cameras_present", facts.cameras_present),
        ("lights_present", facts.lights_present),
        ("instancing_present", facts.instancing_present),
        (
            "unregistered_extensions_present",
            facts.unregistered_extensions_present,
        ),
        ("extras_present", facts.extras_present),
        (
            "unknown_source_members_present",
            facts.unknown_source_members_present,
        ),
        (
            "non_triangle_primitives_present",
            facts.non_triangle_primitives_present,
        ),
        (
            "unsupported_vertex_attributes_present",
            facts.unsupported_vertex_attributes_present,
        ),
        (
            "secondary_skin_influences_present",
            facts.secondary_skin_influences_present,
        ),
        (
            "inverse_bind_issues_present",
            facts.inverse_bind_issues_present,
        ),
        (
            "unsafe_accessor_layout_present",
            facts.unsafe_accessor_layout_present,
        ),
        (
            "external_resources_present",
            facts.external_resources_present,
        ),
    ] {
        if present {
            violations.push(format!("{name}=true"));
        }
    }
    violations
}

#[derive(Debug, Default)]
pub(crate) struct AssetConversionFacts {
    pub(crate) truncated_influence_vertex_count: usize,
    pub(crate) discarded_influence_count: usize,
    pub(crate) renormalized_influence_vertex_count: usize,
    pub(crate) rejected_influence_count: usize,
    pub(crate) missing_skin_influence_corner_count: usize,
    pub(crate) pre_weld_vertex_count: usize,
    pub(crate) post_weld_vertex_count: usize,
}

#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct RestBindMeshPayloadCounts {
    pub(crate) unsupported_mesh_count: usize,
    pub(crate) scale_invariant_mesh_count: usize,
}

fn identity(index: usize, element: &ufbx::Element) -> FbxSourceIdentity {
    FbxSourceIdentity {
        source_index: index,
        ufbx_typed_id: element.typed_id,
        ufbx_element_id: element.element_id,
    }
}

pub(crate) fn inventory(
    scene: &ufbx::Scene,
    conversion: &AssetConversionFacts,
    construct_counts: crate::source_facts::SourceConstructCounts,
) -> (FbxScaleCapabilityInventory, RestBindMeshPayloadCounts) {
    let non_triangle_face_count = scene
        .meshes
        .iter()
        .flat_map(|mesh| mesh.faces.iter())
        .filter(|face| face.num_indices != 3)
        .count();
    let triangulated_face_count = scene
        .meshes
        .iter()
        .flat_map(|mesh| mesh.faces.iter())
        .filter(|face| face.num_indices > 3)
        .count();
    let omitted_non_polygon_face_count = scene
        .meshes
        .iter()
        .flat_map(|mesh| mesh.faces.iter())
        .filter(|face| face.num_indices < 3)
        .count();
    let empty_source_meshes = scene
        .meshes
        .iter()
        .enumerate()
        .filter(|(_, mesh)| mesh.faces.is_empty())
        .map(|(index, mesh)| identity(index, &mesh.element))
        .collect::<Vec<_>>();
    let empty_mesh_definition_count = empty_source_meshes.len();
    let generated_normal_mesh_count = scene
        .meshes
        .iter()
        .filter(|mesh| mesh.generated_normals)
        .count();
    let missing_normal_mesh_count = scene
        .meshes
        .iter()
        .filter(|mesh| !mesh.vertex_normal.exists)
        .count();
    let skin_cluster_count = scene
        .skin_deformers
        .iter()
        .map(|skin| skin.clusters.len())
        .sum();
    let empty_skin_deformer_count = scene
        .skin_deformers
        .iter()
        .filter(|skin| skin.clusters.is_empty())
        .count();
    let incomplete_bind_cluster_count = scene
        .skin_clusters
        .iter()
        .filter(|cluster| super::project_cluster_bind(cluster).is_none())
        .count();
    let mut clusters_per_bone = std::collections::BTreeMap::<u32, usize>::new();
    for cluster in &scene.skin_clusters {
        if let (Some(node), Some(_)) = (&cluster.bone_node, super::project_cluster_bind(cluster)) {
            *clusters_per_bone.entry(node.element.typed_id).or_default() += 1;
        }
    }
    let bone_convenience_bind_overwrite_count = clusters_per_bone
        .values()
        .map(|count| count.saturating_sub(1))
        .sum();
    let multiple_skin_deformer_mesh_count = scene
        .meshes
        .iter()
        .filter(|mesh| mesh.skin_deformers.len() > 1)
        .count();
    let dual_quaternion_skin_count = scene
        .skin_deformers
        .iter()
        .filter(|skin| {
            skin.num_dq_weights > 0 || !matches!(skin.skinning_method, ufbx::SkinningMethod::Linear)
        })
        .count();
    let mesh_payload_counts = scene
        .meshes
        .iter()
        .map(|mesh| classify_mesh_source_payload(mesh))
        .fold(
            RestBindMeshPayloadCounts::default(),
            |mut counts, classification| {
                match classification {
                    MeshSourcePayloadClassification::Absent => {}
                    MeshSourcePayloadClassification::ScaleInvariantConversion => {
                        counts.unsupported_mesh_count += 1;
                        counts.scale_invariant_mesh_count += 1;
                    }
                    MeshSourcePayloadClassification::Unsupported => {
                        counts.unsupported_mesh_count += 1;
                    }
                }
                counts
            },
        );
    let unsupported_vertex_payload_mesh_count = mesh_payload_counts.unsupported_mesh_count;
    let shared_mesh_definition_count = scene
        .meshes
        .iter()
        .filter(|mesh| mesh.element.instances.len() > 1)
        .count();
    let uninstanced_source_meshes = scene
        .meshes
        .iter()
        .enumerate()
        .filter(|(_, mesh)| mesh.element.instances.is_empty())
        .map(|(index, mesh)| identity(index, &mesh.element))
        .collect::<Vec<_>>();
    let uninstanced_mesh_definition_count = uninstanced_source_meshes.len();
    let user_defined_property_count = construct_counts.rest_bind.user_defined_property_count;
    let unsupported_source_element_count =
        construct_counts.rest_bind.total_unmodeled_element_count();
    let external_resource_count = scene
        .textures
        .iter()
        .filter(|texture| texture.content.is_empty() && texture.has_file)
        .count()
        + scene
            .videos
            .iter()
            .filter(|video| {
                video.content.is_empty()
                    && (!video.filename.is_empty()
                        || !video.relative_filename.is_empty()
                        || !video.absolute_filename.is_empty())
            })
            .count();
    let compensated_inherit_node_count = scene
        .nodes
        .iter()
        .filter(|node| {
            node.original_inherit_mode != node.inherit_mode
                || node.is_scale_helper
                || node.is_scale_compensate_parent
        })
        .count();

    let stackless_animation_present = scene.anim_stacks.is_empty()
        && (!scene.anim_layers.is_empty()
            || !scene.anim_values.is_empty()
            || !scene.anim_curves.is_empty());
    let animation = if !scene.anim_stacks.is_empty() {
        FbxScaleDomainStatus::Baked
    } else if stackless_animation_present {
        // No take was available to bake, but authored curve/value/layer rows
        // were parsed and discarded by normalized clip extraction.
        FbxScaleDomainStatus::Unsupported
    } else {
        FbxScaleDomainStatus::Absent
    };
    let domains = FbxScaleDomainInventory {
        rest_hierarchy: FbxScaleDomainStatus::Normalized,
        translation_animation: animation,
        rotation_and_scale_animation: animation,
        root_motion_and_velocity: match animation {
            FbxScaleDomainStatus::Baked => FbxScaleDomainStatus::Derived,
            status => status,
        },
        base_mesh_geometry: if scene.meshes.is_empty() {
            FbxScaleDomainStatus::Absent
        } else if uninstanced_mesh_definition_count > 0
            || omitted_non_polygon_face_count > 0
            || empty_mesh_definition_count > 0
        {
            FbxScaleDomainStatus::Unsupported
        } else {
            FbxScaleDomainStatus::Rebuilt
        },
        morphs: if scene.blend_deformers.is_empty()
            && scene.blend_channels.is_empty()
            && scene.blend_shapes.is_empty()
        {
            FbxScaleDomainStatus::Absent
        } else {
            FbxScaleDomainStatus::Unsupported
        },
        skin_binds: if scene.skin_deformers.is_empty() {
            FbxScaleDomainStatus::Absent
        } else if incomplete_bind_cluster_count > 0 || empty_skin_deformer_count > 0 {
            FbxScaleDomainStatus::Unsupported
        } else {
            FbxScaleDomainStatus::Derived
        },
        cameras_and_lights: if scene.cameras.is_empty() && scene.lights.is_empty() {
            FbxScaleDomainStatus::Absent
        } else {
            FbxScaleDomainStatus::Unsupported
        },
        collision_and_custom_data: if unsupported_source_element_count == 0
            && user_defined_property_count == 0
        {
            FbxScaleDomainStatus::Absent
        } else {
            FbxScaleDomainStatus::Unsupported
        },
        other_vertex_and_source_data: if unsupported_vertex_payload_mesh_count > 0
            || uninstanced_mesh_definition_count > 0
            || omitted_non_polygon_face_count > 0
            || empty_mesh_definition_count > 0
            || multiple_skin_deformer_mesh_count > 0
            || dual_quaternion_skin_count > 0
            || conversion.truncated_influence_vertex_count > 0
            || conversion.missing_skin_influence_corner_count > 0
            || conversion.rejected_influence_count > 0
            || !scene.blend_deformers.is_empty()
            || !scene.blend_channels.is_empty()
            || !scene.blend_shapes.is_empty()
            || !scene.cache_deformers.is_empty()
            || !scene.cache_files.is_empty()
        {
            FbxScaleDomainStatus::Unsupported
        } else if !scene.meshes.is_empty() {
            FbxScaleDomainStatus::Rebuilt
        } else {
            FbxScaleDomainStatus::Absent
        },
        out_of_contract_node_transforms: FbxScaleDomainStatus::Normalized,
        animation_targeting_matrix_nodes: animation,
        shared_raw_accessor_payloads: FbxScaleDomainStatus::Unverifiable,
        unreferenced_accessor_payloads: FbxScaleDomainStatus::Unverifiable,
        image_payload_aliases: FbxScaleDomainStatus::Unverifiable,
    };

    let inventory = FbxScaleCapabilityInventory {
        domains,
        coordinate_normalization: FbxCoordinateNormalization {
            original_up_axis: scene.settings.original_axis_up.into(),
            original_unit_meters: scene.settings.original_unit_meters,
            target_right_handed_y_up: true,
            target_unit_meters: 1.0,
            adjust_transforms: matches!(
                scene.metadata.space_conversion,
                ufbx::SpaceConversion::AdjustTransforms
            ),
        },
        animation_takes_baked: true,
        authored_curve_keys_preserved: false,
        animation_take_count: scene.anim_stacks.len(),
        source_animation_curve_count: scene.anim_curves.len(),
        generated_geometry_helper_node_count: scene
            .nodes
            .iter()
            .filter(|node| node.is_geometry_transform_helper)
            .count(),
        generated_scale_helper_node_count: scene
            .nodes
            .iter()
            .filter(|node| node.is_scale_helper)
            .count(),
        inherit_modes_compensated: matches!(
            scene.metadata.inherit_mode_handling,
            ufbx::InheritModeHandling::Compensate
        ),
        compensated_inherit_node_count,
        generated_normal_mesh_count,
        missing_normal_mesh_count,
        skin_deformer_count: scene.skin_deformers.len(),
        skin_cluster_count,
        empty_skin_deformer_count,
        bind_matrix_provenance: FbxBindMatrixProvenance::UfbxConvertedClusterMatrices,
        incomplete_bind_cluster_count,
        bone_convenience_bind_overwrite_count,
        identity_bind_defaults_invented: false,
        truncated_influence_vertex_count: conversion.truncated_influence_vertex_count,
        discarded_influence_count: conversion.discarded_influence_count,
        renormalized_influence_vertex_count: conversion.renormalized_influence_vertex_count,
        rejected_influence_count: conversion.rejected_influence_count,
        missing_skin_influence_corner_count: conversion.missing_skin_influence_corner_count,
        non_triangle_face_count,
        triangulated_face_count,
        omitted_non_polygon_face_count,
        empty_mesh_definition_count,
        empty_source_meshes,
        pre_weld_vertex_count: conversion.pre_weld_vertex_count,
        post_weld_vertex_count: conversion.post_weld_vertex_count,
        multiple_skin_deformer_mesh_count,
        dual_quaternion_skin_count,
        blend_deformer_count: scene.blend_deformers.len(),
        blend_channel_count: scene.blend_channels.len(),
        blend_shape_count: scene.blend_shapes.len(),
        cache_deformer_count: scene.cache_deformers.len(),
        unsupported_vertex_payload_mesh_count,
        camera_count: scene.cameras.len(),
        light_count: scene.lights.len(),
        shared_mesh_definition_count,
        uninstanced_mesh_definition_count,
        uninstanced_source_meshes,
        user_defined_property_count,
        unsupported_source_element_count,
        external_resource_count,
        source_nodes: scene
            .nodes
            .iter()
            .enumerate()
            .map(|(index, node)| identity(index, &node.element))
            .collect(),
        source_meshes: scene
            .meshes
            .iter()
            .enumerate()
            .map(|(index, mesh)| identity(index, &mesh.element))
            .collect(),
        source_skins: scene
            .skin_deformers
            .iter()
            .enumerate()
            .map(|(index, skin)| identity(index, &skin.element))
            .collect(),
    };
    (inventory, mesh_payload_counts)
}

/// Classify every field in `ufbx::Mesh` at one structural boundary. Omitting
/// `..` is deliberate: a ufbx upgrade that adds mesh payload must fail to
/// compile until extraction either models it or this predicate refuses it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MeshSourcePayloadClassification {
    Absent,
    ScaleInvariantConversion,
    Unsupported,
}

fn classify_mesh_source_payload(mesh: &ufbx::Mesh) -> MeshSourcePayloadClassification {
    let ufbx::Mesh {
        element: _,
        num_vertices: _,
        num_indices: _,
        num_faces: _,
        num_triangles: _,
        num_edges: _,
        max_face_triangles: _,
        num_empty_faces: _,
        num_point_faces: _,
        num_line_faces: _,
        faces: _,
        // Authored face/edge members are not retained by triangle extraction.
        face_smoothing,
        face_material: _,
        face_group,
        face_hole,
        edges,
        edge_smoothing,
        edge_crease,
        edge_visibility,
        vertex_indices: _,
        vertices: _,
        vertex_first_index: _,
        vertex_position: _,
        vertex_normal: _,
        vertex_uv: _,
        vertex_tangent,
        vertex_bitangent,
        vertex_color,
        vertex_crease,
        uv_sets,
        color_sets,
        materials: _,
        face_groups,
        // Mesh parts and skinned views are parser-derived indexes/results.
        material_parts: _,
        face_group_parts: _,
        material_part_usage_order: _,
        skinned_is_local: _,
        skinned_position: _,
        skinned_normal: _,
        // Deformer kinds have dedicated inventory counters.
        skin_deformers: _,
        blend_deformers: _,
        cache_deformers: _,
        all_deformers: _,
        subdivision_preview_levels,
        subdivision_render_levels,
        subdivision_display_mode,
        subdivision_boundary,
        subdivision_uv_boundary,
        // Winding conversion and generated-normal state are consumed/counted.
        reversed_winding: _,
        generated_normals: _,
        subdivision_evaluated,
        subdivision_result,
        from_tessellated_nurbs,
    } = mesh;

    // These fields are produced by ufbx's explicit subdivision/NURBS
    // evaluators rather than by the raw polygon-mesh load used here. Keep
    // them outside the patch-release allowlist until a reachable fixture can
    // prove their normalized handoff independently.
    let unsupported_generated_payload_present =
        !matches!(subdivision_uv_boundary, ufbx::SubdivisionBoundary::Default)
            || *subdivision_evaluated
            || subdivision_result.is_some()
            || *from_tessellated_nurbs;
    let scale_invariant_conversion_facts_present = !face_smoothing.is_empty()
        || !face_group.is_empty()
        || !face_hole.is_empty()
        || !edges.is_empty()
        || !edge_smoothing.is_empty()
        || !edge_crease.is_empty()
        || !edge_visibility.is_empty()
        || vertex_tangent.exists
        || vertex_bitangent.exists
        || vertex_color.exists
        || vertex_crease.exists
        || uv_sets.len() > 1
        || !color_sets.is_empty()
        || !face_groups.is_empty()
        || *subdivision_preview_levels > 0
        || *subdivision_render_levels > 0
        || !matches!(
            subdivision_display_mode,
            ufbx::SubdivisionDisplayMode::Disabled
        )
        || !matches!(subdivision_boundary, ufbx::SubdivisionBoundary::Default);

    if unsupported_generated_payload_present {
        MeshSourcePayloadClassification::Unsupported
    } else if scale_invariant_conversion_facts_present {
        MeshSourcePayloadClassification::ScaleInvariantConversion
    } else {
        MeshSourcePayloadClassification::Absent
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use animsmith_core::{
        InputIdentity, RawSourceFactsBuilderV1, SourceConstructFactV1, SourceFactDomainV1,
        SourceFormatV1, SourceLoaderDispositionV1, SourceLogicalLocatorV1, SourceProvenanceV1,
        SourceResourceKindV1, SourceResourceReferenceV1, SourceTextV1,
    };
    use std::path::PathBuf;

    fn captured_with(configure: impl FnOnce(&mut RawSourceFactsBuilderV1)) -> FbxScaleSource {
        captured_with_counts(configure, |_| {})
    }

    fn captured_with_counts(
        configure: impl FnOnce(&mut RawSourceFactsBuilderV1),
        configure_counts: impl FnOnce(&mut crate::source_facts::RestBindSourceConstructCounts),
    ) -> FbxScaleSource {
        let fixture =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testdata/rigged_triangle.fbx");
        let baseline = crate::load_scale_source(&fixture).expect("checked-in FBX fixture loads");
        let document = baseline.document().clone();
        let mut inventory = baseline.inventory().clone();
        let mut rest_bind_construct_counts = baseline.rest_bind_construct_counts;
        let rest_bind_scale_invariant_payload_mesh_count =
            baseline.rest_bind_scale_invariant_payload_mesh_count;
        configure_counts(&mut rest_bind_construct_counts);
        inventory.user_defined_property_count =
            rest_bind_construct_counts.user_defined_property_count;
        inventory.unsupported_source_element_count =
            rest_bind_construct_counts.total_unmodeled_element_count();
        inventory.domains.collision_and_custom_data = if inventory.user_defined_property_count == 0
            && inventory.unsupported_source_element_count == 0
        {
            FbxScaleDomainStatus::Absent
        } else {
            FbxScaleDomainStatus::Unsupported
        };
        let identity: InputIdentity = baseline.source_facts().primary_identity().clone();
        let mut builder = RawSourceFactsBuilderV1::new(SourceFormatV1::Fbx, identity);
        configure(&mut builder);
        let source = builder.finish(document).expect("synthetic raw facts bind");
        FbxScaleSource {
            source,
            inventory,
            rest_bind_construct_counts,
            rest_bind_scale_invariant_payload_mesh_count,
        }
    }

    fn parser_provenance(path: &str) -> SourceProvenanceV1 {
        SourceProvenanceV1::parser_projected(
            SourceLogicalLocatorV1::fbx_parser_path(path).expect("test parser path is valid"),
        )
    }

    fn complete_captured_source() -> FbxScaleSource {
        captured_with(|builder| {
            builder.mark_complete(SourceFactDomainV1::Constructs);
            builder.mark_complete(SourceFactDomainV1::Resources);
        })
    }

    #[test]
    fn source_aware_rest_bind_admits_only_reconciled_scale_invariant_conversion_facts() {
        let mut source = complete_captured_source();
        source.inventory.domains.other_vertex_and_source_data = FbxScaleDomainStatus::Unsupported;
        source.inventory.unsupported_vertex_payload_mesh_count = 1;
        source.rest_bind_scale_invariant_payload_mesh_count = 1;
        source.inventory.truncated_influence_vertex_count = 1;
        source.inventory.discarded_influence_count = 2;
        source.inventory.renormalized_influence_vertex_count = 1;
        source.inventory.rejected_influence_count = 1;
        source.inventory.non_triangle_face_count = 1;
        source.inventory.triangulated_face_count = 1;
        source.inventory.post_weld_vertex_count = source.inventory.pre_weld_vertex_count - 1;

        assert!(
            rest_bind_capability_facts(source.inventory()).is_err(),
            "a detached public inventory cannot prove these conversions are scale-invariant"
        );
        let facts = rest_bind_capability_facts_for_source(&source)
            .expect("same-parse enumerated conversion facts are admissible");
        assert!(!facts.non_triangle_primitives_present);
        assert!(!facts.unsupported_vertex_attributes_present);
        assert!(!facts.secondary_skin_influences_present);

        source.rest_bind_scale_invariant_payload_mesh_count = 0;
        assert_eq!(
            rest_bind_capability_facts_for_source(&source).unwrap_err(),
            concat!(
                "FBX rest/bind capability inventory rejected: ",
                "unsupported_vertex_payload_mesh_count=1!=scale_invariant_source:0"
            ),
            "an unclassified payload cannot hide inside the public aggregate"
        );

        source.rest_bind_scale_invariant_payload_mesh_count = 1;
        source.inventory.missing_skin_influence_corner_count = 1;
        assert_eq!(
            rest_bind_capability_facts_for_source(&source).unwrap_err(),
            concat!(
                "FBX rest/bind capability inventory rejected: ",
                "missing_skin_influence_corner_count=1"
            ),
            "conversion evidence never overrides missing effective skin coverage"
        );
    }

    #[test]
    fn source_aware_rest_bind_rejects_partial_relevant_coverage() {
        for (source, expected) in [
            (
                captured_with(|builder| {
                    builder.mark_budget_exceeded(SourceFactDomainV1::Constructs);
                    builder.mark_complete(SourceFactDomainV1::Resources);
                }),
                "FBX rest/bind raw-source facts rejected: raw_source.constructs.coverage=partial",
            ),
            (
                captured_with(|builder| {
                    builder.mark_complete(SourceFactDomainV1::Constructs);
                    builder.mark_budget_exceeded(SourceFactDomainV1::Resources);
                }),
                "FBX rest/bind raw-source facts rejected: raw_source.resources.coverage=partial",
            ),
        ] {
            assert_eq!(
                rest_bind_capability_facts_for_source(&source).unwrap_err(),
                expected,
                "partial construct/resource coverage must name the exact raw authority"
            );
        }
    }

    #[test]
    fn source_aware_rest_bind_distinguishes_irrelevant_and_unsupported_shared_domains() {
        for kind in [
            SourceConstructKindV1::UnknownElement,
            SourceConstructKindV1::Extension,
        ] {
            let source = captured_with(|builder| {
                builder.push_construct(
                    SourceConstructFactV1::new(
                        0,
                        kind,
                        SourceTextV1::new("synthetic").expect("bounded test name"),
                        false,
                        1,
                        SourceLoaderDispositionV1::Unsupported,
                        parser_provenance("fbx:synthetic/construct"),
                    )
                    .expect("positive test construct"),
                );
                builder.mark_complete(SourceFactDomainV1::Constructs);
                builder.mark_complete(SourceFactDomainV1::Resources);
            });
            let error = rest_bind_capability_facts_for_source(&source).unwrap_err();
            let expected = match kind {
                SourceConstructKindV1::UnknownElement => "unknown_element",
                SourceConstructKindV1::Extension => "extension",
                SourceConstructKindV1::CustomProperty => unreachable!(),
            };
            assert_eq!(
                error,
                format!(
                    "FBX rest/bind raw-source facts rejected: raw_source.construct={expected}(synthetic; count=1)"
                )
            );
        }

        let custom_and_external = captured_with_counts(
            |builder| {
                builder.push_construct(
                    SourceConstructFactV1::new(
                        0,
                        SourceConstructKindV1::CustomProperty,
                        SourceTextV1::new("fbx:user-defined-properties")
                            .expect("bounded test name"),
                        false,
                        1,
                        SourceLoaderDispositionV1::Unsupported,
                        parser_provenance("fbx:synthetic/property"),
                    )
                    .expect("positive custom-property row"),
                );
                builder.mark_complete(SourceFactDomainV1::Constructs);
                builder.push_resource(SourceResourceReferenceV1::new(
                    0,
                    SourceResourceKindV1::Texture,
                    0,
                    SourceResourceLocatorV1::classify("texture.png"),
                    SourceLoaderDispositionV1::Unknown,
                    parser_provenance("fbx:textures/0/filename"),
                ));
                builder.mark_complete(SourceFactDomainV1::Resources);
            },
            |counts| counts.user_defined_property_count = 1,
        );
        let facts = rest_bind_capability_facts_for_source(&custom_and_external)
            .expect("custom properties and external images are not scale-bearing");
        assert!(!facts.extras_present);
        assert!(!facts.external_resources_present);
        assert!(facts.is_supported_for(
            animsmith_core::scale::ScaleOperation::RestBindUniformScale {
                source_skin_index: 0,
                source_root_node_index: 1,
                expected_factor: 0.01,
            }
        ));
    }
}