cadmpeg-codec-f3d 0.2.0

Decode and encode Autodesk 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
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
// SPDX-License-Identifier: Apache-2.0
//! Decode cached B-spline blocks from spline and procedural SAB records.
//!
//! A `0x0d`-tagged `nubs` marker introduces a non-rational block; `nurbs`
//! introduces a rational block. Surface blocks contain two degrees, closure and
//! singularity enums, U and V knot tables, and a control grid. Curve blocks
//! contain one degree, a closure enum, one knot table, and a control polygon.
//! The token after the first degree distinguishes the two forms.
//!
//! Spline surfaces and procedural curves store solved geometry in these caches.
//! The public decode functions accept one record's bytes, with variants that
//! also follow references through the active slice's subtype table.
//!
//! Endpoint knot multiplicities are stored as `degree` rather than
//! `degree + 1`; the clamped knot vector is recovered by adding one at each
//! end. Control-point x/y/z are model-space lengths converted from centimetres
//! to millimetres; knots and rational weights are not scaled. Surface control
//! grids are stored v-major (v outer, u inner) and are transposed to the IR's
//! u-major order.
//!
//! Integer-family payloads (`0x04` int, `0x0c` ref, `0x15` enum) are 4 bytes in
//! `BinaryFile4` streams and 8 in `BinaryFile8` ([spec §3](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/f3d.md#3-asm-binary-header)); doubles are always
//! 8. Record bytes omit the stream width, so each decoder tests both layouts
//! and validates tags, degrees, counts, and block extents.

use cadmpeg_ir::geometry::{
    BlendCrossSection, BlendRadiusLaw, NurbsCurve, NurbsSurface, PcurveGeometry, SurfaceGeometry,
};
use cadmpeg_ir::le::{f64_at as read_f64, int_at as read_int, u16_at, u32_at};
use cadmpeg_ir::math::{Point2, Point3, Vector3};

use crate::sab::Record;

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

const NUBS_MARKER: &[u8] = b"\x0d\x04nubs";
const NURBS_MARKER: &[u8] = b"\x0d\x05nurbs";

/// Integer/ref payload widths to probe, `BinaryFile8` first. A wrong-width
/// parse cannot yield a false positive: in-range integers (degrees ≤ 20, knot
/// counts ≤ 1000) store zero high bytes, so an 8-byte read on a 4-byte stream
/// swallows the next tag byte into the value and fails the range check, while
/// a 4-byte read on an 8-byte stream leaves a zero byte where the next tag
/// must be and fails tag dispatch.
const INT_WIDTHS: [usize; 2] = [8, 4];

/// Read an `int_width`-byte little-endian signed integer.
/// Consume a `tag`-prefixed integer of `int_width` bytes at `*pos`, advancing
/// past it.
fn take_tagged_int(b: &[u8], pos: &mut usize, tag: u8, int_width: usize) -> Option<i64> {
    if *b.get(*pos)? != tag {
        return None;
    }
    let v = read_int(b, *pos + 1, int_width)?;
    *pos += 1 + int_width;
    Some(v)
}

/// The B-spline marker at `pos`, if any: `(control-point dimension, byte length
/// of the marker, rational?)`.
fn marker_at(b: &[u8], pos: usize) -> Option<(usize, usize, bool)> {
    if b[pos..].starts_with(NUBS_MARKER) {
        Some((3, NUBS_MARKER.len(), false))
    } else if b[pos..].starts_with(NURBS_MARKER) {
        Some((4, NURBS_MARKER.len(), true))
    } else {
        None
    }
}

/// Positions of every `nubs`/`nurbs` marker in `b`, in order.
fn marker_positions(b: &[u8]) -> Vec<usize> {
    let mut out = Vec::new();
    if b.len() < NUBS_MARKER.len() {
        return out;
    }
    for pos in 0..=b.len() - NUBS_MARKER.len() {
        if marker_at(b, pos).is_some() {
            out.push(pos);
        }
    }
    out
}

/// Read a knot table of `n` `(knot, multiplicity)` pairs, returning the expanded
/// clamped knot vector and pole count `sum(mult) - (degree - 1)`.
struct KnotLayout {
    value_offsets: Vec<usize>,
    multiplicity_offsets: Vec<usize>,
    expanded_run_lengths: Vec<usize>,
}

fn read_knots(
    b: &[u8],
    pos: &mut usize,
    n: usize,
    degree: i64,
    int_width: usize,
) -> Option<(Vec<f64>, usize, KnotLayout)> {
    let mut knots = Vec::new();
    let mut mults = Vec::new();
    let mut value_offsets = Vec::new();
    let mut multiplicity_offsets = Vec::new();
    for _ in 0..n {
        if *b.get(*pos)? != 0x06 {
            return None;
        }
        value_offsets.push(*pos + 1);
        knots.push(read_f64(b, *pos + 1)?);
        *pos += 9;
        multiplicity_offsets.push(*pos + 1);
        mults.push(take_tagged_int(b, pos, 0x04, int_width)?);
    }
    let sum: i64 = mults.iter().sum();
    let n_poles = sum - (degree - 1);
    if !(2..=100_000).contains(&n_poles) {
        return None;
    }
    let mut expanded = Vec::new();
    let mut expanded_run_lengths = Vec::new();
    for (i, (kv, m)) in knots.iter().zip(&mults).enumerate() {
        let extra = i64::from(i == 0 || i == n - 1);
        let run_length = usize::try_from((*m + extra).max(0)).ok()?;
        expanded_run_lengths.push(run_length);
        for _ in 0..run_length {
            expanded.push(*kv);
        }
    }
    Some((
        expanded,
        n_poles as usize,
        KnotLayout {
            value_offsets,
            multiplicity_offsets,
            expanded_run_lengths,
        },
    ))
}

/// Read `count` control points of `cp_dims` doubles each at `*pos`. Returns the
/// scaled `(x, y, z)` positions and, for rational blocks, the weights.
fn read_control_points(
    b: &[u8],
    pos: &mut usize,
    count: usize,
    cp_dims: usize,
) -> Option<(Vec<Point3>, Option<Vec<f64>>)> {
    let mut points = Vec::with_capacity(count);
    let mut weights = if cp_dims == 4 {
        Some(Vec::with_capacity(count))
    } else {
        None
    };
    for _ in 0..count {
        let mut comps = [0.0f64; 4];
        for comp in comps.iter_mut().take(cp_dims) {
            if *b.get(*pos)? != 0x06 {
                return None;
            }
            *comp = read_f64(b, *pos + 1)?;
            *pos += 9;
        }
        points.push(Point3::new(
            comps[0] * LEN_TO_MM,
            comps[1] * LEN_TO_MM,
            comps[2] * LEN_TO_MM,
        ));
        if let Some(w) = weights.as_mut() {
            w.push(comps[3]);
        }
    }
    Some((points, weights))
}

/// CLOSURE enum value `2` denotes a periodic parametric direction.
fn is_periodic(enum_val: i64) -> bool {
    enum_val == 2
}

/// Decode a surface `nubs`/`nurbs` block at `marker_pos`, or `None` if the bytes
/// there are not a well-formed surface block.
struct DecodedSurfaceBlock {
    surface: NurbsSurface,
    end: usize,
    control_value_offsets: Vec<usize>,
    rational: bool,
    u_knot_layout: KnotLayout,
    v_knot_layout: KnotLayout,
    periodic_value_offsets: [usize; 2],
    degree_value_offsets: [usize; 2],
}

fn decode_surface_block(
    b: &[u8],
    marker_pos: usize,
    int_width: usize,
) -> Option<DecodedSurfaceBlock> {
    let (cp_dims, marker_len, rational) = marker_at(b, marker_pos)?;
    let mut pos = marker_pos + marker_len;

    let degree_u_offset = pos + 1;
    let degree_u = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    let degree_v_offset = pos + 1;
    let degree_v = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    if !(1..=20).contains(&degree_u) || !(1..=20).contains(&degree_v) {
        return None;
    }
    // Some caches carry an optional scope identifier (`u`/`v`/`both`) before the
    // enum block; skip it so knot counts stay aligned.
    if b.get(pos) == Some(&0x0d) {
        let len = *b.get(pos + 1)? as usize;
        pos += 2 + len;
    }
    let mut enums = [0i64; 4];
    let mut enum_value_offsets = [0usize; 4];
    for (ordinal, e) in enums.iter_mut().enumerate() {
        enum_value_offsets[ordinal] = pos + 1;
        *e = take_tagged_int(b, &mut pos, 0x15, int_width)?;
    }
    let n_uniq_u = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    let n_uniq_v = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    if !(1..=1000).contains(&n_uniq_u) || !(1..=1000).contains(&n_uniq_v) {
        return None;
    }

    let (u_knots, n_poles_u, u_knot_layout) =
        read_knots(b, &mut pos, n_uniq_u as usize, degree_u, int_width)?;
    let (v_knots, n_poles_v, v_knot_layout) =
        read_knots(b, &mut pos, n_uniq_v as usize, degree_v, int_width)?;
    if n_poles_u.checked_mul(n_poles_v).is_none_or(|n| n > 200_000) {
        return None;
    }

    // Grid is stored v-major (v outer, u inner); transpose to the IR's u-major
    // order where index `u * v_count + v` is pole `(u, v)`.
    let control_start = pos;
    let (flat, flat_w) = read_control_points(b, &mut pos, n_poles_u * n_poles_v, cp_dims)?;
    let control_value_offsets = (0..n_poles_u * n_poles_v * cp_dims)
        .map(|ordinal| control_start + ordinal * 9 + 1)
        .collect();
    let mut control_points = vec![Point3::new(0.0, 0.0, 0.0); n_poles_u * n_poles_v];
    let mut weights = flat_w.as_ref().map(|_| vec![0.0f64; n_poles_u * n_poles_v]);
    for v in 0..n_poles_v {
        for u in 0..n_poles_u {
            let file_idx = v * n_poles_u + u;
            let ir_idx = u * n_poles_v + v;
            control_points[ir_idx] = flat[file_idx];
            if let (Some(w), Some(fw)) = (weights.as_mut(), flat_w.as_ref()) {
                w[ir_idx] = fw[file_idx];
            }
        }
    }

    Some(DecodedSurfaceBlock {
        surface: NurbsSurface {
            u_degree: degree_u as u32,
            v_degree: degree_v as u32,
            u_knots,
            v_knots,
            u_count: n_poles_u as u32,
            v_count: n_poles_v as u32,
            control_points,
            weights,
            u_periodic: is_periodic(enums[0]),
            v_periodic: is_periodic(enums[1]),
        },
        end: pos,
        control_value_offsets,
        rational,
        u_knot_layout,
        v_knot_layout,
        periodic_value_offsets: [enum_value_offsets[0], enum_value_offsets[1]],
        degree_value_offsets: [degree_u_offset, degree_v_offset],
    })
}

/// Writable value offsets for the final valid surface cache in one carrier record.
pub(crate) struct SurfacePatchLayout {
    /// Native v-major tagged-double payload offsets, excluding each tag byte.
    pub(crate) control_value_offsets: Vec<usize>,
    /// Whether every pole includes a fourth rational weight component.
    pub(crate) rational: bool,
    /// Pole count in the u direction.
    pub(crate) u_count: usize,
    /// Pole count in the v direction.
    pub(crate) v_count: usize,
    /// Native payload offsets and expanded run lengths for U knots.
    pub(crate) u_knots: KnotPatchLayout,
    /// Native payload offsets and expanded run lengths for V knots.
    pub(crate) v_knots: KnotPatchLayout,
    /// Offset immediately after the final control component.
    pub(crate) end: usize,
    /// Payload offsets for the U/V closure enums.
    pub(crate) periodic_value_offsets: [usize; 2],
    /// Payload offsets for the U/V degree integers.
    pub(crate) degree_value_offsets: [usize; 2],
}

/// Unique native knot payload offsets.
pub(crate) struct KnotPatchLayout {
    /// Payload offsets for unique knot values.
    pub(crate) value_offsets: Vec<usize>,
    /// Payload offsets for stored multiplicities.
    pub(crate) multiplicity_offsets: Vec<usize>,
    /// Repetition count of each unique value in the expanded IR vector.
    #[expect(dead_code)]
    pub(crate) expanded_run_lengths: Vec<usize>,
}

impl From<KnotLayout> for KnotPatchLayout {
    fn from(value: KnotLayout) -> Self {
        Self {
            value_offsets: value.value_offsets,
            multiplicity_offsets: value.multiplicity_offsets,
            expanded_run_lengths: value.expanded_run_lengths,
        }
    }
}

/// Locate the final valid `nubs`/`nurbs` surface block in a carrier record.
pub(crate) fn final_surface_patch_layout(record: &[u8]) -> Option<SurfacePatchLayout> {
    let decoded = INT_WIDTHS.into_iter().find_map(|int_width| {
        marker_positions(record)
            .into_iter()
            .filter_map(|position| decode_surface_block(record, position, int_width))
            .next_back()
    })?;
    Some(SurfacePatchLayout {
        control_value_offsets: decoded.control_value_offsets,
        rational: decoded.rational,
        u_count: decoded.surface.u_count as usize,
        v_count: decoded.surface.v_count as usize,
        u_knots: decoded.u_knot_layout.into(),
        v_knots: decoded.v_knot_layout.into(),
        end: decoded.end,
        periodic_value_offsets: decoded.periodic_value_offsets,
        degree_value_offsets: decoded.degree_value_offsets,
    })
}

/// Locate the surface block at `ordinal` among valid surface caches in a carrier record.
pub(crate) fn surface_patch_layout_at(record: &[u8], ordinal: usize) -> Option<SurfacePatchLayout> {
    let decoded = INT_WIDTHS.into_iter().find_map(|int_width| {
        marker_positions(record)
            .into_iter()
            .filter_map(|position| decode_surface_block(record, position, int_width))
            .nth(ordinal)
    })?;
    Some(SurfacePatchLayout {
        control_value_offsets: decoded.control_value_offsets,
        rational: decoded.rational,
        u_count: decoded.surface.u_count as usize,
        v_count: decoded.surface.v_count as usize,
        u_knots: decoded.u_knot_layout.into(),
        v_knots: decoded.v_knot_layout.into(),
        end: decoded.end,
        periodic_value_offsets: decoded.periodic_value_offsets,
        degree_value_offsets: decoded.degree_value_offsets,
    })
}

/// Decode a curve `nubs`/`nurbs` block at `marker_pos`, or `None` if the bytes
/// there are not a well-formed 3D curve block.
struct DecodedCurveBlock {
    curve: NurbsCurve,
    end: usize,
    control_value_offsets: Vec<usize>,
    rational: bool,
    knot_layout: KnotLayout,
    periodic_value_offset: usize,
    degree_value_offset: usize,
}

fn decode_curve_block(b: &[u8], marker_pos: usize, int_width: usize) -> Option<DecodedCurveBlock> {
    let (cp_dims, marker_len, rational) = marker_at(b, marker_pos)?;
    let mut pos = marker_pos + marker_len;

    let degree_value_offset = pos + 1;
    let degree = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    if !(1..=20).contains(&degree) {
        return None;
    }
    let periodic_value_offset = pos + 1;
    let closure = take_tagged_int(b, &mut pos, 0x15, int_width)?;
    let n_uniq = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    if !(1..=1000).contains(&n_uniq) {
        return None;
    }
    let (knots, n_poles, knot_layout) =
        read_knots(b, &mut pos, n_uniq as usize, degree, int_width)?;
    let control_start = pos;
    let (control_points, weights) = read_control_points(b, &mut pos, n_poles, cp_dims)?;
    let control_value_offsets = (0..n_poles * cp_dims)
        .map(|ordinal| control_start + ordinal * 9 + 1)
        .collect();

    Some(DecodedCurveBlock {
        curve: NurbsCurve {
            degree: degree as u32,
            knots,
            control_points,
            weights,
            periodic: is_periodic(closure),
        },
        end: pos,
        control_value_offsets,
        rational,
        knot_layout,
        periodic_value_offset,
        degree_value_offset,
    })
}

/// Writable value offsets for a 3D curve cache in one carrier record.
pub(crate) struct CurvePatchLayout {
    /// Tagged-double payload offsets in pole/component order.
    pub(crate) control_value_offsets: Vec<usize>,
    /// Whether every pole includes a fourth rational weight component.
    pub(crate) rational: bool,
    /// Number of control points.
    pub(crate) control_count: usize,
    /// Native unique-knot payloads and expanded run lengths.
    pub(crate) knots: KnotPatchLayout,
    /// Offset immediately after the final control component.
    pub(crate) end: usize,
    /// Payload offset for the closure enum.
    pub(crate) periodic_value_offset: usize,
    /// Payload offset for the degree integer.
    pub(crate) degree_value_offset: usize,
}

/// Locate the first valid 3D curve cache in a carrier record.
pub(crate) fn first_curve_patch_layout(record: &[u8]) -> Option<CurvePatchLayout> {
    let decoded = INT_WIDTHS.into_iter().find_map(|int_width| {
        marker_positions(record)
            .into_iter()
            .find_map(|position| decode_curve_block(record, position, int_width))
    })?;
    Some(CurvePatchLayout {
        control_count: decoded.curve.control_points.len(),
        control_value_offsets: decoded.control_value_offsets,
        rational: decoded.rational,
        knots: decoded.knot_layout.into(),
        end: decoded.end,
        periodic_value_offset: decoded.periodic_value_offset,
        degree_value_offset: decoded.degree_value_offset,
    })
}

/// Locate the final valid 3D curve cache in a carrier record.
pub(crate) fn final_curve_patch_layout(record: &[u8]) -> Option<CurvePatchLayout> {
    let decoded = INT_WIDTHS.into_iter().find_map(|int_width| {
        marker_positions(record)
            .into_iter()
            .filter_map(|position| decode_curve_block(record, position, int_width))
            .next_back()
    })?;
    Some(CurvePatchLayout {
        control_count: decoded.curve.control_points.len(),
        control_value_offsets: decoded.control_value_offsets,
        rational: decoded.rational,
        knots: decoded.knot_layout.into(),
        end: decoded.end,
        periodic_value_offset: decoded.periodic_value_offset,
        degree_value_offset: decoded.degree_value_offset,
    })
}

/// The decoded payload of a 2D `nubs` or `nurbs` pcurve block.
pub struct NurbsPcurve {
    /// Curve degree.
    pub degree: u32,
    /// Full clamped knot vector.
    pub knots: Vec<f64>,
    /// UV control points in surface-parameter space, without length scaling.
    pub control_points: Vec<Point2>,
    /// Per-pole homogeneous weights; absent for a `nubs` block.
    pub weights: Option<Vec<f64>>,
    /// Whether the parameter curve is periodic.
    pub periodic: bool,
}

/// Writable value offsets for one 2D pcurve cache.
pub(crate) struct PcurvePatchLayout {
    /// Tagged-integer payload offset for the curve degree.
    pub(crate) degree_value_offset: usize,
    /// Tagged-double payload offsets in `(u, v)` pole order.
    pub(crate) control_value_offsets: Vec<usize>,
    /// Tagged-double payload offsets for homogeneous weights.
    pub(crate) weight_value_offsets: Vec<usize>,
    /// Number of UV control points.
    pub(crate) control_count: usize,
    /// Native unique-knot payloads and expanded run lengths.
    pub(crate) knots: KnotPatchLayout,
    /// Payload offset for the closure enum.
    pub(crate) periodic_value_offset: usize,
    /// Offset immediately after the final UV control component.
    pub(crate) control_end: usize,
}

/// Locate the final valid non-rational 2D pcurve block in a carrier record.
pub(crate) fn final_pcurve_patch_layout(record: &[u8]) -> Option<PcurvePatchLayout> {
    INT_WIDTHS
        .into_iter()
        .find_map(|int_width| final_pcurve_patch_layout_at(record, int_width))
}

fn final_pcurve_patch_layout_at(record: &[u8], int_width: usize) -> Option<PcurvePatchLayout> {
    marker_positions(record)
        .into_iter()
        .filter_map(|marker_pos| {
            let (_cp_dims, marker_len, rational) = marker_at(record, marker_pos)?;
            let mut pos = marker_pos + marker_len;
            let degree_value_offset = pos + 1;
            let degree = take_tagged_int(record, &mut pos, 0x04, int_width)?;
            if !(1..=20).contains(&degree) {
                return None;
            }
            let periodic_value_offset = pos + 1;
            let _closure = take_tagged_int(record, &mut pos, 0x15, int_width)?;
            let unique = take_tagged_int(record, &mut pos, 0x04, int_width)?;
            if !(1..=1000).contains(&unique) {
                return None;
            }
            let (_knots, control_count, knot_layout) =
                read_knots(record, &mut pos, unique as usize, degree, int_width)?;
            let mut offsets = Vec::with_capacity(control_count * 2);
            let mut weight_offsets = Vec::with_capacity(control_count * usize::from(rational));
            for _ in 0..control_count * 2 {
                if record.get(pos) != Some(&0x06) {
                    return None;
                }
                offsets.push(pos + 1);
                pos += 9;
                if rational && offsets.len() % 2 == 0 {
                    if record.get(pos) != Some(&0x06) {
                        return None;
                    }
                    weight_offsets.push(pos + 1);
                    pos += 9;
                }
            }
            Some(PcurvePatchLayout {
                degree_value_offset,
                control_value_offsets: offsets,
                weight_value_offsets: weight_offsets,
                control_count,
                knots: knot_layout.into(),
                periodic_value_offset,
                control_end: pos,
            })
        })
        .next_back()
}

/// Decode the parameter-space fit tolerance immediately following the UV cache.
pub(crate) fn decode_pcurve_fit_tolerance(record: &[u8]) -> Option<f64> {
    let layout = final_pcurve_patch_layout(record)?;
    (record.get(layout.control_end) == Some(&0x06))
        .then(|| read_f64(record, layout.control_end + 1))
        .flatten()
}

fn decode_pcurve_block(b: &[u8], marker_pos: usize, int_width: usize) -> Option<NurbsPcurve> {
    decode_pcurve_block_with_end(b, marker_pos, int_width).map(|(pcurve, _)| pcurve)
}

fn decode_pcurve_block_with_end(
    b: &[u8],
    marker_pos: usize,
    int_width: usize,
) -> Option<(NurbsPcurve, usize)> {
    let (_cp_dims, marker_len, rational) = marker_at(b, marker_pos)?;
    let mut pos = marker_pos + marker_len;
    let degree = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    if !(1..=20).contains(&degree) {
        return None;
    }
    let closure = take_tagged_int(b, &mut pos, 0x15, int_width)?;
    let n_uniq = take_tagged_int(b, &mut pos, 0x04, int_width)?;
    if !(1..=1000).contains(&n_uniq) {
        return None;
    }
    let (knots, n_poles, _knot_layout) =
        read_knots(b, &mut pos, n_uniq as usize, degree, int_width)?;
    let mut control_points = Vec::with_capacity(n_poles);
    let mut weights = rational.then(|| Vec::with_capacity(n_poles));
    for _ in 0..n_poles {
        if *b.get(pos)? != 0x06 {
            return None;
        }
        let u = read_f64(b, pos + 1)?;
        pos += 9;
        if *b.get(pos)? != 0x06 {
            return None;
        }
        let v = read_f64(b, pos + 1)?;
        pos += 9;
        control_points.push(Point2::new(u, v));
        if let Some(weights) = weights.as_mut() {
            if *b.get(pos)? != 0x06 {
                return None;
            }
            weights.push(read_f64(b, pos + 1)?);
            pos += 9;
        }
    }
    Some((
        NurbsPcurve {
            degree: degree as u32,
            knots,
            control_points,
            weights,
            periodic: is_periodic(closure),
        },
        pos,
    ))
}

/// Decode the face-surface cache of a spline surface record: the LAST valid
/// surface block in the record (the final `setSurfaceShape` cache; earlier
/// blocks are support surfaces or 2D pcurves). Returns `None` when no surface
/// block is present or parseable.
pub fn decode_surface_cache(record_bytes: &[u8]) -> Option<NurbsSurface> {
    INT_WIDTHS
        .into_iter()
        .find_map(|int_width| decode_surface_cache_at(record_bytes, int_width))
}

fn decode_surface_cache_at(record_bytes: &[u8], int_width: usize) -> Option<NurbsSurface> {
    let caches = marker_positions(record_bytes)
        .into_iter()
        .filter_map(|pos| decode_surface_block(record_bytes, pos, int_width))
        .map(|decoded| decoded.surface);
    if record_bytes
        .windows(b"comp_spl_sur".len())
        .any(|window| window == b"comp_spl_sur")
    {
        caches.into_iter().next()
    } else {
        caches.into_iter().next_back()
    }
}

/// A decoded native procedural definition and the fit contract of its solved cache.
pub struct DecodedProceduralSurface {
    /// The native procedural surface construction (blend, sweep, loft, or
    /// taper family) decoded from its subtype-dispatched inline fields.
    pub definition: DecodedProceduralSurfaceDefinition,
    /// `surface_fit_tolerance` of the cached B-spline block, if present.
    /// `0.0` indicates fidelity to the procedural surface rather than
    /// identity with a primitive ([spec §7.5](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/f3d.md#75-nubsnurbs-blocks-b-spline-curves-and-surfaces)).
    pub cache_fit_tolerance: Option<f64>,
}

/// Source-native procedural semantics before embedded geometry is assigned IR ids.
pub enum DecodedProceduralSurfaceDefinition {
    /// Exact NURBS construction and retained native U/V intervals.
    Exact {
        /// Ordered U and V intervals.
        parameter_ranges: [[f64; 2]; 2],
        /// Native ASM extension integer.
        extension: i64,
    },
    /// Native compound surface with ordered scalar/component pairs.
    Compound {
        /// Ordered native parameters.
        parameters: Vec<f64>,
        /// Ordered embedded component surfaces.
        components: Vec<SurfaceGeometry>,
    },
    /// Native taper family with shared carriers and subtype tail.
    Taper {
        /// Embedded base surface.
        support: SurfaceGeometry,
        /// Embedded reference curve.
        reference: NurbsCurve,
        /// Embedded UV curve, absent for `nullbs`.
        pcurve: Option<NurbsPcurve>,
        /// Native taper parameter.
        parameter: f64,
        /// Subtype-specific tail.
        taper: cadmpeg_ir::geometry::TaperSurfaceKind,
    },
    /// Native loft construction graph with embedded carriers.
    Loft(EmbeddedLoft),
    /// Native compound-loft graph with embedded carriers.
    CompoundLoft(Box<EmbeddedCompoundLoft>),
    /// Native G2 blend construction with embedded carriers.
    G2Blend(Box<EmbeddedG2Blend>),
    /// Ruled interpolation between two ordered profile curves.
    Ruled {
        /// First embedded profile.
        first: NurbsCurve,
        /// Second embedded profile.
        second: NurbsCurve,
    },
    /// Translational sum of two curves around a stored origin.
    Sum {
        /// First embedded curve.
        first: NurbsCurve,
        /// Second embedded curve.
        second: NurbsCurve,
        /// Native model-space origin.
        basepoint: Vector3,
    },
    /// Revolution of an embedded profile around an axis.
    Revolution {
        /// Embedded profile curve.
        directrix: NurbsCurve,
        /// Point on the axis in model space.
        axis_origin: Point3,
        /// Unit axis direction.
        axis_direction: Vector3,
        /// Angular interval from the solved surface cache.
        angular_interval: [f64; 2],
        /// Native profile parameter interval.
        parameter_interval: [f64; 2],
    },
    /// Signed offset from an embedded support surface.
    Offset {
        /// Embedded support surface.
        support: SurfaceGeometry,
        /// Signed model-space distance.
        distance: f64,
        /// Native U sense enum.
        u_sense: i64,
        /// Native V sense enum.
        v_sense: i64,
        /// Ordered conditional ASM flags.
        extension_flags: Vec<bool>,
    },
    /// Translation of an embedded directrix along a length-bearing direction.
    Extrusion {
        /// Embedded directrix cache.
        directrix: NurbsCurve,
        /// Length-bearing sweep direction.
        direction: Vector3,
    },
    /// Rolling-ball blend with embedded support and spine caches.
    Blend {
        /// Embedded support caches in side order.
        supports: Box<[Option<NurbsSurface>; 2]>,
        /// Embedded center/spine curve.
        spine: Option<NurbsCurve>,
        /// Signed radius law.
        radius: BlendRadiusLaw,
        /// Blend cross-section family.
        cross_section: BlendCrossSection,
        /// Complete native construction graph when the full layout decoded.
        native: Option<Box<EmbeddedRollingBall>>,
    },
    /// Variable-radius blend with a complete embedded construction graph.
    VariableBlend(Box<EmbeddedVariableBlend>),
    /// Vertex-blend patch with complete embedded boundary graphs.
    VertexBlend(Box<EmbeddedVertexBlend>),
}

pub(crate) struct EmbeddedRollingBallSide {
    pub(crate) label: String,
    pub(crate) surface: Option<SurfaceGeometry>,
    pub(crate) curve: NurbsCurve,
    pub(crate) pcurve: Option<NurbsPcurve>,
    pub(crate) location: Point3,
    pub(crate) secondary_pcurve: Option<NurbsPcurve>,
    pub(crate) exact_support: Option<NurbsSurface>,
}

pub(crate) struct EmbeddedRollingBallThirdSide {
    pub(crate) label: String,
    pub(crate) surface: SurfaceGeometry,
    pub(crate) curve: NurbsCurve,
    pub(crate) pcurve: Option<NurbsPcurve>,
    pub(crate) direction: Vector3,
    pub(crate) secondary_pcurve: Option<NurbsPcurve>,
    pub(crate) extension: i64,
    pub(crate) tertiary_pcurve: Option<NurbsPcurve>,
    pub(crate) flag: bool,
}

pub(crate) struct EmbeddedVariableBlendSide {
    pub(crate) label: String,
    pub(crate) surface: SurfaceGeometry,
    pub(crate) curve: NurbsCurve,
    pub(crate) pcurve: Option<NurbsPcurve>,
    pub(crate) location: Point3,
    pub(crate) secondary_pcurve: Option<NurbsPcurve>,
    pub(crate) scalar: f64,
    pub(crate) tertiary_pcurve: Option<NurbsPcurve>,
}

/// Embedded native variable blend before stable IR ids are assigned.
pub struct EmbeddedVariableBlend {
    pub(crate) sides: Box<[EmbeddedVariableBlendSide; 2]>,
    pub(crate) primary_curve: NurbsCurve,
    pub(crate) offsets: [f64; 2],
    pub(crate) radius_kind: i64,
    pub(crate) first_value: cadmpeg_ir::geometry::VariableBlendValue,
    pub(crate) second_value: Option<cadmpeg_ir::geometry::VariableBlendValue>,
    pub(crate) chamfer: Option<Box<cadmpeg_ir::geometry::VariableBlendChamfer>>,
    pub(crate) single_radius_tail: Option<cadmpeg_ir::geometry::VariableBlendSingleRadiusTail>,
    pub(crate) u_range: [f64; 2],
    pub(crate) v_range: [f64; 2],
    pub(crate) shape_prefix: i64,
    pub(crate) shape_parameter: f64,
    pub(crate) shape_length: f64,
    pub(crate) shape_tail: i64,
    pub(crate) shape_extensions: [i64; 3],
    pub(crate) secondary_curve: NurbsCurve,
    pub(crate) convexity: i64,
    pub(crate) render_blend: i64,
    pub(crate) post_range: [f64; 2],
    pub(crate) post_curve: NurbsCurve,
    pub(crate) post_pcurve: Option<NurbsPcurve>,
}

pub(crate) enum EmbeddedVertexBlendBoundaryGeometry {
    Circle {
        curve: NurbsCurve,
        form: i64,
        twists: Vec<Point3>,
        parameters: [f64; 2],
        sense: i64,
    },
    Degenerate {
        location: Point3,
        normals: [Vector3; 2],
    },
    Pcurve {
        surface: SurfaceGeometry,
        pcurve: Option<NurbsPcurve>,
        sense: i64,
        fit_tolerance: f64,
    },
    Plane {
        normal: Vector3,
        parameters: [f64; 2],
        curve: NurbsCurve,
    },
}

pub(crate) struct EmbeddedVertexBlendBoundary {
    pub(crate) boundary_type: i64,
    pub(crate) magic: Point3,
    pub(crate) u_smoothing: i64,
    pub(crate) v_smoothing: i64,
    pub(crate) fullness: f64,
    pub(crate) geometry: EmbeddedVertexBlendBoundaryGeometry,
}

/// Embedded native vertex blend before stable IR ids are assigned.
pub struct EmbeddedVertexBlend {
    pub(crate) boundaries: Vec<EmbeddedVertexBlendBoundary>,
    pub(crate) grid_size: i64,
    pub(crate) fit_tolerance: f64,
}

pub(crate) enum EmbeddedRollingBallRadiusSelector {
    None,
    Value(f64),
}

/// Embedded native rolling-ball graph before stable IR ids are assigned.
pub struct EmbeddedRollingBall {
    pub(crate) sides: Box<[EmbeddedRollingBallSide; 2]>,
    pub(crate) slice: NurbsCurve,
    pub(crate) offsets: [f64; 2],
    pub(crate) radius_selector: EmbeddedRollingBallRadiusSelector,
    pub(crate) u_range: [f64; 2],
    pub(crate) v_range: [f64; 2],
    pub(crate) parameters: [f64; 3],
    pub(crate) tail: i64,
    pub(crate) discontinuities: [Vec<f64>; 3],
    pub(crate) third: Option<Box<EmbeddedRollingBallThirdSide>>,
}

pub(crate) struct EmbeddedG2Side {
    pub(crate) label: String,
    pub(crate) surface: SurfaceGeometry,
    pub(crate) curve: NurbsCurve,
    pub(crate) pcurves: [Option<NurbsPcurve>; 2],
    pub(crate) direction: Vector3,
}

pub(crate) enum EmbeddedG2FirstShape {
    Full {
        surface: Option<NurbsSurface>,
        tolerance: Option<f64>,
    },
    None {
        coefficients: [f64; 9],
        tolerance: f64,
        extension: Option<cadmpeg_ir::geometry::LoftBridgeToken>,
        pcurve: Option<NurbsPcurve>,
    },
}

/// Embedded native G2 blend graph before stable IR ids are assigned.
pub struct EmbeddedG2Blend {
    pub(crate) first: EmbeddedG2Side,
    pub(crate) singularity: i64,
    pub(crate) first_shape: EmbeddedG2FirstShape,
    pub(crate) second: EmbeddedG2Side,
    pub(crate) second_exact_surface: NurbsSurface,
    pub(crate) center_curve: NurbsCurve,
    pub(crate) center_parameters: [f64; 2],
    pub(crate) center_flag: i64,
    pub(crate) parameter_ranges: [[f64; 2]; 2],
    pub(crate) trailing_parameters: [f64; 4],
    pub(crate) discontinuities: [Vec<f64>; 3],
}

#[allow(clippy::option_option)] // Outer None is parse failure; inner None is native nullbs.
fn decode_nullable_embedded_pcurve(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<Option<NurbsPcurve>> {
    let saved = *position;
    if take_native_ident(bytes, position).as_deref() == Some("nullbs") {
        return Some(None);
    }
    *position = saved;
    let (pcurve, end) = decode_pcurve_block_with_end(bytes, *position, int_width)?;
    *position = end;
    Some(Some(pcurve))
}

fn decode_g2_side(bytes: &[u8], position: &mut usize, int_width: usize) -> Option<EmbeddedG2Side> {
    let label = take_native_string(bytes, position)?;
    let surface = decode_embedded_surface(bytes, position, int_width)?;
    let curve = decode_curve_block(bytes, *position, int_width)?;
    *position = curve.end;
    let first = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let direction = take_native_vec3(bytes, position, 0x14)?;
    let second = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    Some(EmbeddedG2Side {
        label,
        surface,
        curve: curve.curve,
        pcurves: [first, second],
        direction: Vector3::new(direction[0], direction[1], direction[2]),
    })
}

fn take_bridge_token(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<cadmpeg_ir::geometry::LoftBridgeToken> {
    use cadmpeg_ir::geometry::LoftBridgeToken;
    match *bytes.get(*position)? {
        0x0a | 0x0b => Some(LoftBridgeToken::Boolean(take_bool(bytes, position)?)),
        0x04 => Some(LoftBridgeToken::Integer(take_tagged_int(
            bytes, position, 0x04, int_width,
        )?)),
        0x06 => Some(LoftBridgeToken::Double(take_f64(bytes, position)?)),
        0x15 => Some(LoftBridgeToken::Enum(take_tagged_int(
            bytes, position, 0x15, int_width,
        )?)),
        0x07..=0x09 => Some(LoftBridgeToken::Text(take_native_string(bytes, position)?)),
        _ => None,
    }
}

fn decode_g2_blend_spl_sur(
    record_bytes: &[u8],
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 2] = [b"g2_blend_spl_sur", b"g2blnsur"];
    let (start, name_len) = names.into_iter().find_map(|name| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name.len()))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name_len + 3;
    let first = decode_g2_side(span, &mut position, int_width)?;
    let singularity = take_tagged_int(span, &mut position, 0x15, int_width)?;
    let first_shape = if matches!(span.get(position), Some(0x0d | 0x0e)) {
        let saved = position;
        if take_native_ident(span, &mut position).as_deref() == Some("nullbs") {
            EmbeddedG2FirstShape::Full {
                surface: None,
                tolerance: None,
            }
        } else {
            position = saved;
            let surface = decode_surface_block(span, position, int_width)?;
            position = surface.end;
            EmbeddedG2FirstShape::Full {
                surface: Some(surface.surface),
                tolerance: Some(take_f64(span, &mut position)? * LEN_TO_MM),
            }
        }
    } else {
        let mut coefficients = [0.0; 9];
        for coefficient in &mut coefficients {
            *coefficient = take_f64(span, &mut position)?;
        }
        let tolerance = take_f64(span, &mut position)? * LEN_TO_MM;
        let extension = (!matches!(span.get(position), Some(0x07..=0x09 | 0x0d | 0x0e)))
            .then(|| take_bridge_token(span, &mut position, int_width))
            .flatten();
        let pcurve = decode_nullable_embedded_pcurve(span, &mut position, int_width)?;
        EmbeddedG2FirstShape::None {
            coefficients,
            tolerance,
            extension,
            pcurve,
        }
    };
    let second = decode_g2_side(span, &mut position, int_width)?;
    let second_exact = decode_surface_block(span, position, int_width)?;
    position = second_exact.end;
    let center = decode_curve_block(span, position, int_width)?;
    position = center.end;
    let center_parameters = [
        take_f64(span, &mut position)?,
        take_f64(span, &mut position)?,
    ];
    let center_flag = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let parameter_ranges = [
        [
            take_f64(span, &mut position)?,
            take_f64(span, &mut position)?,
        ],
        [
            take_f64(span, &mut position)?,
            take_f64(span, &mut position)?,
        ],
    ];
    let mut trailing_parameters = [0.0; 4];
    for parameter in &mut trailing_parameters {
        *parameter = take_f64(span, &mut position)?;
    }
    let cache = decode_surface_block(span, position, int_width)?;
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    position = cache.end + 9;
    let discontinuities = [
        take_float_array(span, &mut position, int_width)?,
        take_float_array(span, &mut position, int_width)?,
        take_float_array(span, &mut position, int_width)?,
    ];
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::G2Blend(Box::new(EmbeddedG2Blend {
            first,
            singularity,
            first_shape,
            second,
            second_exact_surface: second_exact.surface,
            center_curve: center.curve,
            center_parameters,
            center_flag,
            parameter_ranges,
            trailing_parameters,
            discontinuities,
        })),
        cache_fit_tolerance,
    })
}

pub(crate) struct EmbeddedLoftProfileData {
    pub(crate) surface: SurfaceGeometry,
    pub(crate) pcurve: Option<NurbsPcurve>,
    pub(crate) first_flag: bool,
    pub(crate) asm_extension: i64,
    pub(crate) subdata: cadmpeg_ir::geometry::LoftSubdata,
    pub(crate) direction: Option<Vector3>,
}

pub(crate) struct EmbeddedLoftProfileMember {
    pub(crate) type_code: i64,
    pub(crate) curve: NurbsCurve,
    pub(crate) data: EmbeddedLoftProfileData,
}

pub(crate) struct EmbeddedLoftPath {
    pub(crate) curve: NurbsCurve,
    pub(crate) auxiliaries: Vec<NurbsCurve>,
    pub(crate) flag: i64,
}

pub(crate) struct EmbeddedLoftSectionEntry {
    pub(crate) parameter: f64,
    pub(crate) profile: Vec<EmbeddedLoftProfileMember>,
    pub(crate) path: EmbeddedLoftPath,
}

/// Embedded native loft graph before its carriers receive stable IR ids.
pub struct EmbeddedLoft {
    pub(crate) sections: [Vec<EmbeddedLoftSectionEntry>; 2],
    pub(crate) parameter_ranges: [[f64; 2]; 2],
    pub(crate) closures: [i64; 2],
    pub(crate) singularities: [i64; 2],
    pub(crate) mode: i64,
    pub(crate) bridge: Vec<cadmpeg_ir::geometry::LoftBridgeToken>,
}

pub(crate) struct EmbeddedCompoundLoftScale {
    pub(crate) members: Vec<EmbeddedLoftProfileMember>,
    pub(crate) path: NurbsCurve,
    pub(crate) auxiliaries: Vec<NurbsCurve>,
    pub(crate) tail: [i64; 2],
}

pub(crate) enum EmbeddedCompoundLoftDirection {
    Vector(Vector3),
    Curve(NurbsCurve),
}

pub(crate) enum EmbeddedCompoundLoftTail {
    Six {
        flags: [bool; 2],
        scale: Option<Box<EmbeddedCompoundLoftScale>>,
        selector: i64,
        direction: Vector3,
        parameter_range: [f64; 2],
        curve: NurbsCurve,
    },
    Seven {
        first_flag: bool,
        first_scale: Option<Box<EmbeddedCompoundLoftScale>>,
        second_flag: bool,
        second_scale: Option<Box<EmbeddedCompoundLoftScale>>,
        selector: i64,
        direction: Vector3,
        trailing_flags: [bool; 2],
    },
    Zero {
        flags: [bool; 2],
        selector: i64,
        direction: EmbeddedCompoundLoftDirection,
        trailing_flags: [bool; 2],
    },
}

/// Embedded native compound loft before stable IR ids are assigned.
pub struct EmbeddedCompoundLoft {
    pub(crate) scales: Box<[Option<EmbeddedCompoundLoftScale>; 4]>,
    pub(crate) fifth_scale: Option<Box<EmbeddedCompoundLoftScale>>,
    pub(crate) flags: [bool; 2],
    pub(crate) tail: EmbeddedCompoundLoftTail,
}

#[allow(clippy::option_option)] // Outer None is parse failure; inner None is an absent scale slot.
fn decode_compound_loft_scale(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<Option<EmbeddedCompoundLoftScale>> {
    if matches!(bytes.get(*position), Some(0x0a | 0x0b)) {
        return Some(None);
    }
    let count = usize::try_from(take_tagged_int(bytes, position, 0x04, int_width)?).ok()?;
    if count > 100_000 {
        return None;
    }
    let mut members = Vec::with_capacity(count);
    for _ in 0..count {
        let type_code = take_tagged_int(bytes, position, 0x04, int_width)?;
        let curve = decode_curve_block(bytes, *position, int_width)?;
        *position = curve.end;
        let data = decode_loft_profile_data(bytes, position, int_width)?;
        members.push(EmbeddedLoftProfileMember {
            type_code,
            curve: curve.curve,
            data,
        });
    }
    let path = decode_curve_block(bytes, *position, int_width)?;
    *position = path.end;
    let auxiliary_count =
        usize::try_from(take_tagged_int(bytes, position, 0x04, int_width)?).ok()?;
    if auxiliary_count > 100_000 {
        return None;
    }
    let mut auxiliaries = Vec::with_capacity(auxiliary_count);
    for _ in 0..auxiliary_count {
        let curve = decode_curve_block(bytes, *position, int_width)?;
        *position = curve.end;
        auxiliaries.push(curve.curve);
    }
    let tail = [
        take_tagged_int(bytes, position, 0x04, int_width)?,
        take_tagged_int(bytes, position, 0x04, int_width)?,
    ];
    Some(Some(EmbeddedCompoundLoftScale {
        members,
        path: path.curve,
        auxiliaries,
        tail,
    }))
}

fn decode_loft_subdata(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<cadmpeg_ir::geometry::LoftSubdata> {
    use cadmpeg_ir::geometry::{LoftSubdata, LoftSubdataRow};
    let type_code = take_tagged_int(bytes, position, 0x04, int_width)?;
    let row_count = take_tagged_int(bytes, position, 0x04, int_width)?;
    let column_count = take_tagged_int(bytes, position, 0x04, int_width)?;
    let rows_to_read = if type_code == 211 {
        1
    } else {
        usize::try_from(row_count).ok()?
    };
    let columns_to_read = usize::try_from(column_count).ok()?;
    let mut rows = Vec::with_capacity(rows_to_read);
    for _ in 0..rows_to_read {
        let parameters = [take_f64(bytes, position)?, take_f64(bytes, position)?];
        let mut columns = Vec::new();
        if type_code != 211 {
            columns.reserve(columns_to_read);
            for _ in 0..columns_to_read {
                columns.push([take_f64(bytes, position)?, take_f64(bytes, position)?]);
            }
        }
        rows.push(LoftSubdataRow {
            parameters,
            columns,
        });
    }
    Some(LoftSubdata {
        type_code,
        row_count,
        column_count,
        rows,
    })
}

fn decode_loft_profile_data(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<EmbeddedLoftProfileData> {
    let surface = decode_embedded_surface(bytes, position, int_width)?;
    let saved = *position;
    let pcurve = if take_native_ident(bytes, position).as_deref() == Some("nullbs") {
        None
    } else {
        *position = saved;
        let (pcurve, end) = decode_pcurve_block_with_end(bytes, *position, int_width)?;
        *position = end;
        Some(pcurve)
    };
    let first_flag = take_bool(bytes, position)?;
    let asm_extension = take_tagged_int(bytes, position, 0x04, int_width)?;
    let subdata = decode_loft_subdata(bytes, position, int_width)?;
    let direction = if take_bool(bytes, position)? {
        let value = take_native_vec3(bytes, position, 0x14)?;
        Some(Vector3::new(value[0], value[1], value[2]))
    } else {
        None
    };
    Some(EmbeddedLoftProfileData {
        surface,
        pcurve,
        first_flag,
        asm_extension,
        subdata,
        direction,
    })
}

fn decode_loft_section(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<Vec<EmbeddedLoftSectionEntry>> {
    let count = usize::try_from(take_tagged_int(bytes, position, 0x04, int_width)?).ok()?;
    let mut entries = Vec::with_capacity(count);
    for _ in 0..count {
        let parameter = take_f64(bytes, position)?;
        let member_count =
            usize::try_from(take_tagged_int(bytes, position, 0x04, int_width)?).ok()?;
        let mut profile = Vec::with_capacity(member_count);
        for _ in 0..member_count {
            let type_code = take_tagged_int(bytes, position, 0x04, int_width)?;
            let curve = decode_curve_block(bytes, *position, int_width)?;
            *position = curve.end;
            let data = decode_loft_profile_data(bytes, position, int_width)?;
            profile.push(EmbeddedLoftProfileMember {
                type_code,
                curve: curve.curve,
                data,
            });
        }
        let curve = decode_curve_block(bytes, *position, int_width)?;
        *position = curve.end;
        let auxiliary_count =
            usize::try_from(take_tagged_int(bytes, position, 0x04, int_width)?).ok()?;
        let mut auxiliaries = Vec::with_capacity(auxiliary_count);
        for _ in 0..auxiliary_count {
            let auxiliary = decode_curve_block(bytes, *position, int_width)?;
            *position = auxiliary.end;
            auxiliaries.push(auxiliary.curve);
        }
        let flag = take_tagged_int(bytes, position, 0x04, int_width)?;
        entries.push(EmbeddedLoftSectionEntry {
            parameter,
            profile,
            path: EmbeddedLoftPath {
                curve: curve.curve,
                auxiliaries,
                flag,
            },
        });
    }
    Some(entries)
}

fn decode_loft_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    use cadmpeg_ir::geometry::LoftBridgeToken;
    let names: [&[u8]; 2] = [b"loft_spl_sur", b"loftsur"];
    let (start, name_len) = names.into_iter().find_map(|name| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name.len()))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name_len + 3;
    let sections = [
        decode_loft_section(span, &mut position, int_width)?,
        decode_loft_section(span, &mut position, int_width)?,
    ];
    let parameter_ranges = [
        [
            take_f64(span, &mut position)?,
            take_f64(span, &mut position)?,
        ],
        [
            take_f64(span, &mut position)?,
            take_f64(span, &mut position)?,
        ],
    ];
    let closures = [
        take_tagged_int(span, &mut position, 0x15, int_width)?,
        take_tagged_int(span, &mut position, 0x15, int_width)?,
    ];
    let singularities = [
        take_tagged_int(span, &mut position, 0x15, int_width)?,
        take_tagged_int(span, &mut position, 0x15, int_width)?,
    ];
    let mode = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let (cache_at, cache) = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width).map(|cache| (at, cache)))
        .next_back()?;
    let mut bridge = Vec::new();
    while position < cache_at {
        match *span.get(position)? {
            0x0a | 0x0b => bridge.push(LoftBridgeToken::Boolean(take_bool(span, &mut position)?)),
            0x04 => bridge.push(LoftBridgeToken::Integer(take_tagged_int(
                span,
                &mut position,
                0x04,
                int_width,
            )?)),
            0x06 => bridge.push(LoftBridgeToken::Double(take_f64(span, &mut position)?)),
            0x15 => bridge.push(LoftBridgeToken::Enum(take_tagged_int(
                span,
                &mut position,
                0x15,
                int_width,
            )?)),
            0x07..=0x09 => {
                bridge.push(LoftBridgeToken::Text(take_native_string(
                    span,
                    &mut position,
                )?));
            }
            _ => return None,
        }
    }
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Loft(EmbeddedLoft {
            sections,
            parameter_ranges,
            closures,
            singularities,
            mode,
            bridge,
        }),
        cache_fit_tolerance,
    })
}

fn decode_compound_loft_spl_sur(
    record_bytes: &[u8],
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    let name = b"cl_loft_spl_sur";
    let start = record_bytes.windows(name.len() + 3).position(|window| {
        window[0] == 0x0f
            && matches!(window[1], 0x0d | 0x0e)
            && usize::from(window[2]) == name.len()
            && &window[3..] == name
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name.len() + 3;
    let cache = decode_surface_block(span, position, int_width)?;
    position = cache.end;
    let cache_fit_tolerance = Some(take_f64(span, &mut position)? * LEN_TO_MM);
    let scales = Box::new([
        decode_compound_loft_scale(span, &mut position, int_width)?,
        decode_compound_loft_scale(span, &mut position, int_width)?,
        decode_compound_loft_scale(span, &mut position, int_width)?,
        decode_compound_loft_scale(span, &mut position, int_width)?,
    ]);
    let fifth_scale = if span.get(position) == Some(&0x04) {
        decode_compound_loft_scale(span, &mut position, int_width)?.map(Box::new)
    } else {
        None
    };
    let flags = [
        take_bool(span, &mut position)?,
        take_bool(span, &mut position)?,
    ];
    let kind = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let tail = match kind {
        6 => {
            let tail_flags = [
                take_bool(span, &mut position)?,
                take_bool(span, &mut position)?,
            ];
            let scale = decode_compound_loft_scale(span, &mut position, int_width)?.map(Box::new);
            let selector = take_tagged_int(span, &mut position, 0x04, int_width)?;
            let direction = take_native_vec3(span, &mut position, 0x14)?;
            let parameter_range = [
                take_range_value(span, &mut position)?,
                take_range_value(span, &mut position)?,
            ];
            let curve = decode_curve_block(span, position, int_width)?;
            EmbeddedCompoundLoftTail::Six {
                flags: tail_flags,
                scale,
                selector,
                direction: Vector3::new(direction[0], direction[1], direction[2]),
                parameter_range,
                curve: curve.curve,
            }
        }
        7 => {
            let first_flag = take_bool(span, &mut position)?;
            let first_scale =
                decode_compound_loft_scale(span, &mut position, int_width)?.map(Box::new);
            let second_flag = take_bool(span, &mut position)?;
            let second_scale =
                decode_compound_loft_scale(span, &mut position, int_width)?.map(Box::new);
            let selector = take_tagged_int(span, &mut position, 0x04, int_width)?;
            let direction = take_native_vec3(span, &mut position, 0x14)?;
            let trailing_flags = [
                take_bool(span, &mut position)?,
                take_bool(span, &mut position)?,
            ];
            EmbeddedCompoundLoftTail::Seven {
                first_flag,
                first_scale,
                second_flag,
                second_scale,
                selector,
                direction: Vector3::new(direction[0], direction[1], direction[2]),
                trailing_flags,
            }
        }
        0 => {
            let tail_flags = [
                take_bool(span, &mut position)?,
                take_bool(span, &mut position)?,
            ];
            let selector = take_tagged_int(span, &mut position, 0x04, int_width)?;
            let direction = if selector == 0 {
                let value = take_native_vec3(span, &mut position, 0x14)?;
                EmbeddedCompoundLoftDirection::Vector(Vector3::new(value[0], value[1], value[2]))
            } else {
                let curve = decode_curve_block(span, position, int_width)?;
                position = curve.end;
                EmbeddedCompoundLoftDirection::Curve(curve.curve)
            };
            let trailing_flags = [
                take_bool(span, &mut position)?,
                take_bool(span, &mut position)?,
            ];
            EmbeddedCompoundLoftTail::Zero {
                flags: tail_flags,
                selector,
                direction,
                trailing_flags,
            }
        }
        _ => return None,
    };
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::CompoundLoft(Box::new(
            EmbeddedCompoundLoft {
                scales,
                fifth_scale,
                flags,
                tail,
            },
        )),
        cache_fit_tolerance,
    })
}

fn decode_taper_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    use cadmpeg_ir::geometry::TaperSurfaceKind;
    let names: &[(&[u8], u8)] = &[
        (b"taper_spl_sur", 0),
        (b"ortho_spl_sur", 1),
        (b"orthosur", 1),
        (b"edge_tpr_spl_sur", 2),
        (b"shadow_tpr_spl_sur", 3),
        (b"shadowtapersur", 3),
        (b"ruled_tpr_spl_sur", 4),
        (b"ruledtapersur", 4),
        (b"swept_tpr_spl_sur", 5),
        (b"swepttapersur", 5),
    ];
    let (start, name_len, kind) = names.iter().find_map(|(name, kind)| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == *name
            })
            .map(|start| (start, name.len(), *kind))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name_len + 3;
    let support = decode_embedded_surface(span, &mut position, int_width)?;
    let reference = decode_curve_block(span, position, int_width)?;
    position = reference.end;
    let saved = position;
    let pcurve = if take_native_ident(span, &mut position).as_deref() == Some("nullbs") {
        None
    } else {
        position = saved;
        let (pcurve, end) = decode_pcurve_block_with_end(span, position, int_width)?;
        position = end;
        Some(pcurve)
    };
    let parameter = take_f64(span, &mut position)?;
    let cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    position = cache.end + 9;
    let take_draft = |position: &mut usize| {
        let draft = take_native_vec3(span, position, 0x14)?;
        Some(Vector3::new(draft[0], draft[1], draft[2]))
    };
    let taper = match kind {
        0 => TaperSurfaceKind::Standard,
        1 => TaperSurfaceKind::Orthogonal {
            sense: take_bool(span, &mut position)?,
        },
        2 => TaperSurfaceKind::Edge {
            draft: take_draft(&mut position)?,
        },
        3 => TaperSurfaceKind::Shadow {
            draft: take_draft(&mut position)?,
            sine: take_f64(span, &mut position)?,
            cosine: take_f64(span, &mut position)?,
        },
        4 => TaperSurfaceKind::Ruled {
            draft: take_draft(&mut position)?,
            sine: take_f64(span, &mut position)?,
            cosine: take_f64(span, &mut position)?,
            factor: take_f64(span, &mut position)?,
        },
        5 => TaperSurfaceKind::Swept {
            draft: take_draft(&mut position)?,
            sine: take_f64(span, &mut position)?,
            cosine: take_f64(span, &mut position)?,
        },
        _ => return None,
    };
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Taper {
            support,
            reference: reference.curve,
            pcurve,
            parameter,
            taper,
        },
        cache_fit_tolerance,
    })
}

fn decode_comp_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    let name = b"comp_spl_sur";
    let start = record_bytes.windows(name.len() + 3).position(|window| {
        window[0] == 0x0f
            && matches!(window[1], 0x0d | 0x0e)
            && usize::from(window[2]) == name.len()
            && &window[3..] == name
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let cache = marker_positions(span)
        .into_iter()
        .find_map(|at| decode_surface_block(span, at, int_width))?;
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    let mut position = cache.end + 9;
    let parameters = take_float_array(span, &mut position, int_width)?;
    let mut components = Vec::with_capacity(parameters.len());
    for _ in 0..parameters.len() {
        components.push(decode_embedded_surface(span, &mut position, int_width)?);
    }
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Compound {
            parameters,
            components,
        },
        cache_fit_tolerance,
    })
}

fn decode_off_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 2] = [b"off_spl_sur", b"offsur"];
    let (start, name_len, modern) = names.into_iter().find_map(|name| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name.len(), name == b"off_spl_sur"))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name_len + 3;
    let support = decode_embedded_surface(span, &mut position, int_width)?;
    let distance = take_f64(span, &mut position)? * LEN_TO_MM;
    let u_sense = take_tagged_int(span, &mut position, 0x15, int_width)?;
    let v_sense = take_tagged_int(span, &mut position, 0x15, int_width)?;
    let mut extension_flags = Vec::new();
    if modern {
        let first = take_bool(span, &mut position)?;
        extension_flags.push(first);
        if first {
            extension_flags.push(take_bool(span, &mut position)?);
            if matches!(span.get(position), Some(0x0a | 0x0b)) {
                extension_flags.push(take_bool(span, &mut position)?);
            }
        }
    }
    let cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Offset {
            support,
            distance,
            u_sense,
            v_sense,
            extension_flags,
        },
        cache_fit_tolerance,
    })
}

fn decode_rot_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 2] = [b"rot_spl_sur", b"rotsur"];
    let start = names.into_iter().find_map(|name| {
        record_bytes.windows(name.len() + 3).position(|window| {
            window[0] == 0x0f
                && matches!(window[1], 0x0d | 0x0e)
                && usize::from(window[2]) == name.len()
                && &window[3..] == name
        })
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let directrix = marker_positions(span)
        .into_iter()
        .find_map(|at| decode_curve_block(span, at, int_width))?;
    let parameter_interval = [
        *directrix.curve.knots.first()?,
        *directrix.curve.knots.last()?,
    ];
    let mut position = directrix.end;
    let origin = take_native_vec3(span, &mut position, 0x13)?;
    let axis_origin = Point3::new(
        origin[0] * LEN_TO_MM,
        origin[1] * LEN_TO_MM,
        origin[2] * LEN_TO_MM,
    );
    let axis = take_native_vec3(span, &mut position, 0x14)?;
    let axis_direction = normalized(axis)?;
    let cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;
    let angular_interval = [
        *cache.surface.v_knots.first()?,
        *cache.surface.v_knots.last()?,
    ];
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Revolution {
            directrix: directrix.curve,
            axis_origin,
            axis_direction,
            angular_interval,
            parameter_interval,
        },
        cache_fit_tolerance,
    })
}

fn decode_sum_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 2] = [b"sum_spl_sur", b"sumsur"];
    let start = names.into_iter().find_map(|name| {
        record_bytes.windows(name.len() + 3).position(|window| {
            window[0] == 0x0f
                && matches!(window[1], 0x0d | 0x0e)
                && usize::from(window[2]) == name.len()
                && &window[3..] == name
        })
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut decoded_curves = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_curve_block(span, at, int_width));
    let first = decoded_curves.next()?;
    let second = decoded_curves.next()?;
    let mut position = second.end;
    let origin = take_native_vec3(span, &mut position, 0x13)?;
    let basepoint = Vector3::new(
        origin[0] * LEN_TO_MM,
        origin[1] * LEN_TO_MM,
        origin[2] * LEN_TO_MM,
    );
    let cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Sum {
            first: first.curve,
            second: second.curve,
            basepoint,
        },
        cache_fit_tolerance,
    })
}

fn decode_ruled_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 2] = [b"rule_sur", b"rulesur"];
    let start = names.into_iter().find_map(|name| {
        record_bytes.windows(name.len() + 3).position(|window| {
            window[0] == 0x0f
                && matches!(window[1], 0x0d | 0x0e)
                && usize::from(window[2]) == name.len()
                && &window[3..] == name
        })
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut curves = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_curve_block(span, at, int_width).map(|decoded| decoded.curve));
    let first = curves.next()?;
    let second = curves.next()?;
    let cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Ruled { first, second },
        cache_fit_tolerance,
    })
}

fn decode_exact_spl_sur(record_bytes: &[u8], int_width: usize) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 2] = [b"exact_spl_sur", b"exactsur"];
    let (start, name) = names.into_iter().find_map(|name| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|value| value * LEN_TO_MM))
        .flatten();
    let mut position = cache.end + 9;
    let parameter_ranges = [
        [
            take_range_value(span, &mut position)?,
            take_range_value(span, &mut position)?,
        ],
        [
            take_range_value(span, &mut position)?,
            take_range_value(span, &mut position)?,
        ],
    ];
    let extension = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let _ = name;
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Exact {
            parameter_ranges,
            extension,
        },
        cache_fit_tolerance,
    })
}

/// Decode an inline `cyl_spl_sur` translational-extrusion definition.
pub fn decode_cyl_spl_sur(record_bytes: &[u8]) -> Option<DecodedProceduralSurface> {
    INT_WIDTHS
        .into_iter()
        .find_map(|int_width| decode_cyl_spl_sur_at(record_bytes, int_width))
}

fn decode_cyl_spl_sur_at(
    record_bytes: &[u8],
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    let marker = b"\x0f\x0d\x0bcyl_spl_sur";
    let start = record_bytes
        .windows(marker.len())
        .position(|w| w == marker)?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let directrix = decode_curve_cache_at(span, int_width)?;

    let mut doubles = Vec::new();
    let mut direction = None;
    let mut pos = marker.len();
    while pos < span.len() {
        match span[pos] {
            0x06 if direction.is_none() => doubles.push(read_f64(span, pos + 1)?),
            0x14 if direction.is_none() => {
                direction = Some(Vector3::new(
                    read_f64(span, pos + 1)? * LEN_TO_MM,
                    read_f64(span, pos + 9)? * LEN_TO_MM,
                    read_f64(span, pos + 17)? * LEN_TO_MM,
                ));
            }
            _ => {}
        }
        pos = next_token(span, pos, int_width)?;
    }
    let _u_range = [*doubles.first()?, *doubles.get(1)?];
    let decoded_cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;
    let _v_range = [
        *decoded_cache.surface.v_knots.first()?,
        *decoded_cache.surface.v_knots.last()?,
    ];
    let cache_fit_tolerance = (span.get(decoded_cache.end) == Some(&0x06))
        .then(|| read_f64(span, decoded_cache.end + 1).map(|v| v * LEN_TO_MM))
        .flatten();

    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Extrusion {
            directrix,
            direction: direction?,
        },
        cache_fit_tolerance,
    })
}

fn decode_rolling_ball_side(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<EmbeddedRollingBallSide> {
    let label = take_native_string(bytes, position)?;
    let saved = *position;
    let surface = if take_native_ident(bytes, position).as_deref() == Some("null_surface") {
        None
    } else {
        *position = saved;
        Some(decode_embedded_surface(bytes, position, int_width)?)
    };
    let curve = decode_curve_block(bytes, *position, int_width)?;
    *position = curve.end;
    let pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let location = take_native_vec3(bytes, position, 0x13)?;
    let secondary_pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let saved = *position;
    let exact_support = if matches!(
        take_native_ident(bytes, position).as_deref(),
        Some("nullbs" | "null_surface")
    ) {
        None
    } else {
        *position = saved;
        match decode_embedded_surface(bytes, position, int_width)? {
            SurfaceGeometry::Nurbs(surface) => Some(surface),
            _ => return None,
        }
    };
    Some(EmbeddedRollingBallSide {
        label,
        surface,
        curve: curve.curve,
        pcurve,
        location: Point3::new(
            location[0] * LEN_TO_MM,
            location[1] * LEN_TO_MM,
            location[2] * LEN_TO_MM,
        ),
        secondary_pcurve,
        exact_support,
    })
}

fn decode_rolling_ball_third_side(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<EmbeddedRollingBallThirdSide> {
    let label = take_native_string(bytes, position)?;
    let surface = decode_embedded_surface(bytes, position, int_width)?;
    let curve = decode_curve_block(bytes, *position, int_width)?;
    *position = curve.end;
    let pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let direction = take_native_vec3(bytes, position, 0x14)?;
    let secondary_pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let extension = take_tagged_int(bytes, position, 0x04, int_width)?;
    let tertiary_pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let flag = take_bool(bytes, position)?;
    Some(EmbeddedRollingBallThirdSide {
        label,
        surface,
        curve: curve.curve,
        pcurve,
        direction: Vector3::new(direction[0], direction[1], direction[2]),
        secondary_pcurve,
        extension,
        tertiary_pcurve,
        flag,
    })
}

fn decode_variable_blend_side(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<EmbeddedVariableBlendSide> {
    let label = take_native_string(bytes, position)?;
    let surface = decode_embedded_surface(bytes, position, int_width)?;
    let curve = decode_curve_block(bytes, *position, int_width)?;
    *position = curve.end;
    let pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let location = take_native_vec3(bytes, position, 0x13)?;
    let secondary_pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    let scalar = take_f64(bytes, position)?;
    let tertiary_pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
    Some(EmbeddedVariableBlendSide {
        label,
        surface,
        curve: curve.curve,
        pcurve,
        location: Point3::new(
            location[0] * LEN_TO_MM,
            location[1] * LEN_TO_MM,
            location[2] * LEN_TO_MM,
        ),
        secondary_pcurve,
        scalar,
        tertiary_pcurve,
    })
}

fn take_blend_value_name(bytes: &[u8], position: &mut usize) -> Option<String> {
    let saved = *position;
    if let Some(value) = take_native_string(bytes, position) {
        return Some(value);
    }
    *position = saved;
    take_native_ident(bytes, position)
}

fn decode_variable_blend_value(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
    modern: bool,
    depth: usize,
) -> Option<cadmpeg_ir::geometry::VariableBlendValue> {
    use cadmpeg_ir::geometry::{
        LoftBridgeToken, VariableBlendInterpolationPoint, VariableBlendValue,
        VariableBlendValuePayload,
    };
    if depth > 32 {
        return None;
    }
    let name = take_blend_value_name(bytes, position)?;
    let modern_flag = if modern {
        take_bool(bytes, position)?
    } else {
        false
    };
    let discriminator = if bytes.get(*position) == Some(&0x04) {
        take_tagged_int(bytes, position, 0x04, int_width)?
    } else {
        1
    };
    let calibrated = take_tagged_int(bytes, position, 0x15, int_width)?;
    let payload = match name.as_str() {
        "two_ends" => VariableBlendValuePayload::TwoEnds {
            parameters: [take_f64(bytes, position)?, take_f64(bytes, position)?],
            radii: [
                take_f64(bytes, position)? * LEN_TO_MM,
                take_f64(bytes, position)? * LEN_TO_MM,
            ],
        },
        "edge_offset" if discriminator == 0 => VariableBlendValuePayload::EdgeOffset {
            scalars: vec![take_f64(bytes, position)?, take_f64(bytes, position)?],
            lengths: vec![take_f64(bytes, position)? * LEN_TO_MM],
        },
        "edge_offset" if discriminator == 1 => VariableBlendValuePayload::EdgeOffset {
            scalars: vec![take_f64(bytes, position)?],
            lengths: vec![
                take_f64(bytes, position)? * LEN_TO_MM,
                take_f64(bytes, position)? * LEN_TO_MM,
            ],
        },
        "functional" => {
            let parameter = take_f64(bytes, position)?;
            let radius = take_f64(bytes, position)? * LEN_TO_MM;
            let (function, end) = decode_pcurve_block_with_end(bytes, *position, int_width)?;
            *position = end;
            let terminal = if bytes.get(*position) == Some(&0x06) {
                LoftBridgeToken::Double(take_f64(bytes, position)?)
            } else {
                LoftBridgeToken::Text(take_blend_value_name(bytes, position)?)
            };
            VariableBlendValuePayload::Functional {
                parameter,
                radius,
                function: PcurveGeometry::Nurbs {
                    degree: function.degree,
                    knots: function.knots,
                    control_points: function.control_points,
                    weights: function.weights,
                    periodic: function.periodic,
                },
                terminal,
            }
        }
        "const" => VariableBlendValuePayload::Constant {
            parameters: [take_f64(bytes, position)?, take_f64(bytes, position)?],
            radius: take_f64(bytes, position)? * LEN_TO_MM,
            variable_chamfer: take_tagged_int(bytes, position, 0x15, int_width)?,
            chamfer_type: take_tagged_int(bytes, position, 0x15, int_width)?,
            nested: Box::new(decode_variable_blend_value(
                bytes,
                position,
                int_width,
                modern,
                depth + 1,
            )?),
        },
        "interp" => {
            let parameter = take_f64(bytes, position)?;
            let radius = take_f64(bytes, position)? * LEN_TO_MM;
            let (function, end) = decode_pcurve_block_with_end(bytes, *position, int_width)?;
            *position = end;
            let enum_count = take_tagged_int(bytes, position, 0x04, int_width)?;
            let count = usize::try_from(take_tagged_int(bytes, position, 0x04, int_width)?).ok()?;
            if count > 100_000 {
                return None;
            }
            let mut points = Vec::with_capacity(count);
            for _ in 0..count {
                let parameter = take_f64(bytes, position)?;
                let radius = take_f64(bytes, position)? * LEN_TO_MM;
                let tangents = [take_f64(bytes, position)?, take_f64(bytes, position)?];
                let location = take_native_vec3(bytes, position, 0x13)?;
                let normal = take_native_vec3(bytes, position, 0x14)?;
                points.push(VariableBlendInterpolationPoint {
                    parameter,
                    radius,
                    tangents,
                    location: Point3::new(
                        location[0] * LEN_TO_MM,
                        location[1] * LEN_TO_MM,
                        location[2] * LEN_TO_MM,
                    ),
                    normal: Vector3::new(normal[0], normal[1], normal[2]),
                });
            }
            let tail = if take_tagged_int(bytes, position, 0x04, int_width)? != 0 {
                Some([take_f64(bytes, position)?, take_f64(bytes, position)?])
            } else {
                None
            };
            VariableBlendValuePayload::Interpolated {
                parameter,
                radius,
                function: PcurveGeometry::Nurbs {
                    degree: function.degree,
                    knots: function.knots,
                    control_points: function.control_points,
                    weights: function.weights,
                    periodic: function.periodic,
                },
                enum_count,
                points,
                tail,
            }
        }
        _ => return None,
    };
    Some(VariableBlendValue {
        name,
        modern_flag,
        discriminator,
        calibrated,
        payload,
    })
}

#[cfg(test)]
mod variable_blend_value_tests {
    use super::*;
    use cadmpeg_ir::geometry::VariableBlendValuePayload;

    fn text(bytes: &mut Vec<u8>, value: &str) {
        bytes.push(0x07);
        bytes.push(u8::try_from(value.len()).expect("generated text length"));
        bytes.extend_from_slice(value.as_bytes());
    }

    fn integer(bytes: &mut Vec<u8>, tag: u8, value: i64) {
        bytes.push(tag);
        bytes.extend_from_slice(&value.to_le_bytes());
    }

    fn double(bytes: &mut Vec<u8>, value: f64) {
        bytes.push(0x06);
        bytes.extend_from_slice(&value.to_le_bytes());
    }

    fn two_ends(bytes: &mut Vec<u8>) {
        text(bytes, "two_ends");
        bytes.push(0x0a);
        integer(bytes, 0x04, 7);
        integer(bytes, 0x15, 3);
        for value in [0.25, 0.75, 1.5, 2.5] {
            double(bytes, value);
        }
    }

    #[test]
    fn decodes_generated_two_ends_and_recursive_const_values() {
        let mut direct = Vec::new();
        two_ends(&mut direct);
        let mut position = 0;
        let decoded = decode_variable_blend_value(&direct, &mut position, 8, true, 0)
            .expect("generated two-ends value");
        assert_eq!(position, direct.len());
        assert!(decoded.modern_flag);
        assert_eq!(decoded.discriminator, 7);
        let VariableBlendValuePayload::TwoEnds { parameters, radii } = decoded.payload else {
            panic!("expected two-ends payload")
        };
        assert_eq!(parameters, [0.25, 0.75]);
        assert_eq!(radii, [15.0, 25.0]);

        let mut recursive = Vec::new();
        text(&mut recursive, "const");
        recursive.push(0x0b);
        integer(&mut recursive, 0x15, 4);
        for value in [0.1, 0.9, 3.0] {
            double(&mut recursive, value);
        }
        integer(&mut recursive, 0x15, 3);
        integer(&mut recursive, 0x15, 2);
        two_ends(&mut recursive);
        let mut position = 0;
        let decoded = decode_variable_blend_value(&recursive, &mut position, 8, true, 0)
            .expect("generated recursive const value");
        assert_eq!(position, recursive.len());
        let VariableBlendValuePayload::Constant { radius, nested, .. } = decoded.payload else {
            panic!("expected constant payload")
        };
        assert_eq!(radius, 30.0);
        assert!(matches!(
            nested.payload,
            VariableBlendValuePayload::TwoEnds { .. }
        ));
    }
}

fn decode_var_blend_spl_sur(
    record_bytes: &[u8],
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    use cadmpeg_ir::geometry::{
        LoftBridgeToken, VariableBlendChamfer, VariableBlendSingleRadiusTail,
    };
    let names: [&[u8]; 2] = [b"var_blend_spl_sur", b"srf_srf_v_bl_spl_sur"];
    let (start, name_len) = names.into_iter().find_map(|name| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name.len()))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name_len + 3;
    let sides = Box::new([
        decode_variable_blend_side(span, &mut position, int_width)?,
        decode_variable_blend_side(span, &mut position, int_width)?,
    ]);
    let primary = decode_curve_block(span, position, int_width)?;
    position = primary.end;
    let offsets = [
        take_f64(span, &mut position)? * LEN_TO_MM,
        take_f64(span, &mut position)? * LEN_TO_MM,
    ];
    let radius_kind = take_tagged_int(span, &mut position, 0x15, int_width)?;
    if !matches!(radius_kind, 0 | 1) {
        return None;
    }
    let first_value = decode_variable_blend_value(span, &mut position, int_width, true, 0)?;
    let second_value = if radius_kind == 1 {
        Some(decode_variable_blend_value(
            span,
            &mut position,
            int_width,
            true,
            0,
        )?)
    } else {
        None
    };
    let chamfer = if radius_kind == 1
        && span.get(position) == Some(&0x15)
        && read_int(span, position + 1, int_width) == Some(3)
    {
        Some(Box::new(VariableBlendChamfer {
            variable_chamfer: take_tagged_int(span, &mut position, 0x15, int_width)?,
            chamfer_type: take_tagged_int(span, &mut position, 0x15, int_width)?,
            value: decode_variable_blend_value(span, &mut position, int_width, true, 0)?,
        }))
    } else {
        None
    };
    let single_radius_tail = if radius_kind == 0
        && span.get(position) == Some(&0x04)
        && matches!(read_int(span, position + 1, int_width), Some(1 | 7))
    {
        Some(VariableBlendSingleRadiusTail {
            selector: LoftBridgeToken::Integer(take_tagged_int(
                span,
                &mut position,
                0x04,
                int_width,
            )?),
            parameters: [
                take_f64(span, &mut position)?,
                take_f64(span, &mut position)?,
            ],
        })
    } else {
        None
    };
    let u_range = [
        take_range_value(span, &mut position)?,
        take_range_value(span, &mut position)?,
    ];
    let v_range = [
        take_range_value(span, &mut position)?,
        take_range_value(span, &mut position)?,
    ];
    let shape_prefix = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let shape_parameter = take_f64(span, &mut position)?;
    let shape_length = take_f64(span, &mut position)? * LEN_TO_MM;
    let shape_tail = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let cache = decode_surface_block(span, position, int_width)?;
    position = cache.end;
    let cache_fit_tolerance = Some(take_f64(span, &mut position)? * LEN_TO_MM);
    let shape_extensions = [
        take_tagged_int(span, &mut position, 0x04, int_width)?,
        take_tagged_int(span, &mut position, 0x04, int_width)?,
        take_tagged_int(span, &mut position, 0x04, int_width)?,
    ];
    let secondary = decode_curve_block(span, position, int_width)?;
    position = secondary.end;
    let convexity = i64::from(take_bool(span, &mut position)?);
    let render_blend = i64::from(take_bool(span, &mut position)?);
    let post_range = [
        take_range_value(span, &mut position)?,
        take_range_value(span, &mut position)?,
    ];
    let post = decode_curve_block(span, position, int_width)?;
    position = post.end;
    let post_pcurve = decode_nullable_embedded_pcurve(span, &mut position, int_width)?;
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::VariableBlend(Box::new(
            EmbeddedVariableBlend {
                sides,
                primary_curve: primary.curve,
                offsets,
                radius_kind,
                first_value,
                second_value,
                chamfer,
                single_radius_tail,
                u_range,
                v_range,
                shape_prefix,
                shape_parameter,
                shape_length,
                shape_tail,
                shape_extensions,
                secondary_curve: secondary.curve,
                convexity,
                render_blend,
                post_range,
                post_curve: post.curve,
                post_pcurve,
            },
        )),
        cache_fit_tolerance,
    })
}

fn decode_vertex_blend_boundary(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<EmbeddedVertexBlendBoundary> {
    let kind = take_native_string(bytes, position)?;
    let boundary_type = i64::from(take_bool(bytes, position)?);
    let magic = take_native_vec3(bytes, position, 0x13)?;
    let u_smoothing = i64::from(take_bool(bytes, position)?);
    let v_smoothing = i64::from(take_bool(bytes, position)?);
    let fullness = take_f64(bytes, position)?;
    let geometry = match kind.as_str() {
        "circle" => {
            let curve = decode_curve_block(bytes, *position, int_width)?;
            *position = curve.end;
            let form = take_tagged_int(bytes, position, 0x15, int_width)?;
            let twist_count = match form {
                0 => 0,
                1 => 1,
                3 => 2,
                _ => return None,
            };
            let mut twists = Vec::with_capacity(twist_count);
            for _ in 0..twist_count {
                let twist = take_native_vec3(bytes, position, 0x13)?;
                twists.push(Point3::new(
                    twist[0] * LEN_TO_MM,
                    twist[1] * LEN_TO_MM,
                    twist[2] * LEN_TO_MM,
                ));
            }
            let parameters = [take_f64(bytes, position)?, take_f64(bytes, position)?];
            let sense = i64::from(take_bool(bytes, position)?);
            EmbeddedVertexBlendBoundaryGeometry::Circle {
                curve: curve.curve,
                form,
                twists,
                parameters,
                sense,
            }
        }
        "deg" => {
            let location = take_native_vec3(bytes, position, 0x13)?;
            let first = take_native_vec3(bytes, position, 0x14)?;
            let second = take_native_vec3(bytes, position, 0x14)?;
            EmbeddedVertexBlendBoundaryGeometry::Degenerate {
                location: Point3::new(
                    location[0] * LEN_TO_MM,
                    location[1] * LEN_TO_MM,
                    location[2] * LEN_TO_MM,
                ),
                normals: [
                    Vector3::new(first[0], first[1], first[2]),
                    Vector3::new(second[0], second[1], second[2]),
                ],
            }
        }
        "pcurve" => {
            let surface = decode_embedded_surface(bytes, position, int_width)?;
            let pcurve = decode_nullable_embedded_pcurve(bytes, position, int_width)?;
            let sense = i64::from(take_bool(bytes, position)?);
            let fit_tolerance = take_f64(bytes, position)?;
            EmbeddedVertexBlendBoundaryGeometry::Pcurve {
                surface,
                pcurve,
                sense,
                fit_tolerance,
            }
        }
        "plane" => {
            let normal = take_native_vec3(bytes, position, 0x14)?;
            let parameters = [take_f64(bytes, position)?, take_f64(bytes, position)?];
            let curve = decode_curve_block(bytes, *position, int_width)?;
            *position = curve.end;
            EmbeddedVertexBlendBoundaryGeometry::Plane {
                normal: Vector3::new(normal[0], normal[1], normal[2]),
                parameters,
                curve: curve.curve,
            }
        }
        _ => return None,
    };
    Some(EmbeddedVertexBlendBoundary {
        boundary_type,
        magic: Point3::new(
            magic[0] * LEN_TO_MM,
            magic[1] * LEN_TO_MM,
            magic[2] * LEN_TO_MM,
        ),
        u_smoothing,
        v_smoothing,
        fullness,
        geometry,
    })
}

fn decode_vertex_blend_spl_sur(
    record_bytes: &[u8],
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 2] = [b"VBL_SURF", b"vertexblendsur"];
    let (start, name_len) = names.into_iter().find_map(|name| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name.len()))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name_len + 3;
    let count = usize::try_from(take_tagged_int(span, &mut position, 0x04, int_width)?).ok()?;
    if count > 100_000 {
        return None;
    }
    let mut boundaries = Vec::with_capacity(count);
    for _ in 0..count {
        boundaries.push(decode_vertex_blend_boundary(
            span,
            &mut position,
            int_width,
        )?);
    }
    let grid_size = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let fit_tolerance = take_f64(span, &mut position)? * LEN_TO_MM;
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::VertexBlend(Box::new(
            EmbeddedVertexBlend {
                boundaries,
                grid_size,
                fit_tolerance,
            },
        )),
        cache_fit_tolerance: None,
    })
}

fn decode_full_rb_blend_spl_sur(
    record_bytes: &[u8],
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    let names: [(&[u8], bool); 6] = [
        (b"rb_blend_spl_sur", false),
        (b"rbblnsur", false),
        (b"pipe_spl_sur", false),
        (b"pipesur", false),
        (b"sss_blend_spl_sur", true),
        (b"sssblndsur", true),
    ];
    let (start, name_len, has_third) = names.into_iter().find_map(|(name, has_third)| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name.len(), has_third))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let mut position = name_len + 3;
    let sides = Box::new([
        decode_rolling_ball_side(span, &mut position, int_width)?,
        decode_rolling_ball_side(span, &mut position, int_width)?,
    ]);
    let slice = decode_curve_block(span, position, int_width)?;
    position = slice.end;
    let offsets = [
        take_f64(span, &mut position)? * LEN_TO_MM,
        take_f64(span, &mut position)? * LEN_TO_MM,
    ];
    let radius_selector = match span.get(position)? {
        0x15 => {
            if take_tagged_int(span, &mut position, 0x15, int_width)? != -1 {
                return None;
            }
            EmbeddedRollingBallRadiusSelector::None
        }
        0x06 => EmbeddedRollingBallRadiusSelector::Value(take_f64(span, &mut position)?),
        _ => return None,
    };
    let u_range = [
        take_f64(span, &mut position)?,
        take_f64(span, &mut position)?,
    ];
    let v_range = [
        take_f64(span, &mut position)?,
        take_f64(span, &mut position)?,
    ];
    let parameters = [
        take_f64(span, &mut position)?,
        take_f64(span, &mut position)?,
        take_f64(span, &mut position)?,
    ];
    let tail = take_tagged_int(span, &mut position, 0x04, int_width)?;
    let cache = decode_surface_block(span, position, int_width)?;
    position = cache.end;
    let cache_fit_tolerance = Some(take_f64(span, &mut position)? * LEN_TO_MM);
    let discontinuities = [
        take_float_array(span, &mut position, int_width)?,
        take_float_array(span, &mut position, int_width)?,
        take_float_array(span, &mut position, int_width)?,
    ];
    let third = if has_third {
        Some(Box::new(decode_rolling_ball_third_side(
            span,
            &mut position,
            int_width,
        )?))
    } else {
        None
    };
    let radius = if offsets[0] == offsets[1] {
        BlendRadiusLaw::Constant {
            signed_radius: offsets[0],
        }
    } else {
        BlendRadiusLaw::Linear {
            start: offsets[0],
            end: offsets[1],
        }
    };
    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Blend {
            supports: Box::new([None, None]),
            spine: Some(slice.curve.clone()),
            radius,
            cross_section: BlendCrossSection::Circular,
            native: Some(Box::new(EmbeddedRollingBall {
                sides,
                slice: slice.curve,
                offsets,
                radius_selector,
                u_range,
                v_range,
                parameters,
                tail,
                discontinuities,
                third,
            })),
        },
        cache_fit_tolerance,
    })
}

fn decode_rb_blend_spl_sur_fallback(
    record_bytes: &[u8],
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    let names: [&[u8]; 4] = [
        b"rb_blend_spl_sur",
        b"rbblnsur",
        b"pipe_spl_sur",
        b"pipesur",
    ];
    let (start, header_len) = names.into_iter().find_map(|name| {
        record_bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|start| (start, name.len() + 3))
    })?;
    let span = subtype_span(record_bytes, start, int_width)?;
    let cache = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .next_back()?;

    let mut support_count = 0usize;
    let mut radius_boundary = None;
    let mut pos = header_len;
    while pos < cache.end {
        match span[pos] {
            0x0d | 0x0e => {
                let len = usize::from(*span.get(pos + 1)?);
                let name = span.get(pos + 2..pos + 2 + len)?;
                if [b"plane".as_slice(), b"sphere", b"cone", b"torus"].contains(&name) {
                    support_count += 1;
                }
            }
            0x15 if read_int(span, pos + 1, int_width) == Some(-1) => radius_boundary = Some(pos),
            _ => {}
        }
        pos = next_token(span, pos, int_width)?;
    }
    let boundary = radius_boundary?;
    let mut radius_values = Vec::new();
    let mut pos = header_len;
    while pos < boundary {
        if span[pos] == 0x06 {
            radius_values.push(read_f64(span, pos + 1)?);
        }
        pos = next_token(span, pos, int_width)?;
    }
    let end = *radius_values.last()? * LEN_TO_MM;
    let start = *radius_values.get(radius_values.len().checked_sub(2)?)? * LEN_TO_MM;
    let radius = if start == end {
        BlendRadiusLaw::Constant {
            signed_radius: start,
        }
    } else {
        BlendRadiusLaw::Linear { start, end }
    };
    let center_curve = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_curve_block(span, at, int_width))
        .map(|decoded| decoded.curve)
        .next_back();
    let mut support_caches = marker_positions(span)
        .into_iter()
        .filter_map(|at| decode_surface_block(span, at, int_width))
        .filter(|decoded| decoded.end < cache.end)
        .map(|decoded| decoded.surface);
    let supports = [
        (support_count > 0).then(|| support_caches.next()).flatten(),
        (support_count > 1).then(|| support_caches.next()).flatten(),
    ];
    let cache_fit_tolerance = (span.get(cache.end) == Some(&0x06))
        .then(|| read_f64(span, cache.end + 1).map(|v| v * LEN_TO_MM))
        .flatten();

    Some(DecodedProceduralSurface {
        definition: DecodedProceduralSurfaceDefinition::Blend {
            supports: Box::new(supports),
            spine: center_curve,
            radius,
            cross_section: BlendCrossSection::Circular,
            native: None,
        },
        cache_fit_tolerance,
    })
}

/// Decode a native procedural definition, following nested subtype-table references.
pub fn decode_procedural_surface_resolving_refs(
    record_bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
) -> Option<DecodedProceduralSurface> {
    INT_WIDTHS.into_iter().find_map(|int_width| {
        decode_procedural_resolving_refs(
            record_bytes,
            active_bytes,
            tables,
            &mut Vec::new(),
            int_width,
        )
    })
}

fn decode_procedural_resolving_refs(
    bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
    seen: &mut Vec<usize>,
    int_width: usize,
) -> Option<DecodedProceduralSurface> {
    if let Some(decoded) = decode_exact_spl_sur(bytes, int_width)
        .or_else(|| decode_comp_spl_sur(bytes, int_width))
        .or_else(|| decode_taper_spl_sur(bytes, int_width))
        .or_else(|| decode_loft_spl_sur(bytes, int_width))
        .or_else(|| decode_compound_loft_spl_sur(bytes, int_width))
        .or_else(|| decode_g2_blend_spl_sur(bytes, int_width))
        .or_else(|| decode_ruled_spl_sur(bytes, int_width))
        .or_else(|| decode_sum_spl_sur(bytes, int_width))
        .or_else(|| decode_rot_spl_sur(bytes, int_width))
        .or_else(|| decode_off_spl_sur(bytes, int_width))
        .or_else(|| decode_cyl_spl_sur_at(bytes, int_width))
        .or_else(|| decode_var_blend_spl_sur(bytes, int_width))
        .or_else(|| decode_vertex_blend_spl_sur(bytes, int_width))
        .or_else(|| decode_full_rb_blend_spl_sur(bytes, int_width))
        .or_else(|| decode_rb_blend_spl_sur_fallback(bytes, int_width))
    {
        return Some(decoded);
    }
    let table = tables.for_width(int_width);
    for index in subtype_refs(bytes, int_width) {
        if seen.contains(&index) {
            continue;
        }
        let target = *table.get(index)?;
        seen.push(index);
        if let Some(decoded) = decode_procedural_resolving_refs(
            subtype_span(active_bytes, target, int_width)?,
            active_bytes,
            tables,
            seen,
            int_width,
        ) {
            return Some(decoded);
        }
    }
    None
}

/// Decode a surface cache from a carrier record, following the ASM subtype
/// table when the record stores a nested `ref N` instead of an inline cache.
/// `active_bytes` is the full active SAB slice; `N` indexes its non-`ref`
/// subtype openings in byte order.
pub fn decode_surface_cache_resolving_refs(
    record_bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
) -> Option<NurbsSurface> {
    INT_WIDTHS.into_iter().find_map(|int_width| {
        decode_cache_resolving_refs(
            record_bytes,
            active_bytes,
            tables,
            &mut Vec::new(),
            decode_surface_cache_at,
            int_width,
        )
    })
}

/// Decode the 3D curve cache of a procedural curve record: the FIRST valid curve
/// block (surface and 2D pcurve blocks in the record are skipped because they do
/// not parse as a 3D curve block). Returns `None` when none is present.
pub fn decode_curve_cache(record_bytes: &[u8]) -> Option<NurbsCurve> {
    INT_WIDTHS
        .into_iter()
        .find_map(|int_width| decode_curve_cache_at(record_bytes, int_width))
}

fn decode_curve_cache_at(record_bytes: &[u8], int_width: usize) -> Option<NurbsCurve> {
    marker_positions(record_bytes).into_iter().find_map(|pos| {
        decode_curve_block(record_bytes, pos, int_width).map(|decoded| decoded.curve)
    })
}

/// Decode a curve cache from a carrier record, resolving nested ASM subtype
/// references through the active slice's subtype table.
pub fn decode_curve_cache_resolving_refs(
    record_bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
) -> Option<NurbsCurve> {
    INT_WIDTHS.into_iter().find_map(|int_width| {
        decode_cache_resolving_refs(
            record_bytes,
            active_bytes,
            tables,
            &mut Vec::new(),
            decode_curve_cache_at,
            int_width,
        )
    })
}

/// Source curve and tail fields decoded from an `offset_int_cur` construction.
pub(crate) type VectorOffsetDefinition = (NurbsCurve, [f64; 2], Vector3, [String; 2], [i64; 2]);

/// Parent curve and retained range decoded from a `subset_int_cur` construction.
pub(crate) type SubsetDefinition = (NurbsCurve, [f64; 2]);

/// Parameter arrays and child curves decoded from a `comp_int_cur` construction.
pub(crate) type CompoundDefinition = (Vec<f64>, Vec<f64>, Vec<NurbsCurve>);

/// Embedded freeform support carriers and tail fields of an `off_int_cur`.
pub(crate) struct EmbeddedTwoSidedOffset {
    /// Two ordered embedded support surfaces.
    pub(crate) surfaces: [SurfaceGeometry; 2],
    /// Two ordered embedded NURBS parameter curves.
    pub(crate) pcurves: [NurbsPcurve; 2],
    /// Shared native parameter interval.
    pub(crate) parameter_range: [f64; 2],
    /// Three discontinuity arrays.
    pub(crate) discontinuities: [Vec<f64>; 3],
    /// Signed side offsets in document length units.
    pub(crate) offsets: [f64; 2],
}

/// Embedded support carriers and shared fields of an `int_int_cur`.
pub(crate) struct EmbeddedIntersection {
    pub(crate) surfaces: [SurfaceGeometry; 2],
    pub(crate) pcurves: [NurbsPcurve; 2],
    pub(crate) parameter_range: [f64; 2],
    pub(crate) discontinuities: [Vec<f64>; 3],
}

/// Three ordered support carriers and selector of an `sss_int_cur`.
pub(crate) struct EmbeddedThreeSurfaceIntersection {
    pub(crate) surfaces: [SurfaceGeometry; 3],
    pub(crate) pcurves: [NurbsPcurve; 3],
    pub(crate) parameter_range: [f64; 2],
    pub(crate) discontinuities: [Vec<f64>; 3],
    pub(crate) selector: i64,
}

/// Embedded support context, source curve, and tail of a `proj_int_cur`.
pub(crate) struct EmbeddedProjection {
    pub(crate) surfaces: [SurfaceGeometry; 2],
    pub(crate) pcurves: [NurbsPcurve; 2],
    pub(crate) parameter_range: [f64; 2],
    pub(crate) discontinuities: [Vec<f64>; 3],
    pub(crate) source: NurbsCurve,
    pub(crate) tail: cadmpeg_ir::geometry::ProjectionTail,
}

/// Shared context and tail fields of a silhouette intcurve.
pub(crate) struct EmbeddedSilhouette {
    pub(crate) context: EmbeddedIntersection,
    pub(crate) silhouette: cadmpeg_ir::geometry::SilhouetteKind,
    pub(crate) cast_surface: SurfaceGeometry,
    pub(crate) light_direction: Vector3,
}

/// Shared context and tail fields of an `off_surf_int_cur`.
pub(crate) struct EmbeddedSurfaceOffset {
    pub(crate) context: EmbeddedIntersection,
    pub(crate) base_u_range: [f64; 2],
    pub(crate) base_v_range: [f64; 2],
    pub(crate) base: NurbsCurve,
    pub(crate) base_range: [f64; 2],
    pub(crate) distance: f64,
    pub(crate) shift: f64,
    pub(crate) scale: f64,
}

/// Spring support context, conditional null-carrier ranges, and direction enum.
pub(crate) struct EmbeddedSpring {
    pub(crate) surfaces: [Option<SurfaceGeometry>; 2],
    pub(crate) pcurves: [Option<NurbsPcurve>; 2],
    pub(crate) surface_parameter_ranges: [Option<[[f64; 2]; 2]>; 2],
    pub(crate) first_pcurve_parameter_range: Option<[f64; 2]>,
    pub(crate) parameter_range: [f64; 2],
    pub(crate) discontinuities: [Vec<f64>; 3],
    pub(crate) direction: i64,
}

pub(crate) enum EmbeddedDeformableData {
    VectorField {
        vectors: [Vector3; 4],
        parameter_pairs: Vec<[f64; 2]>,
    },
    Surface(SurfaceGeometry),
}

pub(crate) struct EmbeddedDeformable {
    pub(crate) extension: i64,
    pub(crate) bend: NurbsCurve,
    pub(crate) data: EmbeddedDeformableData,
}

/// A procedural curve cache together with its native subtype and fit contract.
pub struct DecodedProceduralCurve {
    /// The cached B-spline curve (control points scaled centimetre→
    /// millimetre; knots and weights unscaled).
    pub curve: NurbsCurve,
    /// The `intcurve` subtype record name (`exact_int_cur`, `off_int_cur`,
    /// `proj_int_cur`, `int_int_cur`, `helix_int_cur`, `sss_int_cur`, ...).
    pub native_kind: String,
    /// Neutral construction fields decoded from the subtype tail.
    pub definition: Option<cadmpeg_ir::geometry::ProceduralCurveDefinition>,
    /// Source curve and tail fields of an `offset_int_cur` construction.
    pub vector_offset: Option<VectorOffsetDefinition>,
    /// Parent curve and retained range of a `subset_int_cur` construction.
    pub subset: Option<SubsetDefinition>,
    /// Parameter arrays and ordered child curves of a `comp_int_cur` construction.
    pub compound: Option<CompoundDefinition>,
    /// Non-null embedded NURBS support carriers of an `off_int_cur`.
    pub(crate) embedded_two_sided_offset: Option<EmbeddedTwoSidedOffset>,
    /// Embedded support context of an `int_int_cur`.
    pub(crate) embedded_intersection: Option<EmbeddedIntersection>,
    /// Three embedded support pairs of an `sss_int_cur`.
    pub(crate) embedded_three_surface_intersection: Option<EmbeddedThreeSurfaceIntersection>,
    /// Prefix-only surface-curve family and support context.
    pub(crate) embedded_surface_curve: Option<(
        cadmpeg_ir::geometry::SurfaceCurveFamily,
        EmbeddedIntersection,
    )>,
    /// Embedded silhouette support, cast surface, and light vector.
    pub(crate) embedded_silhouette: Option<EmbeddedSilhouette>,
    /// Embedded support context and base curve of an `off_surf_int_cur`.
    pub(crate) embedded_surface_offset: Option<EmbeddedSurfaceOffset>,
    /// Modern non-null `spring_int_cur` construction.
    pub(crate) embedded_spring: Option<EmbeddedSpring>,
    /// Embedded bend curve and discriminator payload of a `defm_int_cur`.
    pub(crate) embedded_deformable: Option<EmbeddedDeformable>,
    /// Embedded support context and source of a `proj_int_cur`.
    pub(crate) embedded_projection: Option<EmbeddedProjection>,
    /// `surface_fit_tolerance` of the cached B-spline block, if present
    /// ([spec §7.5](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/f3d.md#75-nubsnurbs-blocks-b-spline-curves-and-surfaces)).
    pub cache_fit_tolerance: Option<f64>,
}

/// Decode a procedural 3D curve cache while following subtype-table references.
pub fn decode_procedural_curve_resolving_refs(
    record_bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
) -> Option<DecodedProceduralCurve> {
    INT_WIDTHS.into_iter().find_map(|int_width| {
        decode_procedural_curve_recursive(
            record_bytes,
            active_bytes,
            tables,
            &mut Vec::new(),
            int_width,
        )
    })
}

fn decode_procedural_curve_recursive(
    bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
    seen: &mut Vec<usize>,
    int_width: usize,
) -> Option<DecodedProceduralCurve> {
    let vector_offset = decode_vector_offset_definition(bytes, int_width);
    let subset = decode_subset_definition(bytes, int_width);
    let compound = decode_compound_definition(bytes, int_width);
    // Wrapper constructions serialize their source curves before the record's
    // own cache, so the cache is the last decodable curve block. Every other
    // intcurve opens with its cache — the first block, followed by the fit
    // tolerance; later blocks belong to nested construction machinery
    // (support surfaces, blend spines, progenitors) and are not the carrier.
    let positions = marker_positions(bytes);
    let solved = if vector_offset.is_some() || subset.is_some() || compound.is_some() {
        positions
            .into_iter()
            .rev()
            .find_map(|position| decode_curve_block(bytes, position, int_width))
    } else {
        positions
            .into_iter()
            .find_map(|position| decode_curve_block(bytes, position, int_width))
    };
    if let Some(decoded) = solved {
        let cache_fit_tolerance = (bytes.get(decoded.end) == Some(&0x06))
            .then(|| read_f64(bytes, decoded.end + 1).map(|value| value * LEN_TO_MM))
            .flatten();
        let native_kind =
            first_construction_subtype(bytes).unwrap_or_else(|| "intcurve".to_string());
        let definition = if native_kind == "exact_int_cur" {
            Some(cadmpeg_ir::geometry::ProceduralCurveDefinition::Exact)
        } else {
            decode_helix_definition(bytes).or_else(|| decode_two_sided_offset(bytes, int_width))
        };
        return Some(DecodedProceduralCurve {
            curve: decoded.curve,
            native_kind,
            definition,
            vector_offset,
            subset,
            compound,
            embedded_two_sided_offset: decode_embedded_two_sided_offset(bytes, int_width),
            embedded_intersection: decode_embedded_intersection(bytes, int_width),
            embedded_three_surface_intersection: decode_embedded_three_surface_intersection(
                bytes, int_width,
            ),
            embedded_surface_curve: decode_embedded_surface_curve(bytes, int_width),
            embedded_silhouette: decode_embedded_silhouette(bytes, int_width),
            embedded_surface_offset: decode_embedded_surface_offset(bytes, int_width),
            embedded_spring: decode_embedded_spring(bytes, int_width),
            embedded_deformable: decode_embedded_deformable(bytes, int_width),
            embedded_projection: decode_embedded_projection(bytes, int_width),
            cache_fit_tolerance,
        });
    }
    let table = tables.for_width(int_width);
    for index in subtype_refs(bytes, int_width) {
        if seen.contains(&index) {
            continue;
        }
        let target = *table.get(index)?;
        seen.push(index);
        if let Some(decoded) = decode_procedural_curve_recursive(
            subtype_span(active_bytes, target, int_width)?,
            active_bytes,
            tables,
            seen,
            int_width,
        ) {
            return Some(decoded);
        }
    }
    None
}

fn decode_embedded_deformable(bytes: &[u8], int_width: usize) -> Option<EmbeddedDeformable> {
    let name = b"defm_int_cur";
    let marker = bytes.windows(name.len() + 3).position(|window| {
        window[0] == 0x0f
            && matches!(window[1], 0x0d | 0x0e)
            && usize::from(window[2]) == name.len()
            && &window[3..] == name
    })?;
    let mut position = marker + name.len() + 3;
    let extension = take_tagged_int(bytes, &mut position, 0x04, int_width)?;
    let bend = decode_curve_block(bytes, position, int_width)?;
    position = bend.end;
    let mode = take_tagged_int(bytes, &mut position, 0x04, int_width)?;
    let data = match mode {
        8 => {
            let mut vectors = [Vector3::new(0.0, 0.0, 0.0); 4];
            for vector in &mut vectors {
                let value = take_native_vec3(bytes, &mut position, 0x14)?;
                *vector = Vector3::new(value[0], value[1], value[2]);
            }
            let count = take_tagged_int(bytes, &mut position, 0x04, int_width)?;
            let count = usize::try_from(count).ok()?;
            let mut parameter_pairs = Vec::with_capacity(count);
            for _ in 0..count {
                parameter_pairs.push([
                    take_f64(bytes, &mut position)?,
                    take_f64(bytes, &mut position)?,
                ]);
            }
            EmbeddedDeformableData::VectorField {
                vectors,
                parameter_pairs,
            }
        }
        5 => EmbeddedDeformableData::Surface(decode_embedded_surface(
            bytes,
            &mut position,
            int_width,
        )?),
        _ => return None,
    };
    Some(EmbeddedDeformable {
        extension,
        bend: bend.curve,
        data,
    })
}

fn decode_embedded_spring(bytes: &[u8], int_width: usize) -> Option<EmbeddedSpring> {
    let name = b"spring_int_cur";
    let (marker, name_len) = find_intcurve_subtype(bytes, name)?;
    let mut position = marker + name_len + 3;
    let mut surfaces = [None, None];
    let mut surface_parameter_ranges = [None, None];
    for side in 0..2 {
        let saved = position;
        if take_native_ident(bytes, &mut position).as_deref() == Some("null_surface") {
            surface_parameter_ranges[side] = Some([
                [
                    take_range_value(bytes, &mut position)?,
                    take_range_value(bytes, &mut position)?,
                ],
                [
                    take_range_value(bytes, &mut position)?,
                    take_range_value(bytes, &mut position)?,
                ],
            ]);
        } else {
            position = saved;
            surfaces[side] = Some(decode_embedded_surface(bytes, &mut position, int_width)?);
        }
    }
    let first_pcurve;
    let first_pcurve_parameter_range;
    let saved = position;
    if take_native_ident(bytes, &mut position).as_deref() == Some("nullbs") {
        first_pcurve = None;
        first_pcurve_parameter_range = Some([
            take_range_value(bytes, &mut position)?,
            take_range_value(bytes, &mut position)?,
        ]);
    } else {
        position = saved;
        let (pcurve, end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
        position = end;
        first_pcurve = Some(pcurve);
        first_pcurve_parameter_range = None;
    }
    let saved = position;
    let second_pcurve = if take_native_ident(bytes, &mut position).as_deref() == Some("nullbs") {
        None
    } else {
        position = saved;
        let (pcurve, end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
        position = end;
        Some(pcurve)
    };
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    take_bool(bytes, &mut position)?;
    let direction = take_tagged_int(bytes, &mut position, 0x15, int_width)?;
    Some(EmbeddedSpring {
        surfaces,
        pcurves: [first_pcurve, second_pcurve],
        surface_parameter_ranges,
        first_pcurve_parameter_range,
        parameter_range,
        discontinuities,
        direction,
    })
}

fn decode_embedded_surface_offset(bytes: &[u8], int_width: usize) -> Option<EmbeddedSurfaceOffset> {
    let name = b"off_surf_int_cur";
    let (marker, name_len) = find_intcurve_subtype(bytes, name)?;
    let mut position = marker + name_len + 3;
    let surfaces = [
        decode_embedded_surface(bytes, &mut position, int_width)?,
        decode_embedded_surface(bytes, &mut position, int_width)?,
    ];
    let (first_pcurve, first_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = first_end;
    let (second_pcurve, second_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = second_end;
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    take_bool(bytes, &mut position)?;
    let base_u_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let base_v_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let base = decode_curve_block(bytes, position, int_width)?;
    position = base.end;
    let base_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    Some(EmbeddedSurfaceOffset {
        context: EmbeddedIntersection {
            surfaces,
            pcurves: [first_pcurve, second_pcurve],
            parameter_range,
            discontinuities,
        },
        base_u_range,
        base_v_range,
        base: base.curve,
        base_range,
        distance: take_f64(bytes, &mut position)? * LEN_TO_MM,
        shift: take_f64(bytes, &mut position)?,
        scale: take_f64(bytes, &mut position)?,
    })
}

fn decode_embedded_silhouette(bytes: &[u8], int_width: usize) -> Option<EmbeddedSilhouette> {
    use cadmpeg_ir::geometry::SilhouetteKind;
    let names = [
        (b"silh_int_cur".as_slice(), SilhouetteKind::Standard),
        (b"para_silh_int_cur".as_slice(), SilhouetteKind::Parametric),
        (b"parasil".as_slice(), SilhouetteKind::Parametric),
        (
            b"taper_silh_int_cur".as_slice(),
            SilhouetteKind::Taper { draft_factor: 0.0 },
        ),
    ];
    let (marker, name, mut silhouette) = names.into_iter().find_map(|(name, silhouette)| {
        bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|marker| (marker, name, silhouette))
    })?;
    let mut position = marker + name.len() + 3;
    let surfaces = [
        decode_embedded_surface(bytes, &mut position, int_width)?,
        decode_embedded_surface(bytes, &mut position, int_width)?,
    ];
    let (first_pcurve, first_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = first_end;
    let (second_pcurve, second_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = second_end;
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    let cast_surface = decode_embedded_surface(bytes, &mut position, int_width)?;
    let light = take_native_vec3(bytes, &mut position, 0x14)?;
    let light_direction = normalized(light)?;
    if matches!(silhouette, SilhouetteKind::Taper { .. }) {
        silhouette = SilhouetteKind::Taper {
            draft_factor: take_f64(bytes, &mut position)?,
        };
    }
    Some(EmbeddedSilhouette {
        context: EmbeddedIntersection {
            surfaces,
            pcurves: [first_pcurve, second_pcurve],
            parameter_range,
            discontinuities,
        },
        silhouette,
        cast_surface,
        light_direction,
    })
}

fn decode_embedded_surface_curve(
    bytes: &[u8],
    int_width: usize,
) -> Option<(
    cadmpeg_ir::geometry::SurfaceCurveFamily,
    EmbeddedIntersection,
)> {
    use cadmpeg_ir::geometry::SurfaceCurveFamily;
    let names = [
        (b"blend_int_cur".as_slice(), SurfaceCurveFamily::Blend),
        (b"bldcur".as_slice(), SurfaceCurveFamily::Blend),
        (
            b"surf_int_cur".as_slice(),
            SurfaceCurveFamily::SurfaceConstrained,
        ),
        (
            b"surfcur".as_slice(),
            SurfaceCurveFamily::SurfaceConstrained,
        ),
        (b"par_int_cur".as_slice(), SurfaceCurveFamily::Parametric),
        (b"parcur".as_slice(), SurfaceCurveFamily::Parametric),
        (b"skin_int_cur".as_slice(), SurfaceCurveFamily::Skin),
        (b"d5c2_cur".as_slice(), SurfaceCurveFamily::Skin),
    ];
    let (marker, name, family) = names.into_iter().find_map(|(name, family)| {
        bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|marker| (marker, name, family))
    })?;
    let mut position = marker + name.len() + 3;
    let surfaces = [
        decode_embedded_surface(bytes, &mut position, int_width)?,
        decode_embedded_surface(bytes, &mut position, int_width)?,
    ];
    let (first_pcurve, first_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = first_end;
    let (second_pcurve, second_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = second_end;
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    Some((
        family,
        EmbeddedIntersection {
            surfaces,
            pcurves: [first_pcurve, second_pcurve],
            parameter_range,
            discontinuities,
        },
    ))
}

fn decode_embedded_three_surface_intersection(
    bytes: &[u8],
    int_width: usize,
) -> Option<EmbeddedThreeSurfaceIntersection> {
    let name = b"sss_int_cur";
    let marker = bytes.windows(name.len() + 3).position(|window| {
        window[0] == 0x0f
            && matches!(window[1], 0x0d | 0x0e)
            && usize::from(window[2]) == name.len()
            && &window[3..] == name
    })?;
    let mut position = marker + name.len() + 3;
    let first = decode_embedded_surface(bytes, &mut position, int_width)?;
    let second = decode_embedded_surface(bytes, &mut position, int_width)?;
    let (first_pcurve, first_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = first_end;
    let (second_pcurve, second_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = second_end;
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    let selector = take_tagged_int(bytes, &mut position, 0x04, int_width)?;
    let third = decode_embedded_surface(bytes, &mut position, int_width)?;
    let (third_pcurve, _) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    Some(EmbeddedThreeSurfaceIntersection {
        surfaces: [first, second, third],
        pcurves: [first_pcurve, second_pcurve, third_pcurve],
        parameter_range,
        discontinuities,
        selector,
    })
}

fn decode_embedded_projection(bytes: &[u8], int_width: usize) -> Option<EmbeddedProjection> {
    let name = b"proj_int_cur";
    let (marker, name_len) = find_intcurve_subtype(bytes, name)?;
    let mut position = marker + name_len + 3;
    let surfaces = [
        decode_embedded_surface(bytes, &mut position, int_width)?,
        decode_embedded_surface(bytes, &mut position, int_width)?,
    ];
    let (first_pcurve, first_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = first_end;
    let (second_pcurve, second_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = second_end;
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    take_bool(bytes, &mut position)?;
    let source = decode_curve_block(bytes, position, int_width)?;
    position = source.end;
    let flag = take_bool(bytes, &mut position)?;
    let tail = if bytes.get(position) == Some(&0x10) {
        cadmpeg_ir::geometry::ProjectionTail::EarlyClose { flag }
    } else {
        cadmpeg_ir::geometry::ProjectionTail::Ranged {
            flag,
            parameter_range: [
                take_range_value(bytes, &mut position)?,
                take_range_value(bytes, &mut position)?,
            ],
            role: take_native_string(bytes, &mut position)?,
        }
    };
    Some(EmbeddedProjection {
        surfaces,
        pcurves: [first_pcurve, second_pcurve],
        parameter_range,
        discontinuities,
        source: source.curve,
        tail,
    })
}

fn decode_embedded_intersection(bytes: &[u8], int_width: usize) -> Option<EmbeddedIntersection> {
    let names: [&[u8]; 3] = [b"int_int_cur", b"surf_surf_int_cur", b"surfintcur"];
    let (marker, name) = names.into_iter().find_map(|name| {
        bytes
            .windows(name.len() + 3)
            .position(|window| {
                window[0] == 0x0f
                    && matches!(window[1], 0x0d | 0x0e)
                    && usize::from(window[2]) == name.len()
                    && &window[3..] == name
            })
            .map(|marker| (marker, name))
    })?;
    let mut position = marker + name.len() + 3;
    let surfaces = [
        decode_embedded_surface(bytes, &mut position, int_width)?,
        decode_embedded_surface(bytes, &mut position, int_width)?,
    ];
    let (first_pcurve, first_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = first_end;
    let (second_pcurve, second_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = second_end;
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    take_bool(bytes, &mut position)?;
    Some(EmbeddedIntersection {
        surfaces,
        pcurves: [first_pcurve, second_pcurve],
        parameter_range,
        discontinuities,
    })
}

fn decode_embedded_two_sided_offset(
    bytes: &[u8],
    int_width: usize,
) -> Option<EmbeddedTwoSidedOffset> {
    let name = b"off_int_cur";
    let (marker, name_len) = find_intcurve_subtype(bytes, name)?;
    let mut position = marker + name_len + 3;
    let first_surface = decode_embedded_surface(bytes, &mut position, int_width)?;
    let second_surface = decode_embedded_surface(bytes, &mut position, int_width)?;
    let surfaces = [first_surface, second_surface];
    let (first_pcurve, first_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = first_end;
    let (second_pcurve, second_end) = decode_pcurve_block_with_end(bytes, position, int_width)?;
    position = second_end;
    let pcurves = [first_pcurve, second_pcurve];
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    if !matches!(bytes.get(position), Some(0x0a | 0x0b)) {
        return None;
    }
    position += 1;
    let offsets = [
        take_range_value(bytes, &mut position)? * LEN_TO_MM,
        take_range_value(bytes, &mut position)? * LEN_TO_MM,
    ];
    Some(EmbeddedTwoSidedOffset {
        surfaces,
        pcurves,
        parameter_range,
        discontinuities,
        offsets,
    })
}

fn decode_embedded_surface(
    bytes: &[u8],
    position: &mut usize,
    int_width: usize,
) -> Option<SurfaceGeometry> {
    let kind = take_native_ident(bytes, position)?;
    if kind == "spline" {
        let decoded = decode_surface_block(bytes, *position, int_width)?;
        *position = decoded.end;
        return Some(SurfaceGeometry::Nurbs(decoded.surface));
    }
    let point = take_native_vec3(bytes, position, 0x13)?;
    let point = Point3::new(
        point[0] * LEN_TO_MM,
        point[1] * LEN_TO_MM,
        point[2] * LEN_TO_MM,
    );
    match kind.as_str() {
        "plane" => {
            let normal = normalized(take_native_vec3(bytes, position, 0x14)?)?;
            let u_axis = normalized(take_native_vec3(bytes, position, 0x14)?)?;
            take_bool(bytes, position)?;
            Some(SurfaceGeometry::Plane {
                origin: point,
                normal,
                u_axis,
            })
        }
        "cone" => {
            let axis = normalized(take_native_vec3(bytes, position, 0x14)?)?;
            let major = take_native_vec3(bytes, position, 0x14)?;
            let ref_direction = normalized(major)?;
            take_f64(bytes, position)?;
            take_bool(bytes, position)?;
            take_bool(bytes, position)?;
            let sine = take_f64(bytes, position)?;
            take_f64(bytes, position)?;
            let radius = take_f64(bytes, position)? * LEN_TO_MM;
            for _ in 0..5 {
                take_bool(bytes, position)?;
            }
            if sine.abs() <= f64::EPSILON {
                Some(SurfaceGeometry::Cylinder {
                    origin: point,
                    axis,
                    ref_direction,
                    radius,
                })
            } else {
                Some(SurfaceGeometry::Cone {
                    origin: point,
                    axis,
                    ref_direction,
                    radius,
                    half_angle: sine.abs().asin(),
                })
            }
        }
        "sphere" => {
            let radius = take_f64(bytes, position)? * LEN_TO_MM;
            let ref_direction = normalized(take_native_vec3(bytes, position, 0x14)?)?;
            let axis = normalized(take_native_vec3(bytes, position, 0x14)?)?;
            for _ in 0..5 {
                take_bool(bytes, position)?;
            }
            Some(SurfaceGeometry::Sphere {
                center: point,
                axis,
                ref_direction,
                radius,
            })
        }
        "torus" => {
            let axis = normalized(take_native_vec3(bytes, position, 0x14)?)?;
            let major_radius = take_f64(bytes, position)? * LEN_TO_MM;
            let minor_radius = take_f64(bytes, position)? * LEN_TO_MM;
            let ref_direction = normalized(take_native_vec3(bytes, position, 0x14)?)?;
            for _ in 0..5 {
                take_bool(bytes, position)?;
            }
            Some(SurfaceGeometry::Torus {
                center: point,
                axis,
                ref_direction,
                major_radius,
                minor_radius,
            })
        }
        _ => None,
    }
}

fn take_f64(bytes: &[u8], position: &mut usize) -> Option<f64> {
    if bytes.get(*position) != Some(&0x06) {
        return None;
    }
    let value = read_f64(bytes, *position + 1)?;
    *position += 9;
    Some(value)
}

fn take_bool(bytes: &[u8], position: &mut usize) -> Option<bool> {
    let value = match bytes.get(*position)? {
        0x0a => true,
        0x0b => false,
        _ => return None,
    };
    *position += 1;
    Some(value)
}

fn normalized(value: [f64; 3]) -> Option<Vector3> {
    let length = value
        .iter()
        .map(|component| component * component)
        .sum::<f64>()
        .sqrt();
    (length.is_finite() && length > 0.0)
        .then(|| Vector3::new(value[0] / length, value[1] / length, value[2] / length))
}

fn decode_two_sided_offset(
    bytes: &[u8],
    int_width: usize,
) -> Option<cadmpeg_ir::geometry::ProceduralCurveDefinition> {
    use cadmpeg_ir::geometry::{
        IntcurveSupportContext, IntcurveSupportSide, ProceduralCurveDefinition,
    };

    let name = b"off_int_cur";
    let (marker, name_len) = find_intcurve_subtype(bytes, name)?;
    let mut position = marker + name_len + 3;
    for expected in ["null_surface", "null_surface", "nullbs", "nullbs"] {
        if take_native_ident(bytes, &mut position)?.as_str() != expected {
            return None;
        }
    }
    let parameter_range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
        take_float_array(bytes, &mut position, int_width)?,
    ];
    if !matches!(bytes.get(position), Some(0x0a | 0x0b)) {
        return None;
    }
    position += 1;
    let offsets = [
        take_range_value(bytes, &mut position)? * LEN_TO_MM,
        take_range_value(bytes, &mut position)? * LEN_TO_MM,
    ];
    Some(ProceduralCurveDefinition::TwoSidedOffset {
        context: IntcurveSupportContext {
            sides: [
                IntcurveSupportSide {
                    surface: None,
                    pcurve: None,
                },
                IntcurveSupportSide {
                    surface: None,
                    pcurve: None,
                },
            ],
            parameter_range,
            discontinuities,
        },
        offsets,
    })
}

fn take_native_ident(bytes: &[u8], position: &mut usize) -> Option<String> {
    if !matches!(bytes.get(*position), Some(0x0d | 0x0e)) {
        return None;
    }
    let length = usize::from(*bytes.get(*position + 1)?);
    let start = *position + 2;
    let end = start.checked_add(length)?;
    let value = String::from_utf8(bytes.get(start..end)?.to_vec()).ok()?;
    *position = end;
    Some(value)
}

fn decode_compound_definition(bytes: &[u8], int_width: usize) -> Option<CompoundDefinition> {
    let name = b"comp_int_cur";
    let marker = bytes.windows(name.len() + 3).position(|window| {
        window[0] == 0x0f
            && matches!(window[1], 0x0d | 0x0e)
            && usize::from(window[2]) == name.len()
            && &window[3..] == name
    })?;
    let mut position = marker + name.len() + 3;
    let parameters = take_float_array(bytes, &mut position, int_width)?;
    let count = usize::try_from(take_tagged_int(bytes, &mut position, 0x04, int_width)?).ok()?;
    if count == 0 {
        return None;
    }
    let mut component_parameters = Vec::with_capacity(count);
    for _ in 0..count {
        if bytes.get(position) != Some(&0x06) {
            return None;
        }
        component_parameters.push(read_f64(bytes, position + 1)?);
        position += 9;
    }
    if !matches!(bytes.get(position), Some(0x0a | 0x0b)) {
        return None;
    }
    position += 1;
    let mut components = Vec::with_capacity(count);
    for _ in 0..count {
        let relative = marker_positions(bytes.get(position..)?)
            .into_iter()
            .next()?;
        let decoded = decode_curve_block(bytes, position + relative, int_width)?;
        components.push(decoded.curve);
        position = decoded.end;
    }
    Some((parameters, component_parameters, components))
}

fn take_float_array(bytes: &[u8], position: &mut usize, int_width: usize) -> Option<Vec<f64>> {
    let count = usize::try_from(take_tagged_int(bytes, position, 0x04, int_width)?).ok()?;
    let mut values = Vec::with_capacity(count);
    for _ in 0..count {
        if bytes.get(*position) != Some(&0x06) {
            return None;
        }
        values.push(read_f64(bytes, *position + 1)?);
        *position += 9;
    }
    Some(values)
}

fn decode_subset_definition(bytes: &[u8], int_width: usize) -> Option<SubsetDefinition> {
    let name = b"subset_int_cur";
    let (marker, name_len) = find_intcurve_subtype(bytes, name)?;
    let start = marker + name_len + 3;
    let source_marker = marker_positions(&bytes[start..]).into_iter().next()? + start;
    let source = decode_curve_block(bytes, source_marker, int_width)?;
    let mut position = source.end;
    let range = [
        take_range_value(bytes, &mut position)?,
        take_range_value(bytes, &mut position)?,
    ];
    Some((source.curve, range))
}

fn decode_vector_offset_definition(
    bytes: &[u8],
    int_width: usize,
) -> Option<VectorOffsetDefinition> {
    let name = b"offset_int_cur";
    let (marker, name_len) = find_intcurve_subtype(bytes, name)?;
    let start = marker + name_len + 3;
    let source_marker = marker_positions(&bytes[start..]).into_iter().next()? + start;
    let source = decode_curve_block(bytes, source_marker, int_width)?;
    let mut position = source.end;
    if bytes.get(position) != Some(&0x06) || bytes.get(position + 9) != Some(&0x06) {
        return None;
    }
    let parameter_range = [
        read_f64(bytes, position + 1)?,
        read_f64(bytes, position + 10)?,
    ];
    position += 18;
    let offset = take_native_vec3(bytes, &mut position, 0x14)?;
    let first_label = take_native_string(bytes, &mut position)?;
    let first_code = take_tagged_int(bytes, &mut position, 0x04, int_width)?;
    let second_label = take_native_string(bytes, &mut position)?;
    let second_code = take_tagged_int(bytes, &mut position, 0x04, int_width)?;
    Some((
        source.curve,
        parameter_range,
        Vector3::new(
            offset[0] * LEN_TO_MM,
            offset[1] * LEN_TO_MM,
            offset[2] * LEN_TO_MM,
        ),
        [first_label, second_label],
        [first_code, second_code],
    ))
}

fn take_native_string(bytes: &[u8], position: &mut usize) -> Option<String> {
    let (length, header) = match *bytes.get(*position)? {
        0x07 => (usize::from(*bytes.get(*position + 1)?), 2),
        0x08 => (usize::from(u16_at(bytes, *position + 1)?), 3),
        0x09 => (usize::try_from(u32_at(bytes, *position + 1)?).ok()?, 5),
        _ => return None,
    };
    let start = *position + header;
    let end = start.checked_add(length)?;
    let value = String::from_utf8(bytes.get(start..end)?.to_vec()).ok()?;
    *position = end;
    Some(value)
}

fn decode_helix_definition(
    bytes: &[u8],
) -> Option<cadmpeg_ir::geometry::ProceduralCurveDefinition> {
    let name = b"helix_int_cur";
    let marker = bytes.windows(name.len() + 3).position(|window| {
        window[0] == 0x0f
            && matches!(window[1], 0x0d | 0x0e)
            && usize::from(window[2]) == name.len()
            && &window[3..] == name
    })?;
    let mut position = marker + name.len() + 3;
    let lower = take_range_value(bytes, &mut position)?;
    let upper = take_range_value(bytes, &mut position)?;
    let center = take_native_vec3(bytes, &mut position, 0x13)?;
    let major = take_native_vec3(bytes, &mut position, 0x13)?;
    let minor = take_native_vec3(bytes, &mut position, 0x13)?;
    let pitch = take_native_vec3(bytes, &mut position, 0x13)?;
    if bytes.get(position) != Some(&0x06) {
        return None;
    }
    let apex_factor = read_f64(bytes, position + 1)?;
    position += 9;
    let axis = take_native_vec3(bytes, &mut position, 0x14)?;
    Some(cadmpeg_ir::geometry::ProceduralCurveDefinition::Helix {
        angle_range: [lower, upper],
        center: Point3::new(
            center[0] * LEN_TO_MM,
            center[1] * LEN_TO_MM,
            center[2] * LEN_TO_MM,
        ),
        major: Vector3::new(
            major[0] * LEN_TO_MM,
            major[1] * LEN_TO_MM,
            major[2] * LEN_TO_MM,
        ),
        minor: Vector3::new(
            minor[0] * LEN_TO_MM,
            minor[1] * LEN_TO_MM,
            minor[2] * LEN_TO_MM,
        ),
        pitch: Vector3::new(
            pitch[0] * LEN_TO_MM,
            pitch[1] * LEN_TO_MM,
            pitch[2] * LEN_TO_MM,
        ),
        apex_factor,
        axis: Vector3::new(axis[0], axis[1], axis[2]),
    })
}

fn take_range_value(bytes: &[u8], position: &mut usize) -> Option<f64> {
    if matches!(bytes.get(*position), Some(0x0a | 0x0b)) {
        *position += 1;
    }
    if bytes.get(*position) != Some(&0x06) {
        return None;
    }
    let value = read_f64(bytes, *position + 1)?;
    *position += 9;
    Some(value)
}

fn take_native_vec3(bytes: &[u8], position: &mut usize, tag: u8) -> Option<[f64; 3]> {
    if bytes.get(*position) != Some(&tag) {
        return None;
    }
    let values = [
        read_f64(bytes, *position + 1)?,
        read_f64(bytes, *position + 9)?,
        read_f64(bytes, *position + 17)?,
    ];
    *position += 25;
    Some(values)
}

fn first_construction_subtype(bytes: &[u8]) -> Option<String> {
    for pos in 0..bytes.len().saturating_sub(3) {
        if bytes[pos] != 0x0f || !matches!(bytes.get(pos + 1), Some(0x0d | 0x0e)) {
            continue;
        }
        let len = usize::from(*bytes.get(pos + 2)?);
        let name = bytes.get(pos + 3..pos + 3 + len)?;
        if name != b"ref" {
            return Some(canonical_intcurve_kind(name).into());
        }
    }
    None
}

fn canonical_intcurve_kind(name: &[u8]) -> &str {
    match name {
        b"bldcur" => "blend_int_cur",
        b"blndsprngcur" => "spring_int_cur",
        b"exactcur" => "exact_int_cur",
        b"lawintcur" => "law_int_cur",
        b"offintcur" => "off_int_cur",
        b"offsetintcur" => "offset_int_cur",
        b"offsurfintcur" => "off_surf_int_cur",
        b"parasil" => "para_silh_int_cur",
        b"parcur" => "par_int_cur",
        b"projcur" => "proj_int_cur",
        b"surfcur" => "surf_int_cur",
        b"surfintcur" => "int_int_cur",
        b"d5c2_cur" => "skin_int_cur",
        b"subsetintcur" => "subset_int_cur",
        _ => std::str::from_utf8(name).unwrap_or("intcurve"),
    }
}

fn find_intcurve_subtype(bytes: &[u8], modern: &[u8]) -> Option<(usize, usize)> {
    let legacy: &[u8] = match modern {
        b"blend_int_cur" => b"bldcur",
        b"spring_int_cur" => b"blndsprngcur",
        b"exact_int_cur" => b"exactcur",
        b"law_int_cur" => b"lawintcur",
        b"off_int_cur" => b"offintcur",
        b"offset_int_cur" => b"offsetintcur",
        b"off_surf_int_cur" => b"offsurfintcur",
        b"para_silh_int_cur" => b"parasil",
        b"par_int_cur" => b"parcur",
        b"proj_int_cur" => b"projcur",
        b"surf_int_cur" => b"surfcur",
        b"int_int_cur" => b"surfintcur",
        b"skin_int_cur" => b"d5c2_cur",
        b"subset_int_cur" => b"subsetintcur",
        _ => b"",
    };
    [modern, legacy]
        .into_iter()
        .filter(|name| !name.is_empty())
        .find_map(|name| {
            bytes
                .windows(name.len() + 3)
                .position(|window| {
                    window[0] == 0x0f
                        && matches!(window[1], 0x0d | 0x0e)
                        && usize::from(window[2]) == name.len()
                        && &window[3..] == name
                })
                .map(|marker| (marker, name.len()))
        })
}

fn decode_cache_resolving_refs<T>(
    bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
    seen: &mut Vec<usize>,
    decode_inline: fn(&[u8], usize) -> Option<T>,
    int_width: usize,
) -> Option<T> {
    if let Some(decoded) = decode_inline(bytes, int_width) {
        return Some(decoded);
    }
    let table = tables.for_width(int_width);
    for index in subtype_refs(bytes, int_width) {
        if seen.contains(&index) {
            continue;
        }
        let target = *table.get(index)?;
        seen.push(index);
        if let Some(decoded) = decode_cache_resolving_refs(
            subtype_span(active_bytes, target, int_width)?,
            active_bytes,
            tables,
            seen,
            decode_inline,
            int_width,
        ) {
            return Some(decoded);
        }
    }
    None
}

/// Byte positions of the stream's subtype definitions, one table per candidate
/// integer width.
///
/// A subtype definition opens as `0x0f` followed by a `0x0d`/`0x0e` name token
/// other than `ref`; the table indexes definitions in stream order. Definition
/// openings are recognized only at token boundaries — the same byte pattern
/// inside an `f64` payload is data, not a definition — so the table is built by
/// token-walking the framed records, not by scanning raw bytes.
pub struct SubtypeTables {
    tables: [Vec<usize>; INT_WIDTHS.len()],
}

impl SubtypeTables {
    /// Build the tables by token-walking each framed record of `bytes`.
    pub fn from_records(records: &[Record], bytes: &[u8]) -> Self {
        Self {
            tables: INT_WIDTHS.map(|walk_width| {
                let mut table = Vec::new();
                for record in records {
                    collect_defs_in_span(
                        bytes,
                        record.offset,
                        record.offset + record.len,
                        walk_width,
                        &mut table,
                    );
                }
                table
            }),
        }
    }

    /// Build the tables by token-walking `bytes` as one contiguous token run.
    pub fn from_stream(bytes: &[u8]) -> Self {
        Self {
            tables: INT_WIDTHS.map(|walk_width| {
                let mut table = Vec::new();
                collect_defs_in_span(bytes, 0, bytes.len(), walk_width, &mut table);
                table
            }),
        }
    }

    fn for_width(&self, int_width: usize) -> &[usize] {
        INT_WIDTHS
            .iter()
            .position(|&width| width == int_width)
            .map_or(&[], |slot| self.tables[slot].as_slice())
    }
}

/// Append the token-boundary subtype-definition openings in
/// `bytes[start..end]` to `table`. Stops at the first unwalkable token.
fn collect_defs_in_span(
    bytes: &[u8],
    start: usize,
    end: usize,
    int_width: usize,
    table: &mut Vec<usize>,
) {
    let end = end.min(bytes.len());
    let mut pos = start;
    while pos < end {
        if bytes[pos] == 0x0f && matches!(bytes.get(pos + 1), Some(0x0d | 0x0e)) {
            let len = usize::from(*bytes.get(pos + 2).unwrap_or(&0));
            if let Some(name) = bytes.get(pos + 3..pos + 3 + len) {
                if name != b"ref" {
                    table.push(pos);
                }
            }
        }
        match next_token(bytes, pos, int_width) {
            Some(next) => pos = next,
            None => return,
        }
    }
}

/// Subtype-table reference indices in `bytes`, in token order. References are
/// recognized only at token boundaries, mirroring [`SubtypeTables`].
fn subtype_refs(bytes: &[u8], int_width: usize) -> Vec<usize> {
    let mut refs = Vec::new();
    let marker = b"\x0f\x0d\x03ref\x04";
    let mut pos = 0usize;
    while pos < bytes.len() {
        if bytes[pos..].starts_with(marker) {
            if let Some(index) = read_int(bytes, pos + marker.len(), int_width) {
                if index >= 0 {
                    refs.push(index as usize);
                }
            }
        }
        match next_token(bytes, pos, int_width) {
            Some(next) => pos = next,
            None => break,
        }
    }
    refs
}

fn subtype_span(bytes: &[u8], start: usize, int_width: usize) -> Option<&[u8]> {
    let mut depth = 0usize;
    let mut pos = start;
    while pos < bytes.len() {
        match bytes[pos] {
            0x0f => depth += 1,
            0x10 => {
                depth = depth.checked_sub(1)?;
                if depth == 0 {
                    return bytes.get(start..=pos);
                }
            }
            _ => {}
        }
        pos = next_token(bytes, pos, int_width)?;
    }
    None
}

fn next_token(bytes: &[u8], pos: usize, int_width: usize) -> Option<usize> {
    let tag = *bytes.get(pos)?;
    let fixed = match tag {
        0x02 => 2,
        0x03 => 3,
        0x04 | 0x0c | 0x15 => 1 + int_width,
        0x06 | 0x17 => 9,
        0x05 => 5,
        0x0a | 0x0b | 0x0f | 0x10 | 0x11 => 1,
        0x13 | 0x14 => 25,
        0x16 => 17,
        0x07 | 0x0d | 0x0e => 2 + usize::from(*bytes.get(pos + 1)?),
        0x08 => {
            3 + usize::from(u16::from_le_bytes(
                bytes.get(pos + 1..pos + 3)?.try_into().ok()?,
            ))
        }
        0x09 | 0x12 => {
            5 + usize::try_from(u32::from_le_bytes(
                bytes.get(pos + 1..pos + 5)?.try_into().ok()?,
            ))
            .ok()?
        }
        _ => return None,
    };
    let next = pos.checked_add(fixed)?;
    (next <= bytes.len()).then_some(next)
}

/// Decode the first well-formed 2D `nubs` block in a pcurve record.
pub fn decode_pcurve_cache(record_bytes: &[u8]) -> Option<NurbsPcurve> {
    INT_WIDTHS
        .into_iter()
        .find_map(|int_width| decode_pcurve_cache_at(record_bytes, int_width))
}

fn decode_pcurve_cache_at(record_bytes: &[u8], int_width: usize) -> Option<NurbsPcurve> {
    marker_positions(record_bytes)
        .into_iter()
        .find_map(|pos| decode_pcurve_block(record_bytes, pos, int_width))
}

/// Decode a 2D pcurve cache, resolving a nested ASM subtype-table reference
/// when the pcurve record delegates its UV carrier to an `intcurve` block.
pub fn decode_pcurve_cache_resolving_refs(
    record_bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
) -> Option<NurbsPcurve> {
    INT_WIDTHS.into_iter().find_map(|int_width| {
        decode_cache_resolving_refs(
            record_bytes,
            active_bytes,
            tables,
            &mut Vec::new(),
            decode_pcurve_cache_at,
            int_width,
        )
    })
}

/// Decode every candidate 2D `nubs`/`nurbs` block reachable from a pcurve
/// carrier record: the record's own blocks plus, through nested `ref N`
/// subtype references, the blocks of the definitions it links. A ref-form
/// pcurve delegates its UV carrier to an `intcurve` entity whose record can
/// hold several 2D blocks (side pcurves and construction machinery); the
/// caller selects among the candidates by checking their endpoints against
/// the face surface and edge vertices.
pub fn decode_pcurve_cache_candidates_resolving_refs(
    record_bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
) -> Vec<NurbsPcurve> {
    for int_width in INT_WIDTHS {
        let mut out = Vec::new();
        collect_pcurve_candidates(
            record_bytes,
            active_bytes,
            tables,
            &mut Vec::new(),
            int_width,
            &mut out,
        );
        if !out.is_empty() {
            return out;
        }
    }
    Vec::new()
}

fn collect_pcurve_candidates(
    bytes: &[u8],
    active_bytes: &[u8],
    tables: &SubtypeTables,
    seen: &mut Vec<usize>,
    int_width: usize,
    out: &mut Vec<NurbsPcurve>,
) {
    // A 3D curve block's bytes can also parse as a 2D block; such ambiguous
    // reads rank after every unambiguous 2D block so an unverified caller
    // taking the first candidate never picks a misread 3D carrier.
    let mut ambiguous = Vec::new();
    for position in marker_positions(bytes) {
        if let Some(pcurve) = decode_pcurve_block(bytes, position, int_width) {
            if decode_curve_block(bytes, position, int_width).is_some() {
                ambiguous.push(pcurve);
            } else {
                out.push(pcurve);
            }
        }
    }
    out.append(&mut ambiguous);
    let table = tables.for_width(int_width);
    for index in subtype_refs(bytes, int_width) {
        if seen.contains(&index) {
            continue;
        }
        seen.push(index);
        let Some(&target) = table.get(index) else {
            continue;
        };
        let Some(span) = subtype_span(active_bytes, target, int_width) else {
            continue;
        };
        collect_pcurve_candidates(span, active_bytes, tables, seen, int_width, out);
    }
}

#[cfg(test)]
mod width_tests {
    use super::*;

    fn push_int(out: &mut Vec<u8>, tag: u8, value: i64, int_width: usize) {
        out.push(tag);
        if int_width == 4 {
            out.extend_from_slice(
                &i32::try_from(value)
                    .expect("test value fits i32")
                    .to_le_bytes(),
            );
        } else {
            out.extend_from_slice(&value.to_le_bytes());
        }
    }

    fn push_f64(out: &mut Vec<u8>, value: f64) {
        out.push(0x06);
        out.extend_from_slice(&value.to_le_bytes());
    }

    /// A degree-1 two-pole 3D `nubs` curve block over `[0, 1]`.
    fn curve_block(int_width: usize) -> Vec<u8> {
        let mut b = NUBS_MARKER.to_vec();
        push_int(&mut b, 0x04, 1, int_width); // degree
        push_int(&mut b, 0x15, 0, int_width); // open closure
        push_int(&mut b, 0x04, 2, int_width); // unique knot count
        push_f64(&mut b, 0.0);
        push_int(&mut b, 0x04, 1, int_width);
        push_f64(&mut b, 1.0);
        push_int(&mut b, 0x04, 1, int_width);
        for component in [0.0, 0.0, 0.0, 1.0, 2.0, 3.0] {
            push_f64(&mut b, component);
        }
        b
    }

    /// A degree-1 2×2-pole `nubs` surface block over `[0, 1]²`.
    fn surface_block(int_width: usize) -> Vec<u8> {
        let mut b = NUBS_MARKER.to_vec();
        push_int(&mut b, 0x04, 1, int_width); // u degree
        push_int(&mut b, 0x04, 1, int_width); // v degree
        for _ in 0..4 {
            push_int(&mut b, 0x15, 0, int_width); // periodic/singularity enums
        }
        push_int(&mut b, 0x04, 2, int_width); // unique u knots
        push_int(&mut b, 0x04, 2, int_width); // unique v knots
        for _ in 0..2 {
            push_f64(&mut b, 0.0);
            push_int(&mut b, 0x04, 1, int_width);
            push_f64(&mut b, 1.0);
            push_int(&mut b, 0x04, 1, int_width);
        }
        for pole in 0..4 {
            push_f64(&mut b, f64::from(pole));
            push_f64(&mut b, 0.0);
            push_f64(&mut b, 0.0);
        }
        b
    }

    #[test]
    fn curve_cache_decodes_in_both_integer_widths() {
        for int_width in [4usize, 8] {
            let curve = decode_curve_cache(&curve_block(int_width))
                .unwrap_or_else(|| panic!("curve cache at width {int_width}"));
            assert_eq!(curve.degree, 1);
            assert_eq!(curve.control_points.len(), 2);
            assert_eq!(curve.control_points[1].x, 10.0); // cm→mm ×10
            assert_eq!(curve.knots, vec![0.0, 0.0, 1.0, 1.0]);
        }
    }

    #[test]
    fn surface_cache_decodes_in_both_integer_widths() {
        for int_width in [4usize, 8] {
            let surface = decode_surface_cache(&surface_block(int_width))
                .unwrap_or_else(|| panic!("surface cache at width {int_width}"));
            assert_eq!((surface.u_degree, surface.v_degree), (1, 1));
            assert_eq!((surface.u_count, surface.v_count), (2, 2));
        }
    }

    #[test]
    fn surface_cache_resolves_width4_subtype_ref() {
        // Active slice: one named subtype span holding the surface cache.
        let mut active = vec![0x0f, 0x0d, 0x07];
        active.extend_from_slice(b"spl_sur");
        active.extend_from_slice(&surface_block(4));
        active.push(0x10);
        // Record: `ref 0` into the subtype table, 4-byte index payload.
        let mut record = vec![0x0f, 0x0d, 0x03];
        record.extend_from_slice(b"ref");
        push_int(&mut record, 0x04, 0, 4);
        record.push(0x10);
        let surface = decode_surface_cache_resolving_refs(
            &record,
            &active,
            &SubtypeTables::from_stream(&active),
        )
        .expect("resolved width-4 ref");
        assert_eq!((surface.u_count, surface.v_count), (2, 2));
    }
}