cadmpeg-codec-f3d 0.1.4

Decode and encode Fusion .f3d B-rep, design, and appearance data.
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
// SPDX-License-Identifier: Apache-2.0
//! Build B-rep topology and geometry from a framed SAB record table.
//!
//! [`decode`] follows the topology chain from bodies through vertices and
//! points. It creates analytic carriers for planes, cylinders, cones, spheres,
//! tori, lines, circles, and ellipses. [`crate::nurbs`] supplies cached NURBS
//! surfaces, 3D curves, and pcurves for spline and procedural records.
//!
//! Faces retain their loops and trims when a referenced surface has no decoded
//! shape; the emitted [`SurfaceGeometry::Unknown`] links to the corresponding
//! [`UnknownRecord`]. Edges retain vertices and parameter ranges when their 3D
//! curve carrier is unavailable. [`Stats`] records these transfer losses for
//! the decode report.
//!
//! ASM model-space lengths become millimetres. Unit vectors, ratios, angles,
//! knots, weights, and UV parameters keep their native scale.

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

use cadmpeg_ir::attributes::{AttributeTarget, AttributeValue, SourceAttribute};
use cadmpeg_ir::design::{PersistentDesignLink, SketchCurveLink};
use cadmpeg_ir::geometry::{
    BlendSupport, Curve, CurveGeometry, NurbsCurve, Pcurve, PcurveGeometry, ProceduralCurve,
    ProceduralSurface, ProceduralSurfaceDefinition, Surface, SurfaceGeometry,
};
use cadmpeg_ir::ids::{
    AttributeId, BodyId, CoedgeId, CurveId, EdgeId, FaceId, LoopId, PcurveId, PointId, RegionId,
    ShellId, SurfaceId, UnknownId, VertexId,
};
use cadmpeg_ir::math::{Point3, Vector3};
use cadmpeg_ir::topology::{
    Body, Coedge, Color, Edge, Face, Loop, Point, Region, Sense, Shell, Vertex,
};
use cadmpeg_ir::unknown::UnknownRecord;

use crate::asm_header;
use crate::nurbs;
use crate::sab::{Record, Token};

/// Millimetres per ASM model-space length unit (centimetres).
const LEN_TO_MM: f64 = 10.0;

/// The decoded B-rep graph plus loss accounting.
#[derive(Default)]
pub struct Brep {
    /// Bodies.
    pub bodies: Vec<Body>,
    /// Regions.
    pub regions: Vec<Region>,
    /// Shells.
    pub shells: Vec<Shell>,
    /// Faces.
    pub faces: Vec<Face>,
    /// Loops.
    pub loops: Vec<Loop>,
    /// Coedges.
    pub coedges: Vec<Coedge>,
    /// Edges.
    pub edges: Vec<Edge>,
    /// Vertices.
    pub vertices: Vec<Vertex>,
    /// Points.
    pub points: Vec<Point>,
    /// Analytic surface carriers.
    pub surfaces: Vec<Surface>,
    /// Analytic curve carriers.
    pub curves: Vec<Curve>,
    /// Parameter-space curve carriers.
    pub pcurves: Vec<Pcurve>,
    /// Native procedural definitions for solved surface carriers.
    pub procedural_surfaces: Vec<ProceduralSurface>,
    /// Native procedural definitions for solved curve caches.
    pub procedural_curves: Vec<ProceduralCurve>,
    /// Typed sketch-curve provenance links.
    pub sketch_curve_links: Vec<SketchCurveLink>,
    /// Persistent design identifiers attached to solved entities.
    pub persistent_design_links: Vec<PersistentDesignLink>,
    /// Native ASM body key by emitted body id, used by Design-side joins.
    pub body_keys: HashMap<BodyId, u64>,
    /// Linked source-native attributes.
    pub attributes: Vec<SourceAttribute>,
    /// Undecoded carrier records preserved verbatim.
    pub unknowns: Vec<UnknownRecord>,
    /// Loss accounting for the report.
    pub stats: Stats,
    /// Source locations for emitted B-rep and synthetic child records.
    pub annotation_records: Vec<AnnotationRecord>,
}

/// One sparse v1 annotation produced while SAB record offsets are available.
pub struct AnnotationRecord {
    /// Globally unique IR entity id.
    pub id: String,
    /// Byte offset in the decompressed ASM stream.
    pub offset: u64,
    /// Source SAB record name.
    pub tag: String,
    /// Serialized fields whose values were canonically derived.
    pub derived_fields: Vec<&'static str>,
}

/// Counts used to construct the B-rep loss report.
#[derive(Default)]
pub struct Stats {
    /// Faces resting on a spline/procedural surface whose shape was not decoded
    /// into a typed carrier; emitted with an unknown-geometry surface.
    pub unknown_surface_faces: usize,
    /// Spline surface records whose cached B-spline block was decoded into a
    /// NURBS carrier.
    pub nurbs_surfaces: usize,
    /// Procedural curve records whose cached 3D B-spline block was decoded into
    /// a NURBS carrier.
    pub nurbs_curves: usize,
    /// Edges whose 3D curve is a procedural carrier (emitted with no curve).
    pub procedural_curve_edges: usize,
    /// Coedges that carried an explicit UV pcurve ref whose carrier could not
    /// be decoded.
    pub undecoded_pcurve_refs: usize,
    /// Procedural blends for which only one of two support families resolved.
    pub partial_procedural_supports: usize,
    /// Record names in the active slice that were neither topology nor a
    /// decoded/preserved carrier (attributes, transforms, refinements, …).
    pub other_records: usize,
    /// Residual record counts by full record name.
    pub other_record_kinds: std::collections::BTreeMap<String, usize>,
}

// ---- geometry carrier decode -------------------------------------------------

/// Ordered typed values pulled from a carrier record's payload.
struct Carrier {
    positions: Vec<[f64; 3]>,
    vectors: Vec<[f64; 3]>,
    doubles: Vec<f64>,
}

fn collect_carrier(rec: &Record) -> Carrier {
    let mut c = Carrier {
        positions: Vec::new(),
        vectors: Vec::new(),
        doubles: Vec::new(),
    };
    for t in &rec.tokens {
        match t {
            Token::Position(p) => c.positions.push(*p),
            Token::Vector3(v) => c.vectors.push(*v),
            Token::Double(d) => c.doubles.push(*d),
            _ => {}
        }
    }
    c
}

fn scale_point(p: [f64; 3]) -> Point3 {
    Point3::new(p[0] * LEN_TO_MM, p[1] * LEN_TO_MM, p[2] * LEN_TO_MM)
}

fn vec3(v: [f64; 3]) -> Vector3 {
    Vector3::new(v[0], v[1], v[2])
}

fn norm3(v: [f64; 3]) -> f64 {
    (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
}

/// Return `v` normalized to unit length, or `v` unchanged if it is degenerate
/// (validation flags a degenerate direction rather than this hiding it).
fn unit(v: [f64; 3]) -> Vector3 {
    let n = norm3(v);
    if n > f64::EPSILON {
        Vector3::new(v[0] / n, v[1] / n, v[2] / n)
    } else {
        vec3(v)
    }
}

/// Whether a record name heads an analytic surface carrier.
fn is_analytic_surface(head: &str) -> bool {
    matches!(head, "plane" | "cone" | "sphere" | "torus")
}

/// Whether a record name heads an analytic curve carrier.
fn is_analytic_curve(head: &str) -> bool {
    matches!(head, "straight" | "ellipse" | "degenerate_curve")
}

/// Decode an analytic surface carrier. Signed sphere and torus radii remain in
/// the IR because they are part of the ASM carrier semantics.
pub(crate) fn decode_surface(rec: &Record) -> Option<(SurfaceGeometry, bool)> {
    let c = collect_carrier(rec);
    let origin = *c.positions.first()?;
    match rec.head.as_str() {
        "plane" => {
            let normal = *c.vectors.first()?;
            let normal = unit(normal);
            let u_axis = c
                .vectors
                .get(1)
                .map_or_else(|| deterministic_ref_direction(normal), |axis| unit(*axis));
            Some((
                SurfaceGeometry::Plane {
                    origin: scale_point(origin),
                    normal,
                    u_axis,
                },
                false,
            ))
        }
        "cone" => {
            let axis = *c.vectors.first()?;
            let axis = unit(axis);
            let major = c.vectors.get(1).copied();
            // Doubles are (ratio, sine, cosine, u_scale). `ratio` (minor/major
            // of an elliptical cone) is not modeled by the IR's circular cone
            // carrier; all corpus cones are circular (ratio 1). `sine` selects
            // cylinder vs cone. The base radius is the major-axis vector's
            // magnitude; the trailing `u_scale` double is the u-parameter
            // scale, which usually coincides with the radius but diverges on
            // offset-derived surfaces. The signed slope `sine / cosine` is the
            // radius change per unit axis distance, and a negative `cosine`
            // points the surface normal toward the axis.
            let sine = *c.doubles.get(1).unwrap_or(&0.0);
            let cosine = *c.doubles.get(2).unwrap_or(&1.0);
            let u_scale = c.doubles.get(3).copied();
            let radius = major
                .map(|vector| norm3(vector) * LEN_TO_MM)
                .filter(|radius| *radius > f64::EPSILON)
                .or_else(|| u_scale.map(|r| r * LEN_TO_MM))?;
            let ref_direction = major.map_or_else(|| deterministic_ref_direction(axis), unit);
            if sine.abs() <= f64::EPSILON {
                Some((
                    SurfaceGeometry::Cylinder {
                        origin: scale_point(origin),
                        axis,
                        ref_direction,
                        radius,
                    },
                    cosine < 0.0,
                ))
            } else {
                // The IR cone's radius grows along `+axis`; a negative native
                // slope shrinks it, so the axis flips to compensate. The
                // outward normal is invariant under the flip; the inward
                // normal of a negative `cosine` folds into the face sense.
                let axis = if sine * cosine < 0.0 {
                    Vector3::new(-axis.x, -axis.y, -axis.z)
                } else {
                    axis
                };
                Some((
                    SurfaceGeometry::Cone {
                        origin: scale_point(origin),
                        axis,
                        ref_direction,
                        radius,
                        half_angle: sine.abs().asin(),
                    },
                    cosine < 0.0,
                ))
            }
        }
        "sphere" => {
            let signed = *c.doubles.first()?;
            let polar_axis = c.vectors.get(1).or_else(|| c.vectors.first()).copied()?;
            let polar_axis = unit(polar_axis);
            let equator = c
                .vectors
                .first()
                .filter(|_| c.vectors.len() > 1)
                .map_or_else(
                    || deterministic_ref_direction(polar_axis),
                    |direction| unit(*direction),
                );
            Some((
                SurfaceGeometry::Sphere {
                    center: scale_point(origin),
                    axis: polar_axis,
                    ref_direction: equator,
                    radius: signed * LEN_TO_MM,
                },
                false,
            ))
        }
        "torus" => {
            let axis = *c.vectors.first()?;
            let axis = unit(axis);
            let ref_direction = c.vectors.get(1).map_or_else(
                || deterministic_ref_direction(axis),
                |direction| unit(*direction),
            );
            let major = *c.doubles.first()?;
            let minor = *c.doubles.get(1)?;
            Some((
                SurfaceGeometry::Torus {
                    center: scale_point(origin),
                    axis,
                    ref_direction,
                    major_radius: major * LEN_TO_MM,
                    minor_radius: minor * LEN_TO_MM,
                },
                false,
            ))
        }
        _ => None,
    }
}

fn deterministic_ref_direction(axis: Vector3) -> Vector3 {
    let candidates = [
        Vector3::new(1.0, 0.0, 0.0),
        Vector3::new(0.0, 1.0, 0.0),
        Vector3::new(0.0, 0.0, 1.0),
    ];
    let basis = candidates
        .into_iter()
        .min_by(|a, b| {
            let a_dot = (a.x * axis.x + a.y * axis.y + a.z * axis.z).abs();
            let b_dot = (b.x * axis.x + b.y * axis.y + b.z * axis.z).abs();
            a_dot.total_cmp(&b_dot)
        })
        .expect("fixed candidate set is non-empty");
    let dot = basis.x * axis.x + basis.y * axis.y + basis.z * axis.z;
    let projected = Vector3::new(
        basis.x - dot * axis.x,
        basis.y - dot * axis.y,
        basis.z - dot * axis.z,
    );
    let length = projected.norm();
    Vector3::new(
        projected.x / length,
        projected.y / length,
        projected.z / length,
    )
}

/// Decode an analytic curve carrier.
pub(crate) fn decode_curve(rec: &Record) -> Option<CurveGeometry> {
    let carrier = collect_carrier(rec);
    let base = *carrier.positions.first()?;
    match rec.head.as_str() {
        "straight" => Some(CurveGeometry::Line {
            origin: scale_point(base),
            direction: unit(*carrier.vectors.first()?),
        }),
        "ellipse" => {
            let axis = *carrier.vectors.first()?;
            let reference = *carrier.vectors.get(1)?;
            let ratio = *carrier.doubles.first()?;
            let major_radius = norm3(reference) * LEN_TO_MM;
            if (ratio.abs() - 1.0).abs() <= f64::EPSILON {
                Some(CurveGeometry::Circle {
                    center: scale_point(base),
                    axis: unit(axis),
                    ref_direction: unit(reference),
                    radius: major_radius,
                })
            } else {
                Some(CurveGeometry::Ellipse {
                    center: scale_point(base),
                    axis: unit(axis),
                    major_direction: unit(reference),
                    major_radius,
                    minor_radius: major_radius * ratio.abs(),
                })
            }
        }
        "degenerate_curve" => Some(CurveGeometry::Degenerate {
            point: scale_point(base),
        }),
        _ => None,
    }
}

fn sense_at(rec: &Record, i: usize) -> Sense {
    match rec.chunk(i) {
        Some(Token::True) => Sense::Reversed,
        _ => Sense::Forward,
    }
}

/// The record-level sense bit of an `intcurve` or `spline` carrier: the boolean
/// token immediately before the record's subtype scope ([spec §7.6](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/f3d.md#76-intcurve-and-spline-subtypes)). `true`
/// marks geometry as the reverse of its cached definition. A reversed intcurve
/// negates the cache parameterization (`C(t) = cache(-t)`), and a reversed
/// spline surface flips the cache normal.
fn record_reversed(rec: &Record) -> bool {
    for token in &rec.tokens {
        match token {
            Token::True => return true,
            Token::False | Token::SubtypeOpen => return false,
            _ => {}
        }
    }
    false
}

/// Reparameterize a cached B-spline to its record's reversed sense,
/// `C'(t) = C(-t)`, by reversing poles and weights and negating reversed knots.
fn reverse_nurbs_curve(curve: &mut NurbsCurve) {
    curve.control_points.reverse();
    if let Some(weights) = curve.weights.as_mut() {
        weights.reverse();
    }
    curve.knots.reverse();
    for knot in &mut curve.knots {
        *knot = -*knot;
    }
}

/// Reverse a curve carrier to its opposite orientation, `C'(t) = C(-t)`.
/// Lines negate their direction, conics negate their plane normal (flipping
/// the angular sweep while keeping the zero-angle direction), and B-splines
/// reverse poles and knots. Carriers without an orientation pass through.
fn reverse_curve_geometry(geometry: &mut CurveGeometry) {
    match geometry {
        CurveGeometry::Line { direction, .. } => {
            *direction = Vector3::new(-direction.x, -direction.y, -direction.z);
        }
        CurveGeometry::Circle { axis, .. } | CurveGeometry::Ellipse { axis, .. } => {
            *axis = Vector3::new(-axis.x, -axis.y, -axis.z);
        }
        CurveGeometry::Nurbs(curve) => reverse_nurbs_curve(curve),
        _ => {}
    }
}

fn double_at(rec: &Record, i: usize) -> Option<f64> {
    match rec.chunk(i) {
        Some(Token::Double(d)) => Some(*d),
        _ => None,
    }
}

/// Decode a framed active slice into the IR B-rep graph.
///
/// `stream` names the source ZIP entry for provenance. Ids are minted as
/// `f3d:brep:entity#<record-index>`, unique across the `RecordTable`.
pub fn decode(records: &[Record], bytes: &[u8], _stream: &str) -> Brep {
    let mut out = Brep::default();

    let id = |i: i64| format!("f3d:brep:entity#{i}");
    // Index records by RecordTable index (== position for a framed slice).
    let by_index: HashMap<i64, &Record> = records.iter().map(|r| (r.index as i64, r)).collect();
    let header_scale = asm_header::parse(bytes)
        .and_then(|header| header.scale)
        .unwrap_or(1.0);

    let attribute_color = |entity: &Record| attribute_chain_color(entity, &by_index);

    // Pass 1: classify carriers and decode analytic geometry.
    let mut surface_geo: HashMap<i64, (SurfaceGeometry, bool)> = HashMap::new();
    let mut procedural_surface_defs = HashMap::new();
    let mut curve_geo: HashMap<i64, CurveGeometry> = HashMap::new();
    let mut procedural_curve_defs = HashMap::new();
    for r in records {
        if is_analytic_surface(&r.head) {
            if let Some(g) = decode_surface(r) {
                surface_geo.insert(r.index as i64, g);
            }
        } else if is_analytic_curve(&r.head) {
            if let Some(g) = decode_curve(r) {
                curve_geo.insert(r.index as i64, g);
            }
        }
    }
    // Carriers whose native normal points opposite the IR carrier's normal;
    // the reversal folds into the referencing faces' senses.
    let inward_normal_surfaces: HashSet<i64> = surface_geo
        .iter()
        .filter(|(_, (_, inward))| *inward)
        .map(|(&index, _)| index)
        .collect();

    // Pass 2: keep every face whose surface reference resolves to a record,
    // then pull its supporting graph in by shell-reachability. A face on a
    // decoded analytic surface gets that carrier; a face on a spline/procedural
    // surface keeps its topology and gets an unknown-geometry carrier linking to
    // the preserved bytes.
    let mut kept_faces: HashSet<i64> = HashSet::new();
    let mut kept_loops: HashSet<i64> = HashSet::new();
    let mut kept_coedges: HashSet<i64> = HashSet::new();
    let mut kept_edges: HashSet<i64> = HashSet::new();
    let mut kept_vertices: HashSet<i64> = HashSet::new();
    let mut kept_points: HashSet<i64> = HashSet::new();
    let mut kept_surfaces: HashSet<i64> = HashSet::new();
    let mut unknown_surface_records: HashSet<i64> = HashSet::new();
    let mut kept_curves: HashSet<i64> = HashSet::new();
    let mut kept_pcurves: HashSet<i64> = HashSet::new();
    let mut pcurve_geo: HashMap<i64, PcurveGeometry> = HashMap::new();
    // Undecoded carriers referenced by real topology, to preserve as unknowns.
    let mut undecoded_carriers: HashSet<i64> = HashSet::new();

    for r in records {
        if r.head != "face" {
            continue;
        }
        let Some(surf_ref) = r.ref_at(7) else {
            continue;
        };
        let Some(surf_rec) = by_index.get(&surf_ref) else {
            // Dangling surface reference: a face without a resolvable surface
            // cannot be emitted (the IR requires one), so it is dropped.
            continue;
        };
        kept_faces.insert(r.index as i64);
        // A non-analytic surface may still carry a decodable B-spline face cache.
        if let std::collections::hash_map::Entry::Vacant(e) = surface_geo.entry(surf_ref) {
            if let Some(ns) =
                nurbs::decode_surface_cache_resolving_refs(record_slice(surf_rec, bytes), bytes)
            {
                e.insert((SurfaceGeometry::Nurbs(ns), false));
                out.stats.nurbs_surfaces += 1;
                if let Some(procedural) = nurbs::decode_procedural_surface_resolving_refs(
                    record_slice(surf_rec, bytes),
                    bytes,
                ) {
                    procedural_surface_defs.insert(surf_ref, procedural);
                }
            }
        }
        if surface_geo.contains_key(&surf_ref) {
            kept_surfaces.insert(surf_ref);
        } else {
            unknown_surface_records.insert(surf_ref);
            undecoded_carriers.insert(surf_ref);
            out.stats.unknown_surface_faces += 1;
        }
    }

    // Walk each kept face's loops and coedge rings, collecting supporting graph.
    for &face_idx in &kept_faces.iter().copied().collect::<Vec<_>>() {
        let Some(face) = by_index.get(&face_idx) else {
            continue;
        };
        let mut loop_ref = face.ref_at(4);
        let mut loop_guard = HashSet::new();
        while let Some(li) = loop_ref {
            if !loop_guard.insert(li) {
                break;
            }
            let Some(lp) = by_index.get(&li) else { break };
            if lp.head != "loop" {
                break;
            }
            kept_loops.insert(li);
            // Ring-walk coedges via chunk[3] = next.
            if let Some(first_ce) = lp.ref_at(4) {
                let mut ce_ref = Some(first_ce);
                let mut ce_guard = HashSet::new();
                while let Some(ci) = ce_ref {
                    if !ce_guard.insert(ci) {
                        break;
                    }
                    let Some(ce) = by_index.get(&ci) else { break };
                    if ce.head != "coedge" {
                        break;
                    }
                    kept_coedges.insert(ci);
                    if let Some(pc) = ce.ref_at(10) {
                        if let Some(prec) = by_index.get(&pc) {
                            let decoded = nurbs::decode_pcurve_cache_resolving_refs(
                                record_slice(prec, bytes),
                                bytes,
                            )
                            .or_else(|| {
                                prec.ref_at(4)
                                    .and_then(|reference| by_index.get(&reference))
                                    .and_then(|intcurve| {
                                        nurbs::decode_intcurve_pcurve_cache_resolving_refs(
                                            record_slice(intcurve, bytes),
                                            bytes,
                                        )
                                    })
                            });
                            if let Some(decoded) = decoded {
                                pcurve_geo.insert(
                                    pc,
                                    PcurveGeometry::Nurbs {
                                        degree: decoded.degree,
                                        knots: decoded.knots,
                                        control_points: decoded.control_points,
                                        weights: decoded.weights,
                                        periodic: decoded.periodic,
                                    },
                                );
                                kept_pcurves.insert(pc);
                            } else {
                                out.stats.undecoded_pcurve_refs += 1;
                            }
                        } else {
                            out.stats.undecoded_pcurve_refs += 1;
                        }
                    }
                    if let Some(ei) = ce.ref_at(6) {
                        if let Some(edge) = by_index.get(&ei) {
                            // An edge is shared by two coedges; process (and
                            // count its curve loss) only the first time it is
                            // reached so shared edges are not double-counted.
                            if edge.head == "edge" && kept_edges.insert(ei) {
                                for slot in [3usize, 5] {
                                    if let Some(vi) = edge.ref_at(slot) {
                                        if let Some(v) = by_index.get(&vi) {
                                            if v.head == "vertex" {
                                                kept_vertices.insert(vi);
                                                if let Some(pi) = v.ref_at(5) {
                                                    kept_points.insert(pi);
                                                }
                                            }
                                        }
                                    }
                                }
                                match edge.ref_at(8) {
                                    Some(cv) if curve_geo.contains_key(&cv) => {
                                        kept_curves.insert(cv);
                                    }
                                    Some(cv) => {
                                        if let Some(crec) = by_index.get(&cv) {
                                            // A procedural curve carries an inline
                                            // 3D B-spline cache in most subtypes.
                                            if let Some(decoded) =
                                                nurbs::decode_procedural_curve_resolving_refs(
                                                    record_slice(crec, bytes),
                                                    bytes,
                                                )
                                            {
                                                let mut curve = decoded.curve;
                                                // A reversed intcurve parameterizes
                                                // as the negation of its cache; the
                                                // edge's stored range is on the
                                                // reversed parameterization.
                                                if record_reversed(crec) {
                                                    reverse_nurbs_curve(&mut curve);
                                                }
                                                curve_geo.insert(cv, CurveGeometry::Nurbs(curve));
                                                procedural_curve_defs.insert(
                                                    cv,
                                                    (
                                                        decoded.native_kind,
                                                        decoded.definition,
                                                        decoded.vector_offset,
                                                        decoded.subset,
                                                        decoded.compound,
                                                        decoded.embedded_two_sided_offset,
                                                        decoded.embedded_intersection,
                                                        decoded.embedded_three_surface_intersection,
                                                        decoded.embedded_surface_curve,
                                                        decoded.embedded_projection,
                                                        decoded.cache_fit_tolerance,
                                                    ),
                                                );
                                                out.stats.nurbs_curves += 1;
                                                kept_curves.insert(cv);
                                            } else {
                                                undecoded_carriers.insert(cv);
                                                out.stats.procedural_curve_edges += 1;
                                            }
                                        }
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                    ce_ref = ce.ref_at(3);
                    if ce_ref == Some(first_ce) {
                        break;
                    }
                }
            }
            loop_ref = lp.ref_at(3);
        }
    }

    let mut wire_edges_by_shell = HashMap::<i64, Vec<i64>>::new();
    for shell in records.iter().filter(|record| record.head == "shell") {
        let shell_index = shell.index as i64;
        let mut wire_ref = shell.ref_at(6);
        let mut wire_guard = HashSet::new();
        while let Some(wire_index) = wire_ref.filter(|index| wire_guard.insert(*index)) {
            let Some(wire) = by_index
                .get(&wire_index)
                .filter(|record| record.head == "wire")
            else {
                break;
            };
            if let Some(first_coedge) = wire.ref_at(4) {
                let mut coedge_ref = Some(first_coedge);
                let mut coedge_guard = HashSet::new();
                while let Some(coedge_index) =
                    coedge_ref.filter(|index| coedge_guard.insert(*index))
                {
                    let Some(coedge) = by_index
                        .get(&coedge_index)
                        .filter(|record| record.head == "coedge")
                    else {
                        break;
                    };
                    if let Some(edge_index) = coedge.ref_at(6) {
                        let edges = wire_edges_by_shell.entry(shell_index).or_default();
                        if !edges.contains(&edge_index) {
                            edges.push(edge_index);
                        }
                        if let Some(edge) = by_index.get(&edge_index) {
                            if edge.head == "edge" && kept_edges.insert(edge_index) {
                                for slot in [3usize, 5] {
                                    if let Some(vertex_index) = edge.ref_at(slot) {
                                        if let Some(vertex) = by_index.get(&vertex_index) {
                                            if vertex.head == "vertex" {
                                                kept_vertices.insert(vertex_index);
                                                if let Some(point_index) = vertex.ref_at(5) {
                                                    kept_points.insert(point_index);
                                                }
                                            }
                                        }
                                    }
                                }
                                if let Some(curve_index) = edge.ref_at(8) {
                                    match curve_geo.entry(curve_index) {
                                        std::collections::hash_map::Entry::Occupied(_) => {
                                            kept_curves.insert(curve_index);
                                        }
                                        std::collections::hash_map::Entry::Vacant(entry) => {
                                            if let Some(curve_record) = by_index.get(&curve_index) {
                                                if let Some(decoded) =
                                                    nurbs::decode_procedural_curve_resolving_refs(
                                                        record_slice(curve_record, bytes),
                                                        bytes,
                                                    )
                                                {
                                                    let mut curve = decoded.curve;
                                                    if record_reversed(curve_record) {
                                                        reverse_nurbs_curve(&mut curve);
                                                    }
                                                    entry.insert(CurveGeometry::Nurbs(curve));
                                                    procedural_curve_defs.insert(
                                                        curve_index,
                                                        (
                                                            decoded.native_kind,
                                                            decoded.definition,
                                                            decoded.vector_offset,
                                                            decoded.subset,
                                                            decoded.compound,
                                                            decoded.embedded_two_sided_offset,
                                                            decoded.embedded_intersection,
                                                            decoded.embedded_three_surface_intersection,
                                                            decoded.embedded_surface_curve,
                                                            decoded.embedded_projection,
                                                            decoded.cache_fit_tolerance,
                                                        ),
                                                    );
                                                    kept_curves.insert(curve_index);
                                                    out.stats.nurbs_curves += 1;
                                                } else {
                                                    undecoded_carriers.insert(curve_index);
                                                    out.stats.procedural_curve_edges += 1;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    coedge_ref = coedge.ref_at(3);
                    if coedge_ref == Some(first_coedge) {
                        break;
                    }
                }
            }
            wire_ref = wire.ref_at(3);
        }
    }

    // An edge whose sense boolean is reversed traverses its curve as
    // `C(-t)`, with the edge parameters on the reversed parameterization.
    // The IR keeps every edge forward on its curve (the STEP writer's
    // `same_sense = .T.` contract), so carriers referenced only by reversed
    // edges are reversed in place; a carrier shared across both senses keeps
    // its forward orientation and reversed edges point at a `:reversed`
    // clone emitted beside it.
    let mut reversed_curve_refs: HashSet<i64> = HashSet::new();
    let mut forward_curve_refs: HashSet<i64> = HashSet::new();
    for r in records {
        if r.head != "edge" || !kept_edges.contains(&(r.index as i64)) {
            continue;
        }
        let Some(curve) = r.ref_at(8).filter(|c| kept_curves.contains(c)) else {
            continue;
        };
        match sense_at(r, 9) {
            Sense::Reversed => reversed_curve_refs.insert(curve),
            Sense::Forward => forward_curve_refs.insert(curve),
        };
    }
    let reversed_curve_id = |c: i64| {
        if reversed_curve_refs.contains(&c) && forward_curve_refs.contains(&c) {
            CurveId(format!("{}:reversed", id(c)))
        } else {
            CurveId(id(c))
        }
    };

    // Pass 3: emit carriers, points, and the reachable topology graph in
    // RecordTable order for deterministic output.
    for r in records {
        let i = r.index as i64;
        match r.head.as_str() {
            _ if kept_surfaces.contains(&i) => {
                // A record index appears at most once in `records`; a duplicate
                // would have consumed the entry already, so skip rather than panic.
                let Some((geometry, _)) = surface_geo.remove(&i) else {
                    continue;
                };
                out.surfaces.push(Surface {
                    id: SurfaceId(id(i)),
                    geometry,
                });
                if let Some(procedural) = procedural_surface_defs.remove(&i) {
                    let definition = match procedural.definition {
                        nurbs::DecodedProceduralSurfaceDefinition::Extrusion {
                            directrix,
                            direction,
                        } => {
                            let directrix_id =
                                CurveId(format!("f3d:brep:procedural_surface#{i}:directrix"));
                            out.curves.push(Curve {
                                id: directrix_id.clone(),
                                geometry: CurveGeometry::Nurbs(directrix),
                            });
                            ProceduralSurfaceDefinition::Extrusion {
                                directrix: directrix_id,
                                direction,
                            }
                        }
                        nurbs::DecodedProceduralSurfaceDefinition::Blend {
                            supports,
                            spine,
                            radius,
                            cross_section,
                        } => {
                            let mut resolved_supports = [None, None];
                            for (side, support) in supports.into_iter().enumerate() {
                                if let Some(support) = support {
                                    let support_id = SurfaceId(format!(
                                        "f3d:brep:procedural_surface#{i}:support#{side}"
                                    ));
                                    out.surfaces.push(Surface {
                                        id: support_id.clone(),
                                        geometry: SurfaceGeometry::Nurbs(support),
                                    });
                                    resolved_supports[side] = Some(BlendSupport {
                                        surface: support_id,
                                        reversed: false,
                                    });
                                }
                            }
                            let spine = spine.map(|spine| {
                                let spine_id =
                                    CurveId(format!("f3d:brep:procedural_surface#{i}:spine"));
                                out.curves.push(Curve {
                                    id: spine_id.clone(),
                                    geometry: CurveGeometry::Nurbs(spine),
                                });
                                spine_id
                            });
                            if resolved_supports
                                .iter()
                                .filter(|support| support.is_some())
                                .count()
                                == 1
                            {
                                out.stats.partial_procedural_supports += 1;
                            }
                            ProceduralSurfaceDefinition::Blend {
                                supports: resolved_supports,
                                spine,
                                radius,
                                cross_section,
                            }
                        }
                    };
                    out.procedural_surfaces.push(ProceduralSurface {
                        id: format!("f3d:brep:procedural_surface#{i}").into(),
                        surface: SurfaceId(id(i)),
                        definition,
                        cache_fit_tolerance: procedural.cache_fit_tolerance,
                    });
                }
            }
            _ if unknown_surface_records.contains(&i) => {
                // Topology-known face on an undecoded surface: emit an opaque
                // carrier linking to the preserved record bytes, marked Unknown.
                out.surfaces.push(Surface {
                    id: SurfaceId(id(i)),
                    geometry: SurfaceGeometry::Unknown {
                        record: Some(UnknownId(unknown_record_id(r))),
                    },
                });
            }
            _ if kept_curves.contains(&i) => {
                let Some(mut geometry) = curve_geo.remove(&i) else {
                    continue;
                };
                if reversed_curve_refs.contains(&i) {
                    if forward_curve_refs.contains(&i) {
                        let mut reversed = geometry.clone();
                        reverse_curve_geometry(&mut reversed);
                        out.curves.push(Curve {
                            id: CurveId(format!("{}:reversed", id(i))),
                            geometry: reversed,
                        });
                    } else {
                        reverse_curve_geometry(&mut geometry);
                    }
                }
                out.curves.push(Curve {
                    id: CurveId(id(i)),
                    geometry,
                });
                if let Some(procedural) = procedural_curve_defs.remove(&i) {
                    let definition = if let Some((source, parameter_range, offset, labels, codes)) =
                        procedural.2
                    {
                        let source_id = CurveId(format!("f3d:brep:procedural_curve#{i}:source"));
                        out.curves.push(Curve {
                            id: source_id.clone(),
                            geometry: CurveGeometry::Nurbs(source),
                        });
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::VectorOffset {
                            source: source_id,
                            parameter_range,
                            offset,
                            labels,
                            codes,
                        }
                    } else if let Some((source, parameter_range)) = procedural.3 {
                        let source_id = CurveId(format!("f3d:brep:procedural_curve#{i}:source"));
                        out.curves.push(Curve {
                            id: source_id.clone(),
                            geometry: CurveGeometry::Nurbs(source),
                        });
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::Subset {
                            source: source_id,
                            parameter_range,
                        }
                    } else if let Some(embedded) = procedural.5 {
                        let surfaces: [Option<SurfaceId>; 2] = embedded
                            .surfaces
                            .into_iter()
                            .enumerate()
                            .map(|(side, geometry)| {
                                let id = SurfaceId(format!(
                                    "f3d:brep:procedural_curve#{i}:support#{side}"
                                ));
                                out.surfaces.push(Surface {
                                    id: id.clone(),
                                    geometry,
                                });
                                Some(id)
                            })
                            .collect::<Vec<_>>()
                            .try_into()
                            .expect("two fixed support sides");
                        let pcurves = embedded.pcurves.map(|pcurve| {
                            Some(PcurveGeometry::Nurbs {
                                degree: pcurve.degree,
                                knots: pcurve.knots,
                                control_points: pcurve.control_points,
                                weights: pcurve.weights,
                                periodic: pcurve.periodic,
                            })
                        });
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::TwoSidedOffset {
                            context: cadmpeg_ir::geometry::IntcurveSupportContext {
                                sides: std::array::from_fn(|side| {
                                    cadmpeg_ir::geometry::IntcurveSupportSide {
                                        surface: surfaces[side].clone(),
                                        pcurve: pcurves[side].clone(),
                                    }
                                }),
                                parameter_range: embedded.parameter_range,
                                discontinuities: embedded.discontinuities,
                            },
                            offsets: embedded.offsets,
                        }
                    } else if let Some(embedded) = procedural.6 {
                        let surfaces: [Option<SurfaceId>; 2] = embedded
                            .surfaces
                            .into_iter()
                            .enumerate()
                            .map(|(side, geometry)| {
                                let id = SurfaceId(format!(
                                    "f3d:brep:procedural_curve#{i}:support#{side}"
                                ));
                                out.surfaces.push(Surface {
                                    id: id.clone(),
                                    geometry,
                                });
                                Some(id)
                            })
                            .collect::<Vec<_>>()
                            .try_into()
                            .expect("two fixed support sides");
                        let pcurves = embedded.pcurves.map(|pcurve| {
                            Some(PcurveGeometry::Nurbs {
                                degree: pcurve.degree,
                                knots: pcurve.knots,
                                control_points: pcurve.control_points,
                                weights: pcurve.weights,
                                periodic: pcurve.periodic,
                            })
                        });
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::Intersection {
                            context: cadmpeg_ir::geometry::IntcurveSupportContext {
                                sides: std::array::from_fn(|side| {
                                    cadmpeg_ir::geometry::IntcurveSupportSide {
                                        surface: surfaces[side].clone(),
                                        pcurve: pcurves[side].clone(),
                                    }
                                }),
                                parameter_range: embedded.parameter_range,
                                discontinuities: embedded.discontinuities,
                            },
                        }
                    } else if let Some(embedded) = procedural.7 {
                        let surface_ids: [SurfaceId; 3] = embedded
                            .surfaces
                            .into_iter()
                            .enumerate()
                            .map(|(side, geometry)| {
                                let id = SurfaceId(format!(
                                    "f3d:brep:procedural_curve#{i}:support#{side}"
                                ));
                                out.surfaces.push(Surface {
                                    id: id.clone(),
                                    geometry,
                                });
                                id
                            })
                            .collect::<Vec<_>>()
                            .try_into()
                            .expect("three fixed support sides");
                        let pcurves = embedded.pcurves.map(|pcurve| PcurveGeometry::Nurbs {
                            degree: pcurve.degree,
                            knots: pcurve.knots,
                            control_points: pcurve.control_points,
                            weights: pcurve.weights,
                            periodic: pcurve.periodic,
                        });
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::ThreeSurfaceIntersection {
                            context: cadmpeg_ir::geometry::IntcurveSupportContext {
                                sides: std::array::from_fn(|side| {
                                    cadmpeg_ir::geometry::IntcurveSupportSide {
                                        surface: Some(surface_ids[side].clone()),
                                        pcurve: Some(pcurves[side].clone()),
                                    }
                                }),
                                parameter_range: embedded.parameter_range,
                                discontinuities: embedded.discontinuities,
                            },
                            selector: embedded.selector,
                            third: cadmpeg_ir::geometry::IntcurveSupportSide {
                                surface: Some(surface_ids[2].clone()),
                                pcurve: Some(pcurves[2].clone()),
                            },
                        }
                    } else if let Some((family, embedded)) = procedural.8 {
                        let surfaces: [Option<SurfaceId>; 2] = embedded
                            .surfaces
                            .into_iter()
                            .enumerate()
                            .map(|(side, geometry)| {
                                let id = SurfaceId(format!(
                                    "f3d:brep:procedural_curve#{i}:support#{side}"
                                ));
                                out.surfaces.push(Surface {
                                    id: id.clone(),
                                    geometry,
                                });
                                Some(id)
                            })
                            .collect::<Vec<_>>()
                            .try_into()
                            .expect("two fixed support sides");
                        let pcurves = embedded.pcurves.map(|pcurve| {
                            Some(PcurveGeometry::Nurbs {
                                degree: pcurve.degree,
                                knots: pcurve.knots,
                                control_points: pcurve.control_points,
                                weights: pcurve.weights,
                                periodic: pcurve.periodic,
                            })
                        });
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::SurfaceCurve {
                            family,
                            context: cadmpeg_ir::geometry::IntcurveSupportContext {
                                sides: std::array::from_fn(|side| {
                                    cadmpeg_ir::geometry::IntcurveSupportSide {
                                        surface: surfaces[side].clone(),
                                        pcurve: pcurves[side].clone(),
                                    }
                                }),
                                parameter_range: embedded.parameter_range,
                                discontinuities: embedded.discontinuities,
                            },
                        }
                    } else if let Some(embedded) = procedural.9 {
                        let surfaces: [Option<SurfaceId>; 2] = embedded
                            .surfaces
                            .into_iter()
                            .enumerate()
                            .map(|(side, geometry)| {
                                let id = SurfaceId(format!(
                                    "f3d:brep:procedural_curve#{i}:support#{side}"
                                ));
                                out.surfaces.push(Surface {
                                    id: id.clone(),
                                    geometry,
                                });
                                Some(id)
                            })
                            .collect::<Vec<_>>()
                            .try_into()
                            .expect("two fixed support sides");
                        let pcurves = embedded.pcurves.map(|pcurve| {
                            Some(PcurveGeometry::Nurbs {
                                degree: pcurve.degree,
                                knots: pcurve.knots,
                                control_points: pcurve.control_points,
                                weights: pcurve.weights,
                                periodic: pcurve.periodic,
                            })
                        });
                        let source = CurveId(format!("f3d:brep:procedural_curve#{i}:source"));
                        out.curves.push(Curve {
                            id: source.clone(),
                            geometry: CurveGeometry::Nurbs(embedded.source),
                        });
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::Projection {
                            context: cadmpeg_ir::geometry::IntcurveSupportContext {
                                sides: std::array::from_fn(|side| {
                                    cadmpeg_ir::geometry::IntcurveSupportSide {
                                        surface: surfaces[side].clone(),
                                        pcurve: pcurves[side].clone(),
                                    }
                                }),
                                parameter_range: embedded.parameter_range,
                                discontinuities: embedded.discontinuities,
                            },
                            source,
                            tail: embedded.tail,
                        }
                    } else if let Some((parameters, component_parameters, components)) =
                        procedural.4
                    {
                        let components = components
                            .into_iter()
                            .enumerate()
                            .map(|(component, curve)| {
                                let id = CurveId(format!(
                                    "f3d:brep:procedural_curve#{i}:component#{component}"
                                ));
                                out.curves.push(Curve {
                                    id: id.clone(),
                                    geometry: CurveGeometry::Nurbs(curve),
                                });
                                id
                            })
                            .collect();
                        cadmpeg_ir::geometry::ProceduralCurveDefinition::Compound {
                            parameters,
                            component_parameters,
                            components,
                        }
                    } else {
                        procedural.1.unwrap_or(
                            cadmpeg_ir::geometry::ProceduralCurveDefinition::Unknown {
                                record: None,
                            },
                        )
                    };
                    out.procedural_curves.push(ProceduralCurve {
                        id: format!("f3d:brep:procedural_curve#{i}").into(),
                        curve: CurveId(id(i)),
                        definition,
                        cache_fit_tolerance: procedural.10,
                    });
                }
            }
            _ => {}
        }
    }

    for r in records {
        let i = r.index as i64;
        if kept_pcurves.contains(&i) {
            if let Some(geometry) = pcurve_geo.remove(&i) {
                out.pcurves.push(Pcurve {
                    id: PcurveId(id(i)),
                    geometry,
                    wrapper_reversed: match r.chunk(4) {
                        Some(Token::True) if matches!(r.chunk(3), Some(Token::Long(0))) => {
                            Some(true)
                        }
                        Some(Token::False) if matches!(r.chunk(3), Some(Token::Long(0))) => {
                            Some(false)
                        }
                        _ => None,
                    },
                    parameter_range: if matches!(
                        r.chunk(4),
                        Some(Token::True | Token::False | Token::Ref(_))
                    ) {
                        let values = r
                            .tokens
                            .iter()
                            .filter_map(|token| match token {
                                Token::Double(value) => Some(*value),
                                _ => None,
                            })
                            .collect::<Vec<_>>();
                        values
                            .get(values.len().saturating_sub(2)..)
                            .filter(|values| values.len() == 2)
                            .map(|values| [values[0], values[1]])
                    } else {
                        None
                    },
                    fit_tolerance: matches!(r.chunk(4), Some(Token::True | Token::False))
                        .then(|| nurbs::decode_pcurve_fit_tolerance(record_slice(r, bytes)))
                        .flatten(),
                });
            }
        }
    }
    for r in records {
        let i = r.index as i64;
        if r.head == "point" && kept_points.contains(&i) {
            let c = collect_carrier(r);
            if let Some(p) = c.positions.first() {
                out.points.push(Point {
                    id: PointId(id(i)),
                    position: scale_point(*p),
                });
            }
        }
    }

    for r in records {
        let i = r.index as i64;
        if r.head == "vertex" && kept_vertices.contains(&i) {
            if let Some(pi) = r.ref_at(5) {
                if kept_points.contains(&pi) {
                    out.vertices.push(Vertex {
                        id: VertexId(id(i)),
                        point: PointId(id(pi)),
                        tolerance: None,
                    });
                }
            }
        }
    }

    for r in records {
        let i = r.index as i64;
        if r.head == "edge" && kept_edges.contains(&i) {
            let (Some(start), Some(end)) = (r.ref_at(3), r.ref_at(5)) else {
                continue;
            };
            if !kept_vertices.contains(&start) || !kept_vertices.contains(&end) {
                continue;
            }
            let curve = r.ref_at(8).filter(|c| kept_curves.contains(c));
            let param_range = match (double_at(r, 4), double_at(r, 6)) {
                (Some(mut a), Some(mut b)) => {
                    if let Some(curve_record) = curve.and_then(|curve| by_index.get(&curve)) {
                        if curve_record.head == "ellipse" {
                            // Native conic parameters are angles from the
                            // major axis, matching the IR carrier's own
                            // parameterization directly.
                            if (b - a).abs() >= std::f64::consts::TAU - 1.0e-12 {
                                a = 0.0;
                                b = std::f64::consts::TAU;
                            } else {
                                // Wrap the arc start into the canonical
                                // `[0, Ï„)` domain, preserving the sweep.
                                let sweep = b - a;
                                a = a.rem_euclid(std::f64::consts::TAU);
                                if std::f64::consts::TAU - a < 1.0e-9 {
                                    a = 0.0;
                                }
                                b = a + sweep;
                            }
                        } else if curve_record.head == "straight" {
                            // Native line parameters are arc lengths in
                            // centimeters; the IR carrier's unit direction
                            // lives in millimeter space.
                            a *= LEN_TO_MM;
                            b *= LEN_TO_MM;
                        }
                    }
                    Some([a, b])
                }
                _ => None,
            };
            // A reversed edge's raw parameters already live on the reversed
            // parameterization its (reversed) carrier now exposes, so the
            // range transforms identically for both senses; only the carrier
            // link differs when the curve is shared across senses.
            let curve = curve.map(|c| match sense_at(r, 9) {
                Sense::Reversed => reversed_curve_id(c),
                Sense::Forward => CurveId(id(c)),
            });
            out.edges.push(Edge {
                id: EdgeId(id(i)),
                curve,
                start: VertexId(id(start)),
                end: VertexId(id(end)),
                param_range,
                tolerance: None,
            });
        }
    }

    for r in records {
        let i = r.index as i64;
        if r.head == "coedge" && kept_coedges.contains(&i) {
            let (Some(next), Some(prev), Some(edge), Some(owner)) =
                (r.ref_at(3), r.ref_at(4), r.ref_at(6), r.ref_at(8))
            else {
                continue;
            };
            if !kept_coedges.contains(&next)
                || !kept_coedges.contains(&prev)
                || !kept_edges.contains(&edge)
                || !kept_loops.contains(&owner)
            {
                continue;
            }
            let partner = r.ref_at(5).filter(|p| kept_coedges.contains(p));
            out.coedges.push(Coedge {
                id: CoedgeId(id(i)),
                owner_loop: LoopId(id(owner)),
                edge: EdgeId(id(edge)),
                next: CoedgeId(id(next)),
                previous: CoedgeId(id(prev)),
                radial_next: partner.map_or_else(|| CoedgeId(id(i)), |p| CoedgeId(id(p))),
                sense: sense_at(r, 7),
                pcurve: r
                    .ref_at(10)
                    .filter(|p| kept_pcurves.contains(p))
                    .map(|p| PcurveId(id(p))),
            });
        }
    }

    for r in records {
        let i = r.index as i64;
        if r.head == "loop" && kept_loops.contains(&i) {
            let Some(owner) = r.ref_at(5) else { continue };
            let coedges = ring_coedges(r, &by_index, &kept_coedges);
            out.loops.push(Loop {
                id: LoopId(id(i)),
                face: FaceId(id(owner)),
                coedges,
            });
        }
    }

    for r in records {
        let i = r.index as i64;
        if r.head == "face" && kept_faces.contains(&i) {
            let (Some(surface), Some(owner)) = (r.ref_at(7), r.ref_at(5)) else {
                continue;
            };
            let loops = loop_chain(r, &by_index, &kept_loops);
            // The face record's sense is relative to its surface record's
            // orientation. A reversed spline record flips the cache normal,
            // and a negative-cosine cone points its normal toward the axis;
            // the IR stores the forward carrier in both cases, so the
            // reversal folds into the face sense to keep the IR
            // self-consistent.
            let mut sense = sense_at(r, 8);
            if by_index
                .get(&surface)
                .is_some_and(|surf| surf.head == "spline" && record_reversed(surf))
                ^ inward_normal_surfaces.contains(&surface)
            {
                sense = match sense {
                    Sense::Forward => Sense::Reversed,
                    Sense::Reversed => Sense::Forward,
                };
            }
            out.faces.push(Face {
                id: FaceId(id(i)),
                shell: ShellId(id(owner)),
                surface: SurfaceId(id(surface)),
                sense,
                loops,
                name: None,
                color: attribute_color(r),
                tolerance: None,
            });
        }
    }

    // Containers: emitted for every record so back-references resolve, with
    // child lists filtered to reachable entities.
    for r in records {
        let i = r.index as i64;
        match r.head.as_str() {
            "shell" => {
                let Some(owner) = r.ref_at(7) else { continue };
                let faces = face_chain(r, &by_index, &kept_faces);
                out.shells.push(Shell {
                    id: ShellId(id(i)),
                    region: RegionId(id(owner)),
                    faces,
                    wire_edges: wire_edges_by_shell
                        .get(&i)
                        .into_iter()
                        .flatten()
                        .map(|edge| EdgeId(id(*edge)))
                        .collect(),
                    free_vertices: Vec::new(),
                });
            }
            // ASM release 231 names this record `region`; release 227 streams
            // carry the original ACIS head `lump`. Same layout in both.
            "region" | "lump" => {
                let Some(owner) = r.ref_at(5) else { continue };
                let shells = shell_chain(r, &by_index);
                out.regions.push(Region {
                    id: RegionId(id(i)),
                    body: BodyId(id(owner)),
                    shells,
                });
            }
            "body" => {
                let regions = region_chain(r, &by_index);
                let body_id = BodyId(id(i));
                if let Some(Token::Long(key)) = r.chunk(1) {
                    if *key >= 0 {
                        out.body_keys.insert(body_id.clone(), *key as u64);
                    }
                }
                out.bodies.push(Body {
                    id: body_id,
                    kind: cadmpeg_ir::topology::BodyKind::Solid,
                    regions,
                    transform: r
                        .ref_at(5)
                        .and_then(|reference| by_index.get(&reference))
                        .and_then(|transform| decode_transform(transform, header_scale)),
                    name: None,
                    color: attribute_color(r),
                });
            }
            _ => {}
        }
    }

    let mut emitted_attributes = HashSet::new();
    for record in records {
        let index = record.index as i64;
        let target = match record.head.as_str() {
            "body" if out.bodies.iter().any(|entity| entity.id.0 == id(index)) => {
                Some(AttributeTarget::Body(BodyId(id(index))))
            }
            "face" if kept_faces.contains(&index) => Some(AttributeTarget::Face(FaceId(id(index)))),
            "coedge" if kept_coedges.contains(&index) => {
                Some(AttributeTarget::Coedge(CoedgeId(id(index))))
            }
            "edge" if kept_edges.contains(&index) => Some(AttributeTarget::Edge(EdgeId(id(index)))),
            "vertex" if kept_vertices.contains(&index) => {
                Some(AttributeTarget::Vertex(VertexId(id(index))))
            }
            _ => None,
        };
        if let Some(target) = target {
            collect_attributes(
                record,
                &target,
                &by_index,
                &mut emitted_attributes,
                &mut out.attributes,
            );
        }
    }

    for record in records {
        let index = record.index as i64;
        if record.name != "ATTRIB_CUSTOM-attrib" || emitted_attributes.contains(&index) {
            continue;
        }
        let Some(owner) = record.ref_at(4).and_then(|owner| by_index.get(&owner)) else {
            continue;
        };
        let owner_index = owner.index as i64;
        let target = match owner.head.as_str() {
            "body" => Some(AttributeTarget::Body(BodyId(id(owner_index)))),
            "face" if kept_faces.contains(&owner_index) => {
                Some(AttributeTarget::Face(FaceId(id(owner_index))))
            }
            "coedge" if kept_coedges.contains(&owner_index) => {
                Some(AttributeTarget::Coedge(CoedgeId(id(owner_index))))
            }
            "edge" if kept_edges.contains(&owner_index) => {
                Some(AttributeTarget::Edge(EdgeId(id(owner_index))))
            }
            "vertex" if kept_vertices.contains(&owner_index) => {
                Some(AttributeTarget::Vertex(VertexId(id(owner_index))))
            }
            _ => None,
        };
        if let Some(target) = target {
            emitted_attributes.insert(index);
            out.attributes.push(source_attribute(record, target));
        }
    }
    out.sketch_curve_links = out
        .attributes
        .iter()
        .filter_map(sketch_curve_link)
        .collect();
    out.persistent_design_links = out
        .attributes
        .iter()
        .flat_map(persistent_design_links)
        .collect();

    // Preserve undecoded carriers referenced by real topology as passthrough.
    for r in records {
        let i = r.index as i64;
        if undecoded_carriers.contains(&i) {
            out.unknowns.push(UnknownRecord {
                id: UnknownId(unknown_record_id(r)),
                offset: r.offset as u64,
                byte_len: r.len as u64,
                sha256: sha256_hex(&bytes[r.offset..(r.offset + r.len).min(bytes.len())]),
                data: Some(bytes[r.offset..(r.offset + r.len).min(bytes.len())].to_vec()),
                links: Vec::new(),
            });
        }
    }

    // Count remaining record kinds we neither emitted nor preserved.
    let kept_transforms: HashSet<i64> = records
        .iter()
        .filter(|record| record.head == "body")
        .filter_map(|record| record.ref_at(5))
        .collect();
    let pcurve_intcurves: HashSet<i64> = records
        .iter()
        .filter(|record| kept_pcurves.contains(&(record.index as i64)))
        .filter_map(|record| record.ref_at(4))
        .collect();
    let known_head = |h: &str| {
        matches!(
            h,
            "body"
                | "region"
                | "lump"
                | "shell"
                | "face"
                | "loop"
                | "coedge"
                | "edge"
                | "vertex"
                | "point"
        ) || is_analytic_surface(h)
            || is_analytic_curve(h)
            || h == "asmheader"
    };
    for r in records {
        let i = r.index as i64;
        // Spline/intcurve records that decoded into a NURBS carrier are counted
        // as transferred, not as opaque leftovers.
        let transferred = kept_surfaces.contains(&i)
            || kept_curves.contains(&i)
            || kept_pcurves.contains(&i)
            || kept_transforms.contains(&i)
            || emitted_attributes.contains(&i)
            || pcurve_intcurves.contains(&i);
        if !known_head(&r.head)
            && r.name != "Begin-of-ASM-History-Data"
            && !undecoded_carriers.contains(&i)
            && !transferred
        {
            out.stats.other_records += 1;
            *out.stats
                .other_record_kinds
                .entry(r.name.clone())
                .or_default() += 1;
        }
    }

    let emitted_ids = out
        .bodies
        .iter()
        .map(|entity| entity.id.0.as_str())
        .chain(out.regions.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.shells.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.faces.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.loops.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.coedges.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.edges.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.vertices.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.points.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.surfaces.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.curves.iter().map(|entity| entity.id.0.as_str()))
        .chain(out.pcurves.iter().map(|entity| entity.id.0.as_str()))
        .collect::<HashSet<_>>();
    for record in records {
        let entity_id = id(record.index as i64);
        if emitted_ids.contains(entity_id.as_str()) {
            let mut derived_fields = Vec::new();
            match record.head.as_str() {
                "plane" => {
                    derived_fields.extend(["geometry.normal", "geometry.u_axis"]);
                }
                "cone" => {
                    derived_fields.extend(["geometry.axis", "geometry.ref_direction"]);
                }
                "sphere" => {
                    derived_fields.extend(["geometry.axis", "geometry.ref_direction"]);
                }
                "torus" => {
                    derived_fields.extend(["geometry.axis", "geometry.ref_direction"]);
                }
                "straight" => derived_fields.push("geometry.direction"),
                "ellipse" => {
                    derived_fields.extend(["geometry.axis", "geometry.major_direction"]);
                }
                _ => {}
            }
            if record.head == "edge" {
                if let Some(curve) = record
                    .ref_at(8)
                    .and_then(|reference| by_index.get(&reference))
                {
                    if curve.head == "ellipse" {
                        derived_fields.push("param_range");
                    }
                }
            }
            out.annotation_records.push(AnnotationRecord {
                id: entity_id,
                offset: record.offset as u64,
                tag: record.name.clone(),
                derived_fields,
            });
        }
        let attribute_id = format!("f3d:brep:attribute#{}", record.index);
        if out
            .attributes
            .iter()
            .any(|attribute| attribute.id.0 == attribute_id)
        {
            out.annotation_records.push(AnnotationRecord {
                id: attribute_id,
                offset: record.offset as u64,
                tag: record.name.clone(),
                derived_fields: Vec::new(),
            });
        }
        let unknown_id = unknown_record_id(record);
        if out
            .unknowns
            .iter()
            .any(|unknown| unknown.id.0 == unknown_id)
        {
            out.annotation_records.push(AnnotationRecord {
                id: unknown_id,
                offset: record.offset as u64,
                tag: record.name.clone(),
                derived_fields: Vec::new(),
            });
        }
        for (synthetic_id, tag) in [
            (
                format!("f3d:brep:procedural_surface#{}", record.index),
                "procedural_surface",
            ),
            (
                format!("f3d:brep:procedural_curve#{}", record.index),
                "procedural_curve",
            ),
        ] {
            if out
                .procedural_surfaces
                .iter()
                .any(|entity| entity.id.0 == synthetic_id)
                || out
                    .procedural_curves
                    .iter()
                    .any(|entity| entity.id.0 == synthetic_id)
            {
                out.annotation_records.push(AnnotationRecord {
                    id: synthetic_id,
                    offset: record.offset as u64,
                    tag: tag.into(),
                    derived_fields: Vec::new(),
                });
            }
        }
    }
    for (entity_id, tag) in out
        .surfaces
        .iter()
        .map(|entity| (entity.id.0.as_str(), "procedural_support"))
        .chain(
            out.curves
                .iter()
                .map(|entity| (entity.id.0.as_str(), "procedural_curve_child")),
        )
    {
        if !entity_id.starts_with("f3d:brep:procedural_surface#") {
            continue;
        }
        let Some(index) = entity_id
            .split_once('#')
            .and_then(|(_, suffix)| suffix.split(':').next())
            .and_then(|value| value.parse::<usize>().ok())
        else {
            continue;
        };
        let Some(record) = records.get(index) else {
            continue;
        };
        out.annotation_records.push(AnnotationRecord {
            id: entity_id.to_owned(),
            offset: record.offset as u64,
            tag: tag.into(),
            derived_fields: Vec::new(),
        });
    }

    classify_body_kinds(&mut out);

    out
}

fn classify_body_kinds(out: &mut Brep) {
    for body in &mut out.bodies {
        let shell_ids = out
            .regions
            .iter()
            .filter(|region| region.body == body.id)
            .flat_map(|region| &region.shells)
            .collect::<HashSet<_>>();
        let face_ids = out
            .shells
            .iter()
            .filter(|shell| shell_ids.contains(&shell.id))
            .flat_map(|shell| &shell.faces)
            .collect::<HashSet<_>>();
        let has_wire_edges = out
            .shells
            .iter()
            .filter(|shell| shell_ids.contains(&shell.id))
            .any(|shell| !shell.wire_edges.is_empty());
        if face_ids.is_empty() {
            body.kind = cadmpeg_ir::topology::BodyKind::Wire;
            continue;
        }
        if has_wire_edges {
            body.kind = cadmpeg_ir::topology::BodyKind::General;
            continue;
        }
        let loop_ids = out
            .faces
            .iter()
            .filter(|face| face_ids.contains(&face.id))
            .flat_map(|face| &face.loops)
            .collect::<HashSet<_>>();
        let coedge_ids = out
            .loops
            .iter()
            .filter(|loop_| loop_ids.contains(&loop_.id))
            .flat_map(|loop_| &loop_.coedges)
            .collect::<HashSet<_>>();
        let mut edge_use_counts = HashMap::<&EdgeId, usize>::new();
        for coedge in out
            .coedges
            .iter()
            .filter(|coedge| coedge_ids.contains(&coedge.id))
        {
            *edge_use_counts.entry(&coedge.edge).or_default() += 1;
        }
        body.kind =
            if !edge_use_counts.is_empty() && edge_use_counts.values().all(|count| *count == 2) {
                cadmpeg_ir::topology::BodyKind::Solid
            } else {
                cadmpeg_ir::topology::BodyKind::Sheet
            };
    }
}

fn sketch_curve_link(attribute: &SourceAttribute) -> Option<SketchCurveLink> {
    let AttributeTarget::Coedge(coedge) = &attribute.target else {
        return None;
    };
    let family = attribute.values.iter().position(
        |value| matches!(value, AttributeValue::String(name) if name == "sketch_attrib_def"),
    )?;
    let fields = attribute.values[family + 1..]
        .iter()
        .filter_map(|value| match value {
            AttributeValue::String(payload) => Some(
                payload
                    .split_ascii_whitespace()
                    .map(str::parse::<i64>)
                    .collect::<Result<Vec<_>, _>>()
                    .ok(),
            ),
            _ => None,
        })
        .flatten()
        .find(|values| values.len() == 6)
        .unwrap_or_else(|| {
            attribute.values[family + 1..]
                .iter()
                .filter_map(|value| match value {
                    AttributeValue::Integer(value) => Some(*value),
                    _ => None,
                })
                .take(6)
                .collect()
        });
    let [sketch_curve_id, 0, signed_reference, 0, role, closure] = fields.as_slice() else {
        return None;
    };
    Some(SketchCurveLink {
        id: format!("f3d:design:sketch-curve-link#{}", attribute_key(attribute)),
        coedge: coedge.clone(),
        sketch_curve_id: *sketch_curve_id,
        signed_reference: (*signed_reference != -1).then_some(*signed_reference),
        role: *role,
        closure: *closure,
    })
}

fn persistent_design_links(attribute: &SourceAttribute) -> Vec<PersistentDesignLink> {
    let Some(family) = attribute.values.iter().position(
        |value| matches!(value, AttributeValue::String(name) if name == "generic_tag_attrib_def"),
    ) else {
        return Vec::new();
    };
    let ids: Vec<String> = attribute.values[family + 1..]
        .iter()
        .filter_map(|value| match value {
            AttributeValue::String(value)
                if value.trim() != "generic_tag_attrib_def"
                    && !value.is_empty()
                    && value.bytes().all(|byte| byte.is_ascii_digit()) =>
            {
                Some(value.clone())
            }
            _ => None,
        })
        .collect();
    let last = ids.len().saturating_sub(1);
    ids.into_iter()
        .enumerate()
        .map(|(ordinal, design_id)| PersistentDesignLink {
            id: format!(
                "f3d:design:persistent-design-link#{}:{ordinal}",
                attribute_key(attribute)
            ),
            target: attribute.target.clone(),
            design_id,
            ordinal: ordinal as u32,
            is_current: ordinal == last,
        })
        .collect()
}

fn collect_attributes(
    entity: &Record,
    target: &AttributeTarget,
    by_index: &HashMap<i64, &Record>,
    emitted: &mut HashSet<i64>,
    out: &mut Vec<SourceAttribute>,
) {
    let mut current = entity.ref_at(0);
    let mut chain = HashSet::new();
    while let Some(index) = current.filter(|index| chain.insert(*index)) {
        let Some(record) = by_index.get(&index) else {
            break;
        };
        if emitted.insert(index) {
            out.push(source_attribute(record, target.clone()));
        }
        current = record.ref_at(0);
    }
}

/// The numeric record-index key of an attribute id
/// (`f3d:brep:attribute#<index>`), used to key records derived from that
/// attribute.
fn attribute_key(attribute: &SourceAttribute) -> &str {
    attribute
        .id
        .0
        .rsplit('#')
        .next()
        .unwrap_or(attribute.id.0.as_str())
}

fn source_attribute(record: &Record, target: AttributeTarget) -> SourceAttribute {
    SourceAttribute {
        id: AttributeId(format!("f3d:brep:attribute#{}", record.index)),
        target,
        name: record.name.clone(),
        values: record.tokens.iter().map(attribute_value).collect(),
    }
}

fn attribute_value(token: &Token) -> AttributeValue {
    match token {
        Token::Char(value) => AttributeValue::Integer(i64::from(*value)),
        Token::Short(value) => AttributeValue::Integer(i64::from(*value)),
        Token::Long(value) | Token::Enum(value) | Token::Int64(value) => {
            AttributeValue::Integer(*value)
        }
        Token::Float(value) => AttributeValue::Float(f64::from(*value)),
        Token::Double(value) => AttributeValue::Float(*value),
        Token::Str(value) => AttributeValue::String(value.clone()),
        Token::True => AttributeValue::Boolean(true),
        Token::False => AttributeValue::Boolean(false),
        Token::Ref(value) => AttributeValue::Reference(format!("f3d:brep:entity#{value}")),
        Token::SubtypeOpen => AttributeValue::String("subtype_open".into()),
        Token::SubtypeClose => AttributeValue::String("subtype_close".into()),
        Token::Position(value) | Token::Vector3(value) => AttributeValue::Vector(value.to_vec()),
        Token::Vector2(value) => AttributeValue::Vector(value.to_vec()),
    }
}

pub(crate) fn decode_transform(
    record: &Record,
    header_scale: f64,
) -> Option<cadmpeg_ir::transform::Transform> {
    let vectors: Vec<[f64; 3]> = record
        .tokens
        .iter()
        .filter_map(|token| match token {
            Token::Position(value) | Token::Vector3(value) => Some(*value),
            _ => None,
        })
        .collect();
    let scale = record
        .tokens
        .iter()
        .filter_map(|token| match token {
            Token::Double(value) => Some(*value),
            _ => None,
        })
        .next_back()?;
    let [x, y, z, translation] = vectors.as_slice() else {
        return None;
    };
    Some(cadmpeg_ir::transform::Transform {
        rows: [
            [x[0], y[0], z[0], translation[0] * header_scale * LEN_TO_MM],
            [x[1], y[1], z[1], translation[1] * header_scale * LEN_TO_MM],
            [x[2], y[2], z[2], translation[2] * header_scale * LEN_TO_MM],
            [0.0, 0.0, 0.0, scale],
        ],
    })
}

pub(crate) fn attribute_chain_color(
    entity: &Record,
    by_index: &HashMap<i64, &Record>,
) -> Option<Color> {
    let mut current = entity.ref_at(0)?;
    let mut seen = HashSet::new();
    while seen.insert(current) {
        let record = by_index.get(&current)?;
        if record.name.contains("rgb_color") {
            let values: Vec<f64> = record
                .tokens
                .iter()
                .filter_map(|t| match t {
                    Token::Double(value) => Some(*value),
                    _ => None,
                })
                .collect();
            if let [r, g, b, ..] = values.as_slice() {
                if [*r, *g, *b].iter().all(|value| (0.0..=1.0).contains(value)) {
                    return Some(Color {
                        r: *r as f32,
                        g: *g as f32,
                        b: *b as f32,
                        a: 1.0,
                    });
                }
            }
        } else if record.name.contains("truecolor") {
            let packed = record.tokens.iter().find_map(|token| match token {
                Token::Int64(value) | Token::Long(value) => Some(*value as u32),
                _ => None,
            })?;
            return Some(Color {
                r: ((packed >> 16) & 0xff) as f32 / 255.0,
                g: ((packed >> 8) & 0xff) as f32 / 255.0,
                b: (packed & 0xff) as f32 / 255.0,
                a: ((packed >> 24) & 0xff) as f32 / 255.0,
            });
        }
        current = record.ref_at(0)?;
    }
    None
}

/// The raw bytes of a record within the decompressed stream.
fn record_slice<'a>(rec: &Record, bytes: &'a [u8]) -> &'a [u8] {
    let end = (rec.offset + rec.len).min(bytes.len());
    &bytes[rec.offset..end]
}

/// The `UnknownId` for a preserved carrier record. Shared by the passthrough
/// `UnknownRecord` and any `SurfaceGeometry::Unknown` that links to it, so the
/// reference resolves under validation.
fn unknown_record_id(rec: &Record) -> String {
    format!("f3d:brep:{}#{}", rec.head, rec.index)
}

fn ring_coedges(
    loop_rec: &Record,
    by_index: &HashMap<i64, &Record>,
    kept: &HashSet<i64>,
) -> Vec<CoedgeId> {
    let id = |i: i64| CoedgeId(format!("f3d:brep:entity#{i}"));
    let mut out = Vec::new();
    let Some(first) = loop_rec.ref_at(4) else {
        return out;
    };
    let mut cur = Some(first);
    let mut guard = HashSet::new();
    while let Some(ci) = cur {
        if !guard.insert(ci) || !kept.contains(&ci) {
            break;
        }
        out.push(id(ci));
        let Some(ce) = by_index.get(&ci) else { break };
        cur = ce.ref_at(3);
        if cur == Some(first) {
            break;
        }
    }
    out
}

fn loop_chain(
    face_rec: &Record,
    by_index: &HashMap<i64, &Record>,
    kept: &HashSet<i64>,
) -> Vec<LoopId> {
    let id = |i: i64| LoopId(format!("f3d:brep:entity#{i}"));
    let mut out = Vec::new();
    let mut cur = face_rec.ref_at(4);
    let mut guard = HashSet::new();
    while let Some(li) = cur {
        if !guard.insert(li) {
            break;
        }
        if kept.contains(&li) {
            out.push(id(li));
        }
        let Some(lp) = by_index.get(&li) else { break };
        cur = lp.ref_at(3);
    }
    out
}

fn face_chain(
    shell_rec: &Record,
    by_index: &HashMap<i64, &Record>,
    kept: &HashSet<i64>,
) -> Vec<FaceId> {
    let id = |i: i64| FaceId(format!("f3d:brep:entity#{i}"));
    let mut out = Vec::new();
    let mut cur = shell_rec.ref_at(5);
    let mut guard = HashSet::new();
    while let Some(fi) = cur {
        if !guard.insert(fi) {
            break;
        }
        if kept.contains(&fi) {
            out.push(id(fi));
        }
        let Some(f) = by_index.get(&fi) else { break };
        cur = f.ref_at(3);
    }
    out
}

fn shell_chain(region_rec: &Record, by_index: &HashMap<i64, &Record>) -> Vec<ShellId> {
    let id = |i: i64| ShellId(format!("f3d:brep:entity#{i}"));
    let mut out = Vec::new();
    let mut cur = region_rec.ref_at(4);
    let mut guard = HashSet::new();
    while let Some(si) = cur {
        if !guard.insert(si) {
            break;
        }
        out.push(id(si));
        let Some(s) = by_index.get(&si) else { break };
        cur = s.ref_at(0);
    }
    out
}

fn region_chain(body_rec: &Record, by_index: &HashMap<i64, &Record>) -> Vec<RegionId> {
    let id = |i: i64| RegionId(format!("f3d:brep:entity#{i}"));
    let mut out = Vec::new();
    let mut cur = body_rec.ref_at(3);
    let mut guard = HashSet::new();
    while let Some(li) = cur {
        if !guard.insert(li) {
            break;
        }
        out.push(id(li));
        let Some(l) = by_index.get(&li) else { break };
        cur = l.ref_at(0);
    }
    out
}

fn sha256_hex(bytes: &[u8]) -> String {
    use std::fmt::Write as _;

    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(bytes);
    let digest = h.finalize();
    let mut s = String::with_capacity(digest.len() * 2);
    for b in digest {
        let _ = write!(s, "{b:02x}");
    }
    s
}