ogeom-offset 0.9.15

Offsetting, shelling, sweeping, lofting and draft
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
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
//! Pipes and lofts: the sweeps whose surfaces are already in the vocabulary.
//!
//! A circular profile along a straight spine is a cylinder; around a full
//! circle it is a torus; along an arc it is a torus segment, built from two
//! half-tube patches and two meridian caps so that every edge is a circle
//! with a closed-form chart. A ruled loft between two parallel sections is
//! walls of planes and cones: segment to segment gives the planar quad,
//! coaxial circle to circle gives the frustum the cone primitive already
//! builds, and a skew ruled wall between two segments is the bilinear patch
//! through its corners, exact. The sweeps that need surfaces with no closed
//! form (a free-form spine, a smoothed skin through many sections) are
//! fitted: the skin holds every section to a stated tolerance and refuses
//! when it cannot reach it.

use ogeom_algo::{
    Built, History, edge_vertices, make_cone, make_cylinder, make_edge, make_edge_between,
    make_face_with_pcurves, make_solid, make_torus, make_vertex, sew,
};
use ogeom_core::{OgeomResult, Tolerances, ogeom_bail};
use ogeom_geom::Curve3d as _;
use ogeom_geom::Transformable as _;
use ogeom_geom::{
    CircleCurve, Curve, Line2d, LineCurve, PlaneSurface, SurfaceGeometry, TorusSurface,
};
use ogeom_math::{Circle, Direction, Frame, Plane, Point, Point2, Torus, Transform, Vector};
use ogeom_topo::{EdgeData, EdgeRepr, Filter, Model, Shape, ShapeType, VertexData, explore};

/// Sweep a circular profile of `radius` along a spine edge.
///
/// A straight spine gives a cylinder, a full circular spine a torus, an arc
/// a torus segment. The history generates the solid from the spine.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if the spine is
/// not straight or circular, the profile radius is not usable, or the tube
/// would swallow its own spine.
pub fn make_pipe(
    model: &mut Model,
    spine: &Shape,
    radius: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if !radius.is_finite() || radius <= tol.confusion() {
        ogeom_bail!(Construction, "a pipe of radius {radius} holds nothing");
    }
    let (curve, range) = {
        let Some(data) = model.node(spine).and_then(|n| n.data().as_edge()) else {
            ogeom_bail!(Construction, "a pipe runs along an edge");
        };
        let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
            ogeom_bail!(Construction, "the spine has no curve");
        };
        let Some(geometry) = model.geometry().curve(*curve) else {
            ogeom_bail!(Dangling, "curve is not in this model");
        };
        (geometry.clone(), *range)
    };
    let mut built = match &curve {
        Curve::Line(line) => {
            let start = curve.point_at(range.0, tol)?;
            let length = range.1 - range.0;
            let frame = Frame::about(start, line.axis().direction);
            make_cylinder(model, frame, radius, length, tol)?
        }
        Curve::Circle(c) => {
            let circle = c.circle();
            if radius >= circle.radius() - tol.confusion() {
                ogeom_bail!(
                    Construction,
                    "a tube of radius {radius} swallows its spine of radius {}",
                    circle.radius()
                );
            }
            let closed = curve
                .point_at(range.0, tol)?
                .distance(curve.point_at(range.1, tol)?)
                <= tol.confusion();
            if closed {
                make_torus(model, circle.frame(), circle.radius(), radius, tol)?
            } else {
                pipe_segment(model, circle, range, radius, tol)?
            }
        }
        _ => ogeom_bail!(
            Construction,
            "a pipe along a free-form spine needs the sweep-surface \
             machinery; see docs/PARITY.md, offset.sweeps"
        ),
    };
    built.history.generate(spine, built.shape.clone());
    Ok(built)
}

/// The torus segment: two half-tube patches and two meridian caps.
///
/// The tube circles are framed so their own parameter *is* the torus tube
/// angle, which makes every tube pcurve a vertical line in the chart and the
/// two patches the clean rectangles `v ∈ [0, π]` and `[π, 2π]`. The outer
/// equator is then the seam between the halves across the period (one edge,
/// two chart rows), which is exactly what [`ogeom_algo::attach_seam`] exists to
/// say.
fn pipe_segment(
    model: &mut Model,
    spine: Circle,
    range: (f64, f64),
    radius: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    let frame = spine.frame();
    let (x, y, z) = (frame.x().vector(), frame.y().vector(), frame.z().vector());
    let major = spine.radius();
    let radial = |u: f64| x * u.cos() + y * u.sin();
    let tangent = |u: f64| x * -u.sin() + y * u.cos();
    let tube_point = |u: f64, v: f64| {
        frame.origin() + radial(u) * radius.mul_add(v.cos(), major) + z * (radius * v.sin())
    };
    let pi = core::f64::consts::PI;
    let tau = core::f64::consts::TAU;

    let torus: SurfaceGeometry = TorusSurface::new(Torus::new(frame, major, radius, tol)?).into();
    let surface_id = model.geometry_mut().add_surface(torus);

    // Vertices at the tube's v = 0 and v = π points of each end.
    let ends = [range.0, range.1];
    let mut verts: Vec<Vec<Shape>> = Vec::new();
    for &u in &ends {
        verts.push(vec![
            make_vertex(model, tube_point(u, 0.0)).shape,
            make_vertex(model, tube_point(u, pi)).shape,
        ]);
    }

    // The tube circles at each end, split at v = 0 and v = π, framed so that
    // the circle's parameter equals the torus tube angle: `z` against the
    // spine tangent makes the frame's `y` the torus's own axis.
    let mut tube_arcs: Vec<Vec<Shape>> = Vec::new();
    for (k, &u) in ends.iter().enumerate() {
        let centre = frame.origin() + radial(u) * major;
        let circle = Circle::new(
            Frame::new(
                centre,
                Direction::new(-tangent(u), tol)?,
                Direction::new(radial(u), tol)?,
                tol,
            )?,
            radius,
            tol,
        )?;
        let curve = Curve::Circle(CircleCurve::new(circle));
        let arcs = vec![
            make_edge_between(
                model,
                curve.clone(),
                (0.0, pi),
                &verts[k][0],
                &verts[k][1],
                tol,
            )?
            .shape,
            make_edge_between(model, curve, (pi, tau), &verts[k][1], &verts[k][0], tol)?.shape,
        ];
        // In the chart both arcs run up the column at this end's angle.
        let column = Line2d::over(
            ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
            0.0,
            tau,
        )?;
        ogeom_algo::attach_pcurve(
            model,
            &arcs[0],
            column.into(),
            surface_id,
            ogeom_topo::Location::identity(),
            (0.0, pi),
        )?;
        ogeom_algo::attach_pcurve(
            model,
            &arcs[1],
            column.into(),
            surface_id,
            ogeom_topo::Location::identity(),
            (pi, tau),
        )?;
        tube_arcs.push(arcs);
    }

    // The long edges: the parallels at v = 0 and v = π, parameterized by the
    // spine's own angle.
    let parallel = |model: &mut Model, v: f64, from: &Shape, to: &Shape| -> OgeomResult<Shape> {
        let height = radius * v.sin();
        let ring = radius.mul_add(v.cos(), major);
        let circle = Circle::new(
            Frame::new(frame.origin() + z * height, frame.z(), frame.x(), tol)?,
            ring,
            tol,
        )?;
        let curve = Curve::Circle(CircleCurve::new(circle));
        Ok(make_edge_between(model, curve, range, from, to, tol)?.shape)
    };
    let row = |v: f64| -> OgeomResult<Line2d> {
        Line2d::over(
            ogeom_math::Axis2::new(Point2::new(0.0, v), ogeom_math::Direction2::X),
            range.0 - 1.0,
            range.1 + 1.0,
        )
    };
    let inner = parallel(model, pi, &verts[0][1], &verts[1][1])?;
    ogeom_algo::attach_pcurve(
        model,
        &inner,
        row(pi)?.into(),
        surface_id,
        ogeom_topo::Location::identity(),
        range,
    )?;
    // The outer equator bounds both halves across the period: v = 0 for its
    // forward use under the lower patch, v = 2Ï€ for its reversed use under
    // the upper: a seam, said as one.
    let outer = parallel(model, 0.0, &verts[0][0], &verts[1][0])?;
    ogeom_algo::attach_seam(
        model,
        &outer,
        row(0.0)?.into(),
        row(tau)?.into(),
        surface_id,
        ogeom_topo::Location::identity(),
        range,
    )?;

    // The two half-tube patches, on the one registered surface, each ring
    // counter-clockwise in the chart: along the spine, up the far end's
    // tube, back, and down the near end's.
    let lower = {
        let wire = ogeom_algo::make_wire(
            model,
            &[
                outer.clone(),
                tube_arcs[1][0].clone(),
                inner.reversed(),
                tube_arcs[0][0].reversed(),
            ],
            tol,
        )?
        .shape;
        ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape
    };
    let upper = {
        let wire = ogeom_algo::make_wire(
            model,
            &[
                inner.clone(),
                tube_arcs[1][1].clone(),
                outer.reversed(),
                tube_arcs[0][1].reversed(),
            ],
            tol,
        )?
        .shape;
        ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape
    };

    // The meridian caps, their outward normals along the spine and away from
    // the material between the ends.
    let mut caps: Vec<Shape> = Vec::new();
    for (k, &u) in ends.iter().enumerate() {
        let outward = if k == 0 { -tangent(u) } else { tangent(u) };
        let centre = frame.origin() + radial(u) * major;
        let plane = Plane::through(centre, Direction::new(outward, tol)?);
        let reach = (major + radius) * 2.0;
        let surface: SurfaceGeometry =
            PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?.into();
        // The tube circles turn about the spine's backward tangent: the near
        // cap walks its circle forward, the far one walks it back.
        let ring = if k == 0 {
            vec![tube_arcs[k][0].clone(), tube_arcs[k][1].clone()]
        } else {
            vec![tube_arcs[k][1].reversed(), tube_arcs[k][0].reversed()]
        };
        caps.push(make_face_with_pcurves(model, surface, &[ring], tol)?.shape);
    }

    let faces = [lower, upper, caps[0].clone(), caps[1].clone()];
    let sewn = sew(model, &faces, tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the pipe segment did not close");
    }
    make_solid(model, std::slice::from_ref(&sewn.shells[0]))
}

/// Loft two parallel closed sections into a solid, ruled.
///
/// Two coaxial circles give the cylinder or the cone frustum; two polygons
/// with the same corner count give planar walls. The sections pair edge by
/// edge in traversal order.
///
/// A wall between two segments that are not coplanar is the bilinear patch
/// through its four corners (the ruled surface between them, exact), so
/// sections may be turned against each other or differ in shape.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if the sections
/// are not both circles or both polygons of the same count, or are not on
/// parallel planes.
pub fn make_loft(
    model: &mut Model,
    bottom: &Shape,
    top: &Shape,
    tol: Tolerances,
) -> OgeomResult<Built> {
    // A vertex for either section is the loft to a point: a cone over a
    // circle, an exact pyramid over a polygon.
    match (model.kind_of(bottom)?, model.kind_of(top)?) {
        (ShapeType::Wire, ShapeType::Vertex) => {
            return loft_to_point(model, bottom, top, tol);
        }
        (ShapeType::Vertex, ShapeType::Wire) => {
            let mut built = loft_to_point(model, top, bottom, tol)?;
            // The apex was named first: the same solid, the history the same.
            built.history.generate(bottom, built.shape.clone());
            return Ok(built);
        }
        _ => {}
    }
    for wire in [bottom, top] {
        if model.kind_of(wire)? != ShapeType::Wire {
            ogeom_bail!(Construction, "a loft runs between wires");
        }
        if !ogeom_algo::is_wire_closed(model, wire, tol)? {
            ogeom_bail!(Construction, "a loft section must be closed");
        }
    }
    let circle_of = |model: &Model, wire: &Shape| -> OgeomResult<Option<Circle>> {
        let edges = explore(model, wire, Filter::OfType(ShapeType::Edge))?;
        if edges.len() != 1 {
            return Ok(None);
        }
        let Some(data) = model.node(&edges[0]).and_then(|n| n.data().as_edge()) else {
            return Ok(None);
        };
        let Some(EdgeRepr::Curve3d { curve, .. }) = data.curve3d() else {
            return Ok(None);
        };
        match model.geometry().curve(*curve) {
            Some(Curve::Circle(c)) => Ok(Some(c.circle())),
            _ => Ok(None),
        }
    };

    if let (Some(lower), Some(upper)) = (circle_of(model, bottom)?, circle_of(model, top)?) {
        // Coaxial circles: the revolved primitives already build these.
        let axis = lower.frame().z().vector();
        let rise = upper.centre() - lower.centre();
        let height = rise.dot(axis);
        if rise.cross(axis).magnitude() > tol.confusion() * 10.0 || height.abs() <= tol.confusion()
        {
            ogeom_bail!(
                Construction,
                "lofted circles must be coaxial on parallel planes; the \
                 oblique loft needs the sweep machinery; see the deferred \
                 table"
            );
        }
        let frame = if height > 0.0 {
            Frame::new(lower.centre(), lower.frame().z(), lower.frame().x(), tol)?
        } else {
            Frame::new(
                lower.centre(),
                lower.frame().z().reversed(),
                lower.frame().x(),
                tol,
            )?
        };
        let mut built = if (lower.radius() - upper.radius()).abs() <= tol.confusion() {
            make_cylinder(model, frame, lower.radius(), height.abs(), tol)?
        } else {
            make_cone(
                model,
                frame,
                lower.radius(),
                upper.radius(),
                height.abs(),
                tol,
            )?
        };
        built.history.generate(bottom, built.shape.clone());
        built.history.generate(top, built.shape.clone());
        return Ok(built);
    }

    // Polygonal sections: matched corners, planar walls.
    let corners_of = |model: &Model, wire: &Shape| -> OgeomResult<Vec<Point>> {
        let mut out = Vec::new();
        for edge in explore(model, wire, Filter::OfType(ShapeType::Edge))? {
            let Some(data) = model.node(&edge).and_then(|n| n.data().as_edge()) else {
                ogeom_bail!(Construction, "a section edge holds no data");
            };
            let Some(EdgeRepr::Curve3d { curve, .. }) = data.curve3d() else {
                ogeom_bail!(Construction, "a section edge has no curve");
            };
            let Some(Curve::Line(_)) = model.geometry().curve(*curve) else {
                ogeom_bail!(
                    Construction,
                    "a mixed or curved section needs the skinning machinery; see \
                     docs/PARITY.md, offset.sweeps"
                );
            };
            let Some((sv, _)) = edge_vertices(model, &edge)? else {
                ogeom_bail!(Construction, "a section edge has no vertices");
            };
            let Some(data) = model.node(&sv).and_then(|n| n.data().as_vertex()) else {
                ogeom_bail!(Construction, "a section vertex holds no point");
            };
            out.push(sv.transform(model.datums())?.apply(data.point));
        }
        Ok(out)
    };
    let low = corners_of(model, bottom)?;
    let high = corners_of(model, top)?;
    if low.len() != high.len() {
        ogeom_bail!(
            Construction,
            "lofted sections must have the same corner count, found {} and {}",
            low.len(),
            high.len()
        );
    }
    let n = low.len();
    let centroid = {
        let mut c = Vector::new(0.0, 0.0, 0.0);
        for p in low.iter().chain(high.iter()) {
            c += p.to_vector();
        }
        #[allow(clippy::cast_precision_loss)]
        let count = 2.0 * n as f64;
        Point::from_vector(c / count)
    };

    // Shared vertices and edges, then walls and caps referencing them.
    let vl: Vec<Shape> = low.iter().map(|p| make_vertex(model, *p).shape).collect();
    let vh: Vec<Shape> = high.iter().map(|p| make_vertex(model, *p).shape).collect();
    let seg = |model: &mut Model, a: (&Shape, Point), b: (&Shape, Point)| -> OgeomResult<Shape> {
        let line = LineCurve::segment(a.1, b.1, tol)?;
        let curve = Curve::Line(line);
        let domain = curve.domain();
        Ok(make_edge_between(model, curve, domain, a.0, b.0, tol)?.shape)
    };
    let mut low_edges = Vec::with_capacity(n);
    let mut high_edges = Vec::with_capacity(n);
    let mut rails = Vec::with_capacity(n);
    for i in 0..n {
        let j = (i + 1) % n;
        low_edges.push(seg(model, (&vl[i], low[i]), (&vl[j], low[j]))?);
        high_edges.push(seg(model, (&vh[i], high[i]), (&vh[j], high[j]))?);
        rails.push(seg(model, (&vl[i], low[i]), (&vh[i], high[i]))?);
    }

    let planar = |model: &mut Model, corners: &[Point], edges: Vec<Shape>| -> OgeomResult<Shape> {
        let normal = {
            let mut n = (corners[1] - corners[0]).cross(corners[2] - corners[0]);
            let m = n.magnitude();
            if m <= tol.confusion() {
                ogeom_bail!(Construction, "a loft wall is degenerate");
            }
            n /= m;
            if n.dot(corners[0] - centroid) < 0.0 {
                -n
            } else {
                n
            }
        };
        let skew = corners.iter().any(|p| {
            Plane::through(
                corners[0],
                Direction::new(normal, tol).unwrap_or(Direction::Z),
            )
            .distance_to(*p)
                > tol.confusion() * 10.0
        });
        if skew {
            // A wall between two segments that do not lie in one plane is
            // the ruled surface between them, and that is exact: bilinear
            // in the four corners, a B-spline of degree one each way.
            if corners.len() != 4 || edges.len() != 4 {
                ogeom_bail!(Construction, "a skew ruled wall has four corners");
            }
            return bilinear_wall(model, corners, &edges, centroid, tol);
        }
        let plane = Plane::through(corners[0], Direction::new(normal, tol)?);
        let mut reach = 1.0_f64;
        for p in corners {
            reach = reach.max(p.distance(corners[0]) * 2.0);
        }
        let surface: SurfaceGeometry =
            PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?.into();
        // The ring keeps the material on its left about the outward normal:
        // one walking the corners clockwise about it is walked back.
        let turn = (0..corners.len())
            .map(|i| {
                corners[i]
                    .to_vector()
                    .cross(corners[(i + 1) % corners.len()].to_vector())
            })
            .fold(Vector::new(0.0, 0.0, 0.0), |sum, v| sum + v);
        let ring = if turn.dot(normal) < 0.0 {
            walked_back(&edges)
        } else {
            edges
        };
        Ok(make_face_with_pcurves(model, surface, &[ring], tol)?.shape)
    };

    let mut faces: Vec<Shape> = Vec::with_capacity(n + 2);
    for i in 0..n {
        let j = (i + 1) % n;
        faces.push(planar(
            model,
            &[low[i], low[j], high[j], high[i]],
            vec![
                low_edges[i].clone(),
                rails[j].clone(),
                high_edges[i].reversed(),
                rails[i].reversed(),
            ],
        )?);
    }
    faces.push(planar(model, &low, low_edges.clone())?);
    faces.push(planar(model, &high, high_edges.clone())?);

    let sewn = sew(model, &faces, tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the loft did not close");
    }
    let mut built = make_solid(model, std::slice::from_ref(&sewn.shells[0]))?;
    built.history.generate(bottom, built.shape.clone());
    built.history.generate(top, built.shape.clone());
    Ok(built)
}

/// The ruled wall between two straight segments that are not coplanar: the
/// bilinear patch through its four corners, exact, as a B-spline of degree
/// one each way.
///
/// `corners` run round the wall (low start, low end, high end, high
/// start) and `edges` walk them in that order, the third and fourth
/// reversed as the caller's wire has them. Each edge's pcurve is the chart
/// side it lies on, parameterized by the edge's own range so the two agree
/// point for point; the wall faces away from `centroid`.
fn bilinear_wall(
    model: &mut Model,
    corners: &[Point],
    edges: &[Shape],
    centroid: Point,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    use ogeom_geom::Surface as _;
    let (p00, p10, p11, p01) = (corners[0], corners[1], corners[2], corners[3]);
    let grid = ogeom_math::ControlGrid::new(vec![p00, p01, p10, p11], 2, 2)?;
    let line = ogeom_math::KnotVector::clamped_uniform(1, 2)?;
    let patch = ogeom_geom::BSplineSurface::new(line.clone(), line, &grid, tol)?;
    let outward = {
        let (du, dv) = patch.d1_at(0.5, 0.5, tol)?;
        let centre = patch.point_at(0.5, 0.5, tol)?;
        du.cross(dv).dot(centre - centroid) >= 0.0
    };
    let surface_id = model
        .geometry_mut()
        .add_surface(SurfaceGeometry::BSpline(patch));

    // Each edge's chart side, run in the edge's own direction over the
    // edge's own parameter range: a degree-one B-spline in the chart,
    // which is what makes the pcurve the edge's equal parameter for
    // parameter whatever length the edge has.
    let sides: [(Point2, Point2); 4] = [
        (Point2::new(0.0, 0.0), Point2::new(1.0, 0.0)),
        (Point2::new(1.0, 0.0), Point2::new(1.0, 1.0)),
        (Point2::new(0.0, 1.0), Point2::new(1.0, 1.0)),
        (Point2::new(0.0, 0.0), Point2::new(0.0, 1.0)),
    ];
    for (edge, (from, to)) in edges.iter().zip(sides) {
        let range = {
            let Some(node) = model.node(edge) else {
                ogeom_bail!(Dangling, "a loft edge is not in this model");
            };
            let Some(data) = node.data().as_edge() else {
                ogeom_bail!(Construction, "a loft edge holds no edge data");
            };
            let Some(EdgeRepr::Curve3d { range, .. }) = data.curve3d() else {
                ogeom_bail!(Construction, "a loft edge has no curve");
            };
            *range
        };
        let knots = ogeom_math::KnotVector::new(vec![range.0, range.0, range.1, range.1], 1)?;
        let pcurve = ogeom_geom::BSpline2d::new(knots, vec![from, to], tol)?;
        ogeom_algo::attach_pcurve(
            model,
            edge,
            pcurve.into(),
            surface_id,
            ogeom_topo::Location::identity(),
            range,
        )?;
    }
    let wire = ogeom_algo::make_wire(model, edges, tol)?.shape;
    let face = ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape;
    Ok(if outward { face } else { face.reversed() })
}

/// What a skin is fitted to: its rows of samples, and the geometry they
/// sample where the builder knows it.
struct Skin<'a> {
    /// `rows[j][i]` runs along row `j`: once round a section without the
    /// closing point where `round`, across an open strip otherwise.
    rows: Vec<Vec<Point>>,
    /// Whether each row runs once round, its end its start.
    round: bool,
    /// Whether bare rows sit across the skin by chord length (sections a
    /// caller spaced) rather than centripetally.
    by_spacing: bool,
    /// The geometry the rows sample, if known: `point(u, v)` with `u` along
    /// the rows over the sampling's `u` range (once round where `round`, its
    /// end the start again) and `v` across them, and where the fit starts
    /// sampling it.
    traced: Option<Traced<'a>>,
}

/// The geometry a skin traces and where its fit starts sampling it.
struct Traced<'a> {
    point: Box<dyn Fn(f64, f64) -> OgeomResult<Point> + 'a>,
    sampling: ogeom_geom::fit::Sampling,
}

/// One section a skin passes through: a closed loop read by arc length,
/// or the point a skin narrows to.
#[derive(Clone)]
enum Section {
    Loop(ArcLoop),
    Point(Point),
    /// A loop moved halfway toward a point, every point of it.
    Halfway(ArcLoop, Point),
}

impl Section {
    /// The point a fraction `f` of the way round.
    fn at(&self, f: f64) -> Point {
        match self {
            Self::Loop(arc) => arc.at(f),
            Self::Point(p) => *p,
            Self::Halfway(arc, to) => {
                Point::from_vector((arc.at(f).to_vector() + to.to_vector()) * 0.5)
            }
        }
    }
}

/// The samples a skin's sections take round: an even fraction apart, from
/// each section's own start.
const AROUND_SECTION: usize = 48;

/// `n + 1` even fractions of one, from naught to one.
fn fractions(n: usize) -> Vec<f64> {
    (0..=n)
        .map(|i| {
            #[allow(clippy::cast_precision_loss, reason = "a small count")]
            let f = i as f64 / n as f64;
            f
        })
        .collect()
}

impl<'a> Skin<'a> {
    /// A skin over bare rows, each once round: fitted through them,
    /// measured at them.
    fn rows(rows: Vec<Vec<Point>>) -> Self {
        Self {
            rows,
            round: true,
            by_spacing: false,
            traced: None,
        }
    }

    /// A skin whose every column is a function of its parameter along the
    /// rows: `column(u)` is the column of points at `u`, one per row,
    /// sampled at `us` to start with and checked and refined between them.
    /// Across the rows the samples are all there is of the skin: the rows
    /// sit there at the parameters [`ogeom_geom::fit::grid_parameters`]
    /// gives them, by chord length where `by_spacing`, centripetally
    /// otherwise. Where `round`, the last of `us` is the first again; where
    /// `closed_v`, the rows loop and the first row closes it.
    fn columns(
        column: impl Fn(f64) -> OgeomResult<Vec<Point>> + 'a,
        us: Vec<f64>,
        round: bool,
        by_spacing: bool,
        closed_v: bool,
    ) -> OgeomResult<Self> {
        let sampled: Vec<Vec<Point>> = us[..us.len() - usize::from(round)]
            .iter()
            .map(|u| column(*u))
            .collect::<OgeomResult<_>>()?;
        let count = sampled[0].len();
        let rows: Vec<Vec<Point>> = (0..count)
            .map(|j| sampled.iter().map(|c| c[j]).collect())
            .collect();
        let mut grid: Vec<Vec<Point>> = rows
            .iter()
            .map(|r| {
                let mut r = r.clone();
                if round {
                    r.push(r[0]);
                }
                r
            })
            .collect();
        if closed_v {
            grid.push(grid[0].clone());
        }
        let bare = Self {
            rows: rows.clone(),
            round,
            by_spacing,
            traced: None,
        };
        let (_, vs) = ogeom_geom::fit::grid_parameters(&grid, (false, by_spacing))?;
        if vs.windows(2).any(|w| w[1] <= w[0]) {
            // Rows that coincide have no order across the skin; the bare
            // rows decide what the fit makes of them.
            return Ok(bare);
        }
        let row_vs = vs.clone();
        let (u0, u1) = (us[0], us[us.len() - 1]);
        let held: std::cell::RefCell<ogeom_core::FastMap<u64, Vec<Point>>> =
            std::cell::RefCell::default();
        let point = move |u: f64, v: f64| -> OgeomResult<Point> {
            let Some(j) = row_vs.iter().position(|w| w.to_bits() == v.to_bits()) else {
                ogeom_bail!(Construction, "a skin is known across only at its rows");
            };
            // The end of the way round is its start, to the bit, so the
            // seam closes exactly.
            let u = if round && u >= u1 { u0 } else { u };
            if let Some(c) = held.borrow().get(&u.to_bits()) {
                return Ok(c[j % count]);
            }
            let c = column(u)?;
            if c.len() != count {
                ogeom_bail!(Construction, "a skin's column changed its length");
            }
            let p = c[j % count];
            held.borrow_mut().insert(u.to_bits(), c);
            Ok(p)
        };
        Ok(Self {
            traced: Some(Traced {
                point: Box::new(point),
                sampling: ogeom_geom::fit::Sampling {
                    us,
                    vs,
                    between: (true, false),
                    closed_v,
                    most: 512,
                },
            }),
            ..bare
        })
    }

    /// A skin known everywhere: `point(u, s)` with `u` along the rows and
    /// `s` a station index across them, a whole number at a station and a
    /// fraction between two. It is sampled at `us` and at every station
    /// from `stations.0` to `stations.1` to start with, and checked and
    /// refined between them both ways. Across, the skin's parameter runs
    /// from naught to one over the stations, evenly. Where `round`, the
    /// last of `us` is the first again.
    fn swept(
        point: impl Fn(f64, f64) -> OgeomResult<Point> + 'a,
        us: Vec<f64>,
        stations: (usize, usize),
        round: bool,
    ) -> OgeomResult<Self> {
        let (u0, u1) = (us[0], us[us.len() - 1]);
        #[allow(clippy::cast_precision_loss, reason = "station counts")]
        let (first, steps) = (stations.0 as f64, (stations.1 - stations.0) as f64);
        if steps < 1.0 {
            ogeom_bail!(Construction, "a swept skin needs two stations");
        }
        let vs: Vec<f64> = (stations.0..=stations.1)
            .map(|i| {
                #[allow(clippy::cast_precision_loss, reason = "station counts")]
                let step = (i - stations.0) as f64;
                step / steps
            })
            .collect();
        // The end of the way round is its start, to the bit, so the seam
        // closes exactly; a station is its whole index, to the bit.
        let point = move |u: f64, v: f64| -> OgeomResult<Point> {
            let s = first + v * steps;
            let whole = s.round();
            let s = if (s - whole).abs() <= 1e-9 { whole } else { s };
            point(if round && u >= u1 { u0 } else { u }, s)
        };
        let rows: Vec<Vec<Point>> = vs
            .iter()
            .map(|v| {
                us[..us.len() - usize::from(round)]
                    .iter()
                    .map(|u| point(*u, *v))
                    .collect::<OgeomResult<Vec<Point>>>()
            })
            .collect::<OgeomResult<_>>()?;
        Ok(Self {
            rows,
            round,
            by_spacing: false,
            traced: Some(Traced {
                point: Box::new(point),
                sampling: ogeom_geom::fit::Sampling {
                    us,
                    vs,
                    between: (true, true),
                    closed_v: false,
                    most: 512,
                },
            }),
        })
    }

    /// A skin through `sections`, each sampled at [`AROUND_SECTION`] even
    /// fractions of its length to start with (see [`Self::columns`]).
    fn sections(sections: Vec<Section>, closed: bool) -> OgeomResult<Self> {
        Self::columns(
            move |u| Ok(sections.iter().map(|s| s.at(u)).collect()),
            fractions(AROUND_SECTION),
            true,
            false,
            closed,
        )
    }

    /// The skin's fitted surface: where `round`, closed the way round (each
    /// row's end its start, so the row fits' pinned ends make the two
    /// border control columns equal); where `closed_v`, smoothly across the
    /// loop of its rows.
    fn fit(
        &self,
        closed_v: bool,
        tolerance: f64,
        tol: Tolerances,
    ) -> OgeomResult<ogeom_geom::fit::Fitted<ogeom_geom::BSplineSurface>> {
        match &self.traced {
            None => {
                let mut grid: Vec<Vec<Point>> = self
                    .rows
                    .iter()
                    .map(|row| {
                        let mut r = row.clone();
                        if self.round {
                            r.push(row[0]);
                        }
                        r
                    })
                    .collect();
                if closed_v {
                    grid.push(grid[0].clone());
                    ogeom_geom::fit::fit_surface_grid_closed_v(&grid, 3, tolerance, tol)
                } else if self.by_spacing {
                    ogeom_geom::fit::fit_surface_grid_sections(&grid, 3, tolerance, tol)
                } else {
                    ogeom_geom::fit::fit_surface_grid(&grid, 3, tolerance, tol)
                }
            }
            Some(traced) => {
                let mut sampling = traced.sampling.clone();
                sampling.closed_v = closed_v;
                ogeom_geom::fit::fit_surface_sampled(
                    |u, v| (traced.point)(u, v),
                    &sampling,
                    3,
                    tolerance,
                    tol,
                )
            }
        }
    }
}

/// A closed polyline read by arc length.
#[derive(Clone)]
struct ArcLoop {
    dense: Vec<Point>,
    /// The length run to each point of `dense`.
    lengths: Vec<f64>,
    /// The length round, the closing chord included.
    total: f64,
}

impl ArcLoop {
    fn new(dense: Vec<Point>) -> Self {
        let mut lengths = Vec::with_capacity(dense.len());
        lengths.push(0.0);
        for w in dense.windows(2) {
            let last = lengths[lengths.len() - 1];
            lengths.push(last + w[0].distance(w[1]));
        }
        let total = lengths[lengths.len() - 1] + dense[dense.len() - 1].distance(dense[0]);
        Self {
            dense,
            lengths,
            total,
        }
    }

    /// The point a fraction `f` of the length round from the first point;
    /// a whole turn is the first point again.
    fn at(&self, f: f64) -> Point {
        let f = if (0.0..1.0).contains(&f) { f } else { 0.0 };
        let target = self.total * f;
        let n = self.dense.len();
        let cursor = self.lengths[1..]
            .partition_point(|l| *l < target)
            .min(n - 1);
        let (a, b) = (self.dense[cursor], self.dense[(cursor + 1) % n]);
        let la = self.lengths[cursor];
        let lb = if cursor + 1 < n {
            self.lengths[cursor + 1]
        } else {
            self.total
        };
        let t = if lb > la {
            (target - la) / (lb - la)
        } else {
            0.0
        };
        a + (b - a) * t.clamp(0.0, 1.0)
    }
}

/// A skinned wall and the pieces a caller needs to close it: the rings at
/// both ends, their exact border curves off the control net, and the chart's
/// `u` window the ring pcurves span.
struct SkinnedWall {
    face: Shape,
    ring0: Shape,
    ring1: Shape,
    curve0: ogeom_geom::Curve,
    curve1: ogeom_geom::Curve,
    u_dom: (f64, f64),
}

/// The wall of a skin over a grid of section samples, closed the way round.
///
/// The wall is the skin's fitted surface ([`Skin::fit`]), with each row's
/// first sample repeated at its end: the row fits pin their ends, so the two
/// border control columns are *equal* and the seam closes exactly, not
/// within tolerance. The border iso-curves come straight off the control
/// net (the v-borders are the fitted sections, planar whenever the
/// sections are, which is what lets the caps be planes), and every pcurve
/// is an iso line in the fitted chart, same-parameter by construction.
fn skinned_wall(
    model: &mut Model,
    skin: &Skin<'_>,
    shared: (Option<&Shape>, Option<&Shape>),
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<SkinnedWall> {
    use ogeom_geom::Surface as _;
    let rows = &skin.rows;
    let fitted = skin.fit(false, tolerance, tol)?;
    if !fitted.met {
        ogeom_bail!(
            NotDone,
            "the skin reached {} against a target of {tolerance}",
            fitted.error
        );
    }
    let surface = fitted.curve;
    let (u_knots, v_knots) = (surface.u_knots().clone(), surface.v_knots().clone());
    let (k, l, net) = {
        let grid = surface.grid();
        let net: Vec<Point> = grid.points().iter().map(|w| (*w).point()).collect();
        (grid.u_count(), grid.v_count(), net)
    };
    let point_at = |i: usize, j: usize| -> Point { net[i * l + j] };
    let (u_dom, v_dom) = surface.domain();

    // Border curves straight off the net: v-borders are the end sections,
    // the u-border is the seam.
    let border_v = |j: usize| -> OgeomResult<ogeom_geom::Curve> {
        let control: Vec<Point> = (0..k).map(|i| point_at(i, j)).collect();
        Ok(ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            u_knots.clone(),
            control,
            tol,
        )?))
    };
    let seam_curve = {
        let control: Vec<Point> = (0..l).map(|j| point_at(0, j)).collect();
        ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            v_knots.clone(),
            control,
            tol,
        )?)
    };

    let surface_geo: SurfaceGeometry = surface.into();
    let surface_id = model.geometry_mut().add_surface(surface_geo.clone());

    // An end ring the neighbouring wall already built is adopted, not
    // refitted (see `adopt_border`).
    let slack = fitted.error + tol.confusion();
    let ring_of = |model: &mut Model,
                   j: usize,
                   given: Option<&Shape>|
     -> OgeomResult<(Shape, ogeom_geom::Curve)> {
        match given {
            Some(edge) => {
                adopt_border(model, edge, &surface_geo, slack, tol)?;
                Ok((edge.clone(), spine_curve_of(model, edge)?.0))
            }
            None => {
                let curve = border_v(j)?;
                Ok((make_edge(model, curve.clone(), u_dom, tol)?.shape, curve))
            }
        }
    };
    let (ring0, curve0) = ring_of(model, 0, shared.0)?;
    let (ring1, curve1) = ring_of(model, l - 1, shared.1)?;
    let anchor0 = ogeom_algo::edge_vertices(model, &ring0)?
        .map(|(a, _)| a)
        .ok_or_else(|| ogeom_core::ogeom_err!(Construction, "a skinned ring has no vertex"))?;
    let anchor1 = ogeom_algo::edge_vertices(model, &ring1)?
        .map(|(a, _)| a)
        .ok_or_else(|| ogeom_core::ogeom_err!(Construction, "a skinned ring has no vertex"))?;
    let seam = make_edge_between(model, seam_curve, v_dom, &anchor0, &anchor1, tol)?.shape;

    // Pcurves: rows for the rings, both columns for the seam.
    let row_line = |v: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(0.0, v), ogeom_math::Direction2::X),
            u_dom.0 - 1.0,
            u_dom.1 + 1.0,
        )?
        .into())
    };
    let column_line = |u: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
            v_dom.0 - 1.0,
            v_dom.1 + 1.0,
        )?
        .into())
    };
    ogeom_algo::attach_pcurve(
        model,
        &ring0,
        row_line(v_dom.0)?,
        surface_id,
        ogeom_topo::Location::identity(),
        u_dom,
    )?;
    ogeom_algo::attach_pcurve(
        model,
        &ring1,
        row_line(v_dom.1)?,
        surface_id,
        ogeom_topo::Location::identity(),
        u_dom,
    )?;
    ogeom_algo::attach_seam(
        model,
        &seam,
        column_line(u_dom.0)?,
        column_line(u_dom.1)?,
        surface_id,
        ogeom_topo::Location::identity(),
        v_dom,
    )?;

    let wall = {
        let wire = ogeom_algo::make_wire(
            model,
            &[
                ring0.clone(),
                seam.clone(),
                ring1.reversed(),
                seam.reversed(),
            ],
            tol,
        )?
        .shape;
        let face =
            ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape;
        // Outward by measurement at the middle of the skin: away from the
        // centre of the section the point lies on. The centre of the whole
        // skin will not do: along a bent spine it lies inside the bend,
        // on the far side of the inner wall.
        let mid_u = f64::midpoint(u_dom.0, u_dom.1);
        let mid_v = f64::midpoint(v_dom.0, v_dom.1);
        let s_mid = surface_geo.point_at(mid_u, mid_v, tol)?;
        let (du, dv) = surface_geo.d1_at(mid_u, mid_v, tol)?;
        if du.cross(dv).dot(s_mid - section_centre(rows, s_mid)) >= 0.0 {
            face
        } else {
            face.reversed()
        }
    };
    Ok(SkinnedWall {
        face: wall,
        ring0,
        ring1,
        curve0,
        curve1,
        u_dom,
    })
}

/// The centre of the section (row) passing nearest `at`: the mean of its
/// points.
fn section_centre(rows: &[Vec<Point>], at: Point) -> Point {
    let nearest = rows.iter().filter(|row| !row.is_empty()).min_by(|a, b| {
        let d = |row: &Vec<Point>| {
            row.iter()
                .map(|p| p.distance(at))
                .fold(f64::INFINITY, f64::min)
        };
        d(a).total_cmp(&d(b))
    });
    let Some(row) = nearest else {
        return at;
    };
    let sum = row
        .iter()
        .fold(Vector::new(0.0, 0.0, 0.0), |acc, p| acc + p.to_vector());
    #[allow(clippy::cast_precision_loss)]
    Point::from_vector(sum / row.len() as f64)
}

/// A strip closed the *long* way: open across its own width, a smooth loop
/// along the sweep: one face of a faceted ring, [`skinned_wall`]'s
/// construction with the chart's roles swapped and the loop made C1 by
/// [`ogeom_geom::fit::fit_surface_grid_closed_v`]. The rails are the two
/// closed border loops; the seam is one station's column, used twice.
fn skinned_ring_strip(
    model: &mut Model,
    skin: &Skin<'_>,
    outward_hint: Point,
    shared: [Option<&Shape>; 2],
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<(Shape, Shape, Shape)> {
    use ogeom_geom::Surface as _;
    // The loop: first row repeated at the end, as the closed fit demands.
    let fitted = skin.fit(true, tolerance, tol)?;
    if !fitted.met {
        ogeom_bail!(
            NotDone,
            "the ring strip reached {} against a target of {tolerance}",
            fitted.error
        );
    }
    let surface = fitted.curve;
    let (u_knots, v_knots) = (surface.u_knots().clone(), surface.v_knots().clone());
    let (k, l, net) = {
        let grid = surface.grid();
        let net: Vec<Point> = grid.points().iter().map(|w| (*w).point()).collect();
        (grid.u_count(), grid.v_count(), net)
    };
    let point_at = |i: usize, j: usize| -> Point { net[i * l + j] };
    let (u_dom, v_dom) = surface.domain();

    // The chart's roles, straight: `u` runs across the strip (open), `v`
    // around the loop (closed). The rails are v-curves (the closed border
    // loops at the two u-borders), and the seam is the u-row at the loop's
    // join, bounding the chart twice as every seam does.
    let rail_curve = |i: usize| -> OgeomResult<ogeom_geom::Curve> {
        let control: Vec<Point> = (0..l).map(|j| point_at(i, j)).collect();
        Ok(ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            v_knots.clone(),
            control,
            tol,
        )?))
    };
    let seam_curve = {
        let control: Vec<Point> = (0..k).map(|i| point_at(i, 0)).collect();
        ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            u_knots.clone(),
            control,
            tol,
        )?)
    };
    let surface_geo: SurfaceGeometry = surface.into();
    let surface_id = model.geometry_mut().add_surface(surface_geo.clone());

    // A corner loop shared with the neighbouring strip is one edge for
    // both: the neighbour built it from its own fit, and this strip's
    // border is another fit of the same loop, so the edge widens to how
    // far it honestly sits from this surface. Two independent fits of one
    // loop can disagree by more than either fit's own error (the sew refuses
    // that gap under a frame that turns fast), and one edge cannot disagree
    // with itself.
    let slack = fitted.error + tol.confusion();
    let rail_of = |model: &mut Model, i: usize, given: Option<&Shape>| -> OgeomResult<Shape> {
        let Some(edge) = given else {
            let edge = make_edge(model, rail_curve(i)?, v_dom, tol)?.shape;
            model.widen(&edge, ogeom_core::Tolerance::new(slack)?)?;
            return Ok(edge);
        };
        let (curve, range) = spine_curve_of(model, edge)?;
        let mut off: f64 = 0.0;
        for step in 0..=32 {
            #[allow(clippy::cast_precision_loss)]
            let t = range.0 + (range.1 - range.0) * (step as f64) / 32.0;
            let p = curve.point_at(t, tol)?;
            off = off.max(ogeom_algo::project_on_surface(&surface_geo, p, 16, tol)?.distance);
        }
        model.widen(edge, ogeom_core::Tolerance::new(off + slack)?)?;
        if let Some((a, b)) = ogeom_algo::edge_vertices(model, edge)? {
            for v in [&a, &b] {
                model.widen(v, ogeom_core::Tolerance::new(off + slack)?)?;
            }
        }
        Ok(edge.clone())
    };
    let rail0 = rail_of(model, 0, shared[0])?;
    let rail1 = rail_of(model, k - 1, shared[1])?;
    let anchor0 = ogeom_algo::edge_vertices(model, &rail0)?
        .map(|(a, _)| a)
        .ok_or_else(|| ogeom_core::ogeom_err!(Construction, "a strip rail has no vertex"))?;
    let anchor1 = ogeom_algo::edge_vertices(model, &rail1)?
        .map(|(a, _)| a)
        .ok_or_else(|| ogeom_core::ogeom_err!(Construction, "a strip rail has no vertex"))?;
    let seam = make_edge_between(model, seam_curve, u_dom, &anchor0, &anchor1, tol)?.shape;

    let row_line = |v: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(0.0, v), ogeom_math::Direction2::X),
            u_dom.0 - 1.0,
            u_dom.1 + 1.0,
        )?
        .into())
    };
    let column_line = |u: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
            v_dom.0 - 1.0,
            v_dom.1 + 1.0,
        )?
        .into())
    };
    ogeom_algo::attach_pcurve(
        model,
        &rail0,
        column_line(u_dom.0)?,
        surface_id,
        ogeom_topo::Location::identity(),
        v_dom,
    )?;
    ogeom_algo::attach_pcurve(
        model,
        &rail1,
        column_line(u_dom.1)?,
        surface_id,
        ogeom_topo::Location::identity(),
        v_dom,
    )?;
    ogeom_algo::attach_seam(
        model,
        &seam,
        row_line(v_dom.0)?,
        row_line(v_dom.1)?,
        surface_id,
        ogeom_topo::Location::identity(),
        u_dom,
    )?;
    let wire = ogeom_algo::make_wire(
        model,
        &[
            rail0.clone(),
            seam.clone(),
            rail1.reversed(),
            seam.reversed(),
        ],
        tol,
    )?
    .shape;
    let face = ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape;
    let mid_u = f64::midpoint(u_dom.0, u_dom.1);
    let mid_v = f64::midpoint(v_dom.0, v_dom.1);
    let s_mid = surface_geo.point_at(mid_u, mid_v, tol)?;
    let (du, dv) = surface_geo.d1_at(mid_u, mid_v, tol)?;
    let face = if du.cross(dv).dot(s_mid - outward_hint) >= 0.0 {
        face
    } else {
        face.reversed()
    };
    Ok((face, rail0, rail1))
}

/// A border edge the neighbouring skin built from its own fit, adopted by
/// this skin: the edge widens to how far it honestly sits from `surface`
/// plus this fit's own slack, its vertices with it. Two independent fits of
/// one row can disagree by more than either fit's own error, and one edge
/// cannot disagree with itself.
fn adopt_border(
    model: &mut Model,
    edge: &Shape,
    surface: &SurfaceGeometry,
    slack: f64,
    tol: Tolerances,
) -> OgeomResult<()> {
    let (curve, range) = spine_curve_of(model, edge)?;
    let mut off: f64 = 0.0;
    for step in 0..=32 {
        #[allow(clippy::cast_precision_loss)]
        let t = range.0 + (range.1 - range.0) * (step as f64) / 32.0;
        let p = curve.point_at(t, tol)?;
        off = off.max(ogeom_algo::project_on_surface(surface, p, 16, tol)?.distance);
    }
    model.widen(edge, ogeom_core::Tolerance::new(off + slack)?)?;
    if let Some((a, b)) = ogeom_algo::edge_vertices(model, edge)? {
        for v in [&a, &b] {
            model.widen(v, ogeom_core::Tolerance::new(off + slack)?)?;
        }
    }
    Ok(())
}

/// An adopted border's image on a surface it was not fitted on: the
/// border's own points, each read off the surface at its nearest point,
/// fitted at the border's own parameters so the image is same-parameter
/// with it. Returned with the parameter range it spans and how far the
/// surface at the image stands from the border, measured between the
/// samples as well as at them.
fn adopted_image(
    model: &Model,
    edge: &Shape,
    surface: &SurfaceGeometry,
    tol: Tolerances,
) -> OgeomResult<(ogeom_geom::PlanarCurve, (f64, f64), f64)> {
    const SAMPLES: u32 = 64;
    let (curve, range) = spine_curve_of(model, edge)?;
    let mut params = Vec::with_capacity(SAMPLES as usize + 1);
    let mut image = Vec::with_capacity(SAMPLES as usize + 1);
    let mut guess: Option<(f64, f64)> = None;
    for step in 0..=SAMPLES {
        let t = range.0 + (range.1 - range.0) * f64::from(step) / f64::from(SAMPLES);
        let p = curve.point_at(t, tol)?;
        let foot = match guess {
            Some(g) => ogeom_algo::project_on_surface_from(surface, p, g, tol)?,
            None => ogeom_algo::project_on_surface(surface, p, 16, tol)?,
        };
        guess = Some(foot.parameters);
        params.push(t);
        image.push(Point2::new(foot.parameters.0, foot.parameters.1));
    }
    use ogeom_geom::Surface as _;
    let fitted = ogeom_geom::fit::fit_points_2d_at(&params, &image, 3, tol.confusion(), tol)?;
    let mut off = 0.0_f64;
    for step in 0..=SAMPLES * 4 {
        let t = range.0 + (range.1 - range.0) * f64::from(step) / f64::from(SAMPLES * 4);
        let at = ogeom_geom::Curve2d::point_at(&fitted.curve, t, tol)?;
        // A border image runs along the chart's edge, and rounding may set
        // it a hair outside; the surface is read at the edge there.
        let ((u0, u1), (v0, v1)) = surface.domain();
        let at = Point2::new(at.x.clamp(u0, u1), at.y.clamp(v0, v1));
        off = off.max(
            surface
                .point_at(at.x, at.y, tol)?
                .distance(curve.point_at(t, tol)?),
        );
    }
    Ok((fitted.curve.into(), range, off))
}

/// A solid skinned over a grid of section samples: [`skinned_wall`] with a
/// planar cap over each end ring.
/// How a skinned solid's end is closed.
#[derive(Debug, Clone, Copy)]
enum EndCap {
    /// The section is planar: a plane face, its normal pointing out.
    Plane(Vector),
    /// The section is not: a patch skinned from the ring down to a point
    /// inside it, sharing the wall's ring edge.
    Skinned,
}

fn skinned_solid(
    model: &mut Model,
    skin: &Skin<'_>,
    caps: (EndCap, EndCap),
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    let wall = skinned_wall(model, skin, (None, None), tolerance, tol)?;
    let rows = &skin.rows;
    let u_dom = wall.u_dom;

    let cap = |model: &mut Model,
               ring: &Shape,
               curve: ogeom_geom::Curve,
               outward: Vector|
     -> OgeomResult<Shape> {
        let at = curve.point_at(u_dom.0, tol)?;
        let plane = Plane::through(at, Direction::new(outward, tol)?);
        let mut reach = 1.0_f64;
        for t in 0..8 {
            let p = curve.point_at(u_dom.0 + (u_dom.1 - u_dom.0) * f64::from(t) / 8.0, tol)?;
            reach = reach.max(p.distance(at) * 2.0);
        }
        let cap_surface: SurfaceGeometry =
            PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?.into();
        let walked = walked_about(model, std::slice::from_ref(ring), outward, true, tol)?;
        let wire = ogeom_algo::make_wire(model, &walked, tol)?.shape;
        let face =
            ogeom_algo::make_face(model, cap_surface.clone(), std::slice::from_ref(&wire), tol)?
                .shape;
        let id = {
            let Some(node) = model.node(&face) else {
                ogeom_bail!(Dangling, "the cap just built is not in this model");
            };
            let ogeom_topo::NodeData::Face(data) = node.data() else {
                ogeom_bail!(Construction, "the cap holds no face data");
            };
            data.surface
        };
        let Some(pcurve) = ogeom_intersect::exact_pcurve_of(&curve, &cap_surface, tol) else {
            ogeom_bail!(Construction, "a cap edge has no closed-form pcurve");
        };
        ogeom_algo::attach_pcurve(
            model,
            ring,
            pcurve,
            id,
            ogeom_topo::Location::identity(),
            u_dom,
        )?;
        Ok(face)
    };
    let close = |model: &mut Model,
                 end: EndCap,
                 ring: &Shape,
                 curve: &ogeom_geom::Curve,
                 row: &[Point],
                 last: bool| {
        match end {
            EndCap::Plane(outward) => cap(model, ring, curve.clone(), outward),
            EndCap::Skinned => {
                // The cone from the section to the point its rows collapse
                // to (the section's own centroid, which a closed section
                // winds round): the ring, a row halfway in, and the point.
                let apex = centroid_of(std::slice::from_ref(&row.to_vec()));
                let patch = match &skin.traced {
                    // Known between the samples where the skin knows its
                    // end section there, and checked there too.
                    Some(traced) => {
                        let vs = &traced.sampling.vs;
                        let at = if last { vs[vs.len() - 1] } else { vs[0] };
                        Skin::swept(
                            move |f, s| {
                                let p = (traced.point)(f, at)?;
                                Ok(apex + (p - apex) * (1.0 - s * 0.5))
                            },
                            traced.sampling.us.clone(),
                            (0, 2),
                            skin.round,
                        )?
                    }
                    None => {
                        let half: Vec<Point> = row
                            .iter()
                            .map(|p| Point::from_vector((p.to_vector() + apex.to_vector()) * 0.5))
                            .collect();
                        Skin::rows(vec![row.to_vec(), half, vec![apex; row.len()]])
                    }
                };
                // Inside the solid behind the cap: the middle of the next
                // section in.
                let next = if last {
                    &rows[rows.len() - 2]
                } else {
                    &rows[1]
                };
                let inside = centroid_of(std::slice::from_ref(next));
                Ok(apex_patch(model, &patch, Some(ring), Some(inside), tolerance, tol)?.0)
            }
        }
    };
    let cap0 = close(model, caps.0, &wall.ring0, &wall.curve0, &rows[0], false)?;
    let cap1 = close(
        model,
        caps.1,
        &wall.ring1,
        &wall.curve1,
        &rows[rows.len() - 1],
        true,
    )?;

    let faces = [wall.face, cap0, cap1];
    let sewn = sew(model, &faces, tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the skinned solid did not close");
    }
    make_solid(model, std::slice::from_ref(&sewn.shells[0]))
}

/// A patch skinned from a ring down to a point: [`skinned_wall`]'s
/// construction with the top ring replaced by the apex: a degenerate
/// edge on one vertex, bounding the chart's whole top row the way a cone's
/// apex bounds a countersink. The ring edge is adopted from `shared`
/// where a neighbour already built it, and the face is turned to point
/// away from `inside` where given (a point within the solid behind the
/// patch), from the section it passes through otherwise. Returns the face
/// and its ring edge.
fn apex_patch(
    model: &mut Model,
    skin: &Skin<'_>,
    shared: Option<&Shape>,
    inside: Option<Point>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<(Shape, Shape)> {
    use ogeom_geom::Surface as _;
    let rows = &skin.rows;
    let fitted = skin.fit(false, tolerance, tol)?;
    if !fitted.met {
        ogeom_bail!(
            NotDone,
            "the skin reached {} against a target of {tolerance}",
            fitted.error
        );
    }
    let surface = fitted.curve;
    let (u_knots, v_knots) = (surface.u_knots().clone(), surface.v_knots().clone());
    let (k, l, net) = {
        let grid = surface.grid();
        let net: Vec<Point> = grid.points().iter().map(|w| (*w).point()).collect();
        (grid.u_count(), grid.v_count(), net)
    };
    let point_at = |i: usize, j: usize| -> Point { net[i * l + j] };
    let (u_dom, v_dom) = surface.domain();
    let apex = rows[rows.len() - 1][0];

    let ring_curve = {
        let control: Vec<Point> = (0..k).map(|i| point_at(i, 0)).collect();
        ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            u_knots.clone(),
            control,
            tol,
        )?)
    };
    let seam_curve = {
        let control: Vec<Point> = (0..l).map(|j| point_at(0, j)).collect();
        ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            v_knots.clone(),
            control,
            tol,
        )?)
    };
    let surface_geo: SurfaceGeometry = surface.into();
    let surface_id = model.geometry_mut().add_surface(surface_geo.clone());

    // The ring a neighbour built is adopted, not refitted (see `adopt_border`).
    let ring0 = match shared {
        Some(edge) => {
            adopt_border(
                model,
                edge,
                &surface_geo,
                fitted.error + tol.confusion(),
                tol,
            )?;
            edge.clone()
        }
        None => make_edge(model, ring_curve.clone(), u_dom, tol)?.shape,
    };
    let anchor0 = ogeom_algo::edge_vertices(model, &ring0)?
        .map(|(a, _)| a)
        .ok_or_else(|| ogeom_core::ogeom_err!(Construction, "a skinned ring has no vertex"))?;
    let apex_vertex = model.add_vertex(VertexData::new(apex));
    let apex_edge = {
        let mut data = EdgeData::new();
        data.degenerate = true;
        model.add_edge(data, &[apex_vertex.clone(), apex_vertex.clone()])?
    };
    let seam = make_edge_between(model, seam_curve, v_dom, &anchor0, &apex_vertex, tol)?.shape;

    let row_line = |v: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(0.0, v), ogeom_math::Direction2::X),
            u_dom.0 - 1.0,
            u_dom.1 + 1.0,
        )?
        .into())
    };
    let column_line = |u: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
            v_dom.0 - 1.0,
            v_dom.1 + 1.0,
        )?
        .into())
    };
    ogeom_algo::attach_pcurve(
        model,
        &ring0,
        row_line(v_dom.0)?,
        surface_id,
        ogeom_topo::Location::identity(),
        u_dom,
    )?;
    // The apex bounds the chart's whole top row while covering no distance:
    // the degenerate edge carries the row's pcurve, exactly as a cone's apex
    // does after the reader synthesises it.
    ogeom_algo::attach_pcurve(
        model,
        &apex_edge,
        row_line(v_dom.1)?,
        surface_id,
        ogeom_topo::Location::identity(),
        u_dom,
    )?;
    ogeom_algo::attach_seam(
        model,
        &seam,
        column_line(u_dom.0)?,
        column_line(u_dom.1)?,
        surface_id,
        ogeom_topo::Location::identity(),
        v_dom,
    )?;

    let wire = ogeom_algo::make_wire(
        model,
        &[
            ring0.clone(),
            seam.clone(),
            apex_edge.reversed(),
            seam.reversed(),
        ],
        tol,
    )?
    .shape;
    let face = ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape;
    let mid_u = f64::midpoint(u_dom.0, u_dom.1);
    let mid_v = f64::midpoint(v_dom.0, v_dom.1);
    let s_mid = surface_geo.point_at(mid_u, mid_v, tol)?;
    let (du, dv) = surface_geo.d1_at(mid_u, mid_v, tol)?;
    // Without a point inside, inside is judged from the section the patch
    // passes through at that row, not from the whole skin's centroid: a
    // skin that bends puts that centroid outside itself, in the crook of
    // the bend. A patch spanning a section (a cap) has its normal square to
    // the way out from that section's middle, and is told where inside is.
    let local = match inside {
        Some(at) => at,
        None => {
            let mut sum = Vector::ZERO;
            for k in 0..16 {
                let u = u_dom.0 + (u_dom.1 - u_dom.0) * f64::from(k) / 16.0;
                sum += surface_geo.point_at(u, mid_v, tol)?.to_vector();
            }
            Point::from_vector(sum / 16.0)
        }
    };
    let face = if du.cross(dv).dot(s_mid - local) >= 0.0 {
        face
    } else {
        face.reversed()
    };
    Ok((face, ring0))
}

/// The mean of every point in every row.
fn centroid_of(rows: &[Vec<Point>]) -> Point {
    let mut c = Vector::new(0.0, 0.0, 0.0);
    let mut n = 0.0;
    for row in rows {
        for p in row {
            c += p.to_vector();
            n += 1.0;
        }
    }
    Point::from_vector(c / n)
}

/// A solid skinned down to a point: [`apex_patch`] for the wall, and one
/// cap at the open end; the apex end closes by construction.
fn skinned_solid_to_apex(
    model: &mut Model,
    skin: &Skin<'_>,
    cap_outward: Vector,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    use ogeom_geom::Curve3d as _;
    let (wall, ring0) = apex_patch(model, skin, None, None, tolerance, tol)?;
    let (ring_curve, u_dom) = {
        let (curve, range) = spine_curve_of(model, &ring0)?;
        (curve, range)
    };

    // One cap, on the open end; the machinery is skinned_solid's, inlined
    // for the single ring.
    let cap = {
        let at = ring_curve.point_at(u_dom.0, tol)?;
        let plane = Plane::through(at, Direction::new(cap_outward, tol)?);
        let mut reach = 1.0_f64;
        for t in 0..8 {
            let p = ring_curve.point_at(u_dom.0 + (u_dom.1 - u_dom.0) * f64::from(t) / 8.0, tol)?;
            reach = reach.max(p.distance(at) * 2.0);
        }
        let cap_surface: SurfaceGeometry =
            PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?.into();
        let walked = walked_about(model, std::slice::from_ref(&ring0), cap_outward, true, tol)?;
        let wire = ogeom_algo::make_wire(model, &walked, tol)?.shape;
        let face =
            ogeom_algo::make_face(model, cap_surface.clone(), std::slice::from_ref(&wire), tol)?
                .shape;
        let id = {
            let Some(node) = model.node(&face) else {
                ogeom_bail!(Dangling, "the cap just built is not in this model");
            };
            let ogeom_topo::NodeData::Face(data) = node.data() else {
                ogeom_bail!(Construction, "the cap holds no face data");
            };
            data.surface
        };
        let Some(pcurve) = ogeom_intersect::exact_pcurve_of(&ring_curve, &cap_surface, tol) else {
            ogeom_bail!(Construction, "a cap edge has no closed-form pcurve");
        };
        ogeom_algo::attach_pcurve(
            model,
            &ring0,
            pcurve,
            id,
            ogeom_topo::Location::identity(),
            u_dom,
        )?;
        face
    };

    let faces = [wall, cap];
    let sewn = sew(model, &faces, tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the skinned apex solid did not close");
    }
    make_solid(model, std::slice::from_ref(&sewn.shells[0]))
}

/// A solid skinned over a grid of sections that loops back on itself: the
/// wall is one face closed in both chart directions, no caps at all.
///
/// The `u` seam closes the way every skin's does (pinned row ends), and
/// the `v` loop closes through [`ogeom_geom::fit::fit_surface_grid_closed_v`],
/// C1 across the join. All four boundary traversals are two seam edges used
/// twice, anchored at one shared vertex, exactly as a torus bounds itself.
fn closed_skinned_solid(
    model: &mut Model,
    skin: &Skin<'_>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    let shell = closed_skinned_shell(model, skin, tolerance, tol)?;
    make_solid(model, std::slice::from_ref(&shell))
}

/// The closed skin as a shell, for callers assembling solids with voids;
/// a holed profile's ring is one outer shell and one per tunnel.
fn closed_skinned_shell(
    model: &mut Model,
    skin: &Skin<'_>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    use ogeom_geom::Surface as _;
    let rows = &skin.rows;
    let fitted = skin.fit(true, tolerance, tol)?;
    if !fitted.met {
        ogeom_bail!(
            NotDone,
            "the closed skin reached {} against a target of {tolerance}",
            fitted.error
        );
    }
    let surface = fitted.curve;
    let (u_knots, v_knots) = (surface.u_knots().clone(), surface.v_knots().clone());
    let (k, l, net) = {
        let grid = surface.grid();
        let net: Vec<Point> = grid.points().iter().map(|w| (*w).point()).collect();
        (grid.u_count(), grid.v_count(), net)
    };
    let point_at = |i: usize, j: usize| -> Point { net[i * l + j] };
    let (u_dom, v_dom) = surface.domain();

    // Both seams straight off the net: the u-run at v's join, and the v-run
    // at u's.
    let along_u = {
        let control: Vec<Point> = (0..k).map(|i| point_at(i, 0)).collect();
        ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(u_knots, control, tol)?)
    };
    let along_v = {
        let control: Vec<Point> = (0..l).map(|j| point_at(0, j)).collect();
        ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(v_knots, control, tol)?)
    };
    let surface_geo: SurfaceGeometry = surface.into();
    let surface_id = model.geometry_mut().add_surface(surface_geo.clone());

    let u_edge = make_edge(model, along_u, u_dom, tol)?.shape;
    let Some((corner, _)) = ogeom_algo::edge_vertices(model, &u_edge)? else {
        ogeom_bail!(Construction, "the closed skin's seam has no vertex");
    };
    let v_edge = make_edge_between(model, along_v, v_dom, &corner, &corner, tol)?.shape;

    let row_line = |v: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(0.0, v), ogeom_math::Direction2::X),
            u_dom.0 - 1.0,
            u_dom.1 + 1.0,
        )?
        .into())
    };
    let column_line = |u: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
            v_dom.0 - 1.0,
            v_dom.1 + 1.0,
        )?
        .into())
    };
    // The u-run is a seam in v (the same curve at both rows), and the
    // v-run a seam in u.
    ogeom_algo::attach_seam(
        model,
        &u_edge,
        row_line(v_dom.0)?,
        row_line(v_dom.1)?,
        surface_id,
        ogeom_topo::Location::identity(),
        u_dom,
    )?;
    ogeom_algo::attach_seam(
        model,
        &v_edge,
        column_line(u_dom.1)?,
        column_line(u_dom.0)?,
        surface_id,
        ogeom_topo::Location::identity(),
        v_dom,
    )?;

    let wire = ogeom_algo::make_wire(
        model,
        &[
            u_edge.clone(),
            v_edge.clone(),
            u_edge.reversed(),
            v_edge.reversed(),
        ],
        tol,
    )?
    .shape;
    let face = ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape;
    // Away from the centre of the section the point lies on; a closed
    // skin's centre as a whole sits in its hole.
    let mid_u = f64::midpoint(u_dom.0, u_dom.1);
    let mid_v = f64::midpoint(v_dom.0, v_dom.1);
    let s_mid = surface_geo.point_at(mid_u, mid_v, tol)?;
    let (du, dv) = surface_geo.d1_at(mid_u, mid_v, tol)?;
    let face = if du.cross(dv).dot(s_mid - section_centre(rows, s_mid)) >= 0.0 {
        face
    } else {
        face.reversed()
    };

    let sewn = sew(model, std::slice::from_ref(&face), tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the closed skin did not close");
    }
    Ok(sewn.shells[0].clone())
}

/// The loft to a point: a wire section closing onto a single apex vertex.
///
/// A circle takes the cone the revolved primitives already build, apex on
/// its axis or refused; a polygon takes exact planar triangle walls, sound
/// for *any* apex: a skew pyramid's walls are still triangles.
fn loft_to_point(
    model: &mut Model,
    section: &Shape,
    apex: &Shape,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if !ogeom_algo::is_wire_closed(model, section, tol)? {
        ogeom_bail!(Construction, "a loft section must be closed");
    }
    let apex_point = {
        let Some(data) = model.node(apex).and_then(|n| n.data().as_vertex()) else {
            ogeom_bail!(Construction, "the apex vertex holds no data");
        };
        data.point
    };

    // The circular case: a cone, apex on the axis.
    let edges = explore(model, section, Filter::OfType(ShapeType::Edge))?;
    if edges.len() == 1
        && let Some(data) = model.node(&edges[0]).and_then(|n| n.data().as_edge())
        && let Some(EdgeRepr::Curve3d { curve, .. }) = data.curve3d()
        && let Some(Curve::Circle(c)) = model.geometry().curve(*curve)
    {
        let circle = c.circle();
        let axis = circle.frame().z().vector();
        let rise = apex_point - circle.centre();
        let height = rise.dot(axis);
        if rise.cross(axis).magnitude() > tol.confusion() * 10.0 {
            ogeom_bail!(
                Construction,
                "a circle lofts to a point on its own axis; the oblique cone \
                 needs the skinned machinery; see docs/PARITY.md, offset.loft"
            );
        }
        if height.abs() <= tol.confusion() {
            ogeom_bail!(Construction, "the apex sits in the section's own plane");
        }
        let base = if height > 0.0 {
            circle.frame()
        } else {
            Frame::new(
                circle.centre(),
                -circle.frame().z(),
                circle.frame().x(),
                tol,
            )?
        };
        let mut built =
            ogeom_algo::make_cone(model, base, circle.radius(), 0.0, height.abs(), tol)?;
        built.history.generate(section, built.shape.clone());
        built.history.generate(apex, built.shape.clone());
        return Ok(built);
    }

    // The polygonal case: exact triangle walls to a shared apex.
    let mut corners: Vec<Point> = Vec::new();
    for edge in model.ordered_children_of(section)? {
        let Some(data) = model.node(&edge).and_then(|n| n.data().as_edge()) else {
            ogeom_bail!(Construction, "a section edge holds no data");
        };
        let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
            ogeom_bail!(Construction, "a section edge has no curve");
        };
        let Some(Curve::Line(line)) = model.geometry().curve(*curve).cloned() else {
            ogeom_bail!(
                Construction,
                "a mixed or curved section lofts to a point through the \
                 skinned machinery; see docs/PARITY.md, offset.loft"
            );
        };
        let t = if edge.orientation() == ogeom_topo::Orientation::Reversed {
            range.1
        } else {
            range.0
        };
        corners.push(ogeom_geom::Curve::Line(line).point_at(t, tol)?);
    }
    if corners.len() < 3 {
        ogeom_bail!(Construction, "a pyramid needs at least three base corners");
    }
    let apex_vertex = ogeom_algo::make_vertex(model, apex_point).shape;
    let base_vertices: Vec<Shape> = corners
        .iter()
        .map(|p| ogeom_algo::make_vertex(model, *p).shape)
        .collect();
    let segment =
        |model: &mut Model, from: (&Shape, Point), to: (&Shape, Point)| -> OgeomResult<Shape> {
            let line = ogeom_geom::LineCurve::segment(from.1, to.1, tol)?;
            let curve: Curve = line.into();
            let domain = curve.domain();
            Ok(make_edge_between(model, curve, domain, from.0, to.0, tol)?.shape)
        };
    let count = corners.len();
    let mut base_edges = Vec::with_capacity(count);
    let mut rails = Vec::with_capacity(count);
    for i in 0..count {
        let next = (i + 1) % count;
        base_edges.push(segment(
            model,
            (&base_vertices[i], corners[i]),
            (&base_vertices[next], corners[next]),
        )?);
        rails.push(segment(
            model,
            (&base_vertices[i], corners[i]),
            (&apex_vertex, apex_point),
        )?);
    }
    let centroid = {
        let mut c = Vector::new(0.0, 0.0, 0.0);
        for p in &corners {
            c += p.to_vector();
        }
        #[allow(clippy::cast_precision_loss)]
        Point::from_vector(c / count as f64 / 4.0 * 3.0 + apex_point.to_vector() / 4.0)
    };
    let planar = |model: &mut Model, pts: [Point; 3], walk: Vec<Shape>| -> OgeomResult<Shape> {
        let n = (pts[1] - pts[0]).cross(pts[2] - pts[0]);
        let m = n.magnitude();
        if m <= tol.confusion() {
            ogeom_bail!(Construction, "a wall of the pyramid is degenerate");
        }
        let mut outward = n / m;
        if outward.dot(pts[0] - centroid) < 0.0 {
            outward = -outward;
        }
        let plane = ogeom_math::Plane::through(pts[0], Direction::new(outward, tol)?);
        let mut reach = 1.0_f64;
        for p in pts {
            reach = reach.max(p.distance(pts[0]) * 2.0);
        }
        let surface: SurfaceGeometry =
            PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?.into();
        let id = model.geometry_mut().add_surface(surface.clone());
        let signed = {
            let (du, dv) = {
                use ogeom_geom::Surface as _;
                surface.d1_at(0.0, 0.0, tol)?
            };
            du.cross(dv).dot(outward) >= 0.0
        };
        let mut wired = Vec::with_capacity(walk.len());
        for used in &walk {
            let (curve, range) = spine_curve_of(model, used)?;
            let Some(pcurve) = ogeom_intersect::exact_pcurve_of(&curve, &surface, tol) else {
                ogeom_bail!(Construction, "a wall edge has no closed-form pcurve");
            };
            ogeom_algo::attach_pcurve(
                model,
                used,
                pcurve,
                id,
                ogeom_topo::Location::identity(),
                range,
            )?;
            wired.push(used.clone());
        }
        let wire = ogeom_algo::make_wire(model, &wired, tol)?.shape;
        let face = ogeom_algo::make_face_on(model, id, std::slice::from_ref(&wire), tol)?.shape;
        Ok(if signed { face } else { face.reversed() })
    };
    let mut faces = Vec::with_capacity(count + 1);
    for i in 0..count {
        let next = (i + 1) % count;
        faces.push(planar(
            model,
            [corners[i], corners[next], apex_point],
            vec![
                base_edges[i].clone(),
                rails[next].clone(),
                rails[i].reversed(),
            ],
        )?);
    }
    // The base cap: all corners, wound against the walls.
    let base_walk: Vec<Shape> = (0..count).rev().map(|i| base_edges[i].reversed()).collect();
    faces.push({
        let n = (corners[1] - corners[0]).cross(corners[2] - corners[0]);
        let mut outward = n / n.magnitude();
        if outward.dot(corners[0] - centroid) < 0.0 {
            outward = -outward;
        }
        let plane = ogeom_math::Plane::through(corners[0], Direction::new(outward, tol)?);
        let mut reach = 1.0_f64;
        for p in &corners {
            reach = reach.max(p.distance(corners[0]) * 2.0);
        }
        let surface: SurfaceGeometry =
            PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?.into();
        let id = model.geometry_mut().add_surface(surface.clone());
        for used in &base_walk {
            let (curve, range) = spine_curve_of(model, used)?;
            let Some(pcurve) = ogeom_intersect::exact_pcurve_of(&curve, &surface, tol) else {
                ogeom_bail!(Construction, "a base edge has no closed-form pcurve");
            };
            ogeom_algo::attach_pcurve(
                model,
                used,
                pcurve,
                id,
                ogeom_topo::Location::identity(),
                range,
            )?;
        }
        let wire = ogeom_algo::make_wire(model, &base_walk, tol)?.shape;
        let face = ogeom_algo::make_face_on(model, id, std::slice::from_ref(&wire), tol)?.shape;
        let signed = {
            use ogeom_geom::Surface as _;
            let (du, dv) = surface.d1_at(0.0, 0.0, tol)?;
            du.cross(dv).dot(outward) >= 0.0
        };
        if signed { face } else { face.reversed() }
    });

    let sewn = sew(model, &faces, tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the pyramid did not close");
    }
    let mut built = make_solid(model, std::slice::from_ref(&sewn.shells[0]))?;
    built.history.generate(section, built.shape.clone());
    built.history.generate(apex, built.shape.clone());
    Ok(built)
}

/// Loft through sections with the start of each row named by the caller.
///
/// [`make_loft_skinned`] leaves alignment to each section's own traversal
/// start; this sibling takes one hint per section (a point near where its
/// row should begin) and rotates each sampling there, which is how a
/// caller untwists a loft whose wires happen to start in different places.
///
/// # Errors
///
/// As [`make_loft_skinned`], and additionally if the hints do not pair up
/// with the sections.
pub fn make_loft_skinned_aligned(
    model: &mut Model,
    sections: &[Shape],
    hints: &[Point],
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if hints.len() != sections.len() {
        ogeom_bail!(
            Construction,
            "{} hints against {} sections; each section names its own start",
            hints.len(),
            sections.len()
        );
    }
    if sections.len() < 2 {
        ogeom_bail!(Construction, "a loft needs at least two sections");
    }
    let mut loops: Vec<Section> = Vec::with_capacity(sections.len());
    let mut planes: Vec<Plane> = Vec::with_capacity(sections.len());
    for (wire, hint) in sections.iter().zip(hints) {
        if model.kind_of(wire)? != ShapeType::Wire {
            ogeom_bail!(Construction, "a loft section is a closed wire");
        }
        if !ogeom_algo::is_wire_closed(model, wire, tol)? {
            ogeom_bail!(Construction, "a loft section must be closed");
        }
        let Some(plane) = ogeom_algo::find_plane(model, wire, tol)? else {
            ogeom_bail!(Construction, "a loft section must be planar");
        };
        planes.push(plane);
        loops.push(Section::Loop(section_loop(model, wire, Some(*hint), tol)?));
    }
    let skin = Skin::sections(loops, false)?;
    let rows = &skin.rows;
    let outward0 = {
        let towards = rows[1][0] - rows[0][0];
        let n = planes[0].normal().vector();
        if n.dot(towards) > 0.0 { -n } else { n }
    };
    let outward1 = {
        let towards = rows[rows.len() - 2][0] - rows[rows.len() - 1][0];
        let n = planes[planes.len() - 1].normal().vector();
        if n.dot(towards) > 0.0 { -n } else { n }
    };
    let mut built = skinned_solid(
        model,
        &skin,
        (EndCap::Plane(outward0), EndCap::Plane(outward1)),
        tolerance,
        tol,
    )?;
    for section in sections {
        built.history.generate(section, built.shape.clone());
    }
    Ok(built)
}

/// Loft a ring through closed planar sections that loop back to the first.
///
/// [`make_loft_skinned`]'s closed sibling: the sections are sampled the same
/// way, the skin runs through all of them and back to the start, C1 across
/// the loop, and there are no caps: the result bounds itself the way a
/// torus does. The sections are *not* repeated: the loop-back is the
/// construction's own.
///
/// The closed join costs freedom: a sparse loop fits only loosely, and the
/// refusal quotes the deviation it honestly reached. A loop that wants a
/// tight tolerance wants sections dense enough to bend around: in
/// practice, a dozen and up.
///
/// # Errors
///
/// As [`make_loft_skinned`], needing at least three sections;
/// [`OgeomError::NotDone`](ogeom_core::OgeomError::NotDone) if the closed
/// skin cannot reach the tolerance.
pub fn make_loft_skinned_closed(
    model: &mut Model,
    sections: &[Shape],
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if sections.len() < 3 {
        ogeom_bail!(Construction, "a closed loft needs at least three sections");
    }
    let mut loops: Vec<Section> = Vec::with_capacity(sections.len());
    for wire in sections {
        if model.kind_of(wire)? != ShapeType::Wire {
            ogeom_bail!(Construction, "a loft section is a closed wire");
        }
        if !ogeom_algo::is_wire_closed(model, wire, tol)? {
            ogeom_bail!(Construction, "a loft section must be closed");
        }
        if ogeom_algo::find_plane(model, wire, tol)?.is_none() {
            ogeom_bail!(Construction, "a loft section must be planar");
        }
        loops.push(Section::Loop(section_loop(model, wire, None, tol)?));
    }
    let skin = Skin::sections(loops, true)?;
    let mut built = closed_skinned_solid(model, &skin, tolerance, tol)?;
    for section in sections {
        built.history.generate(section, built.shape.clone());
    }
    Ok(built)
}

/// A skinned strip: one open patch of a sweep, with its border edges.
///
/// The wall of a *faceted* profile cannot be one closed skin (a fit cannot
/// speak a corner), so each profile edge sweeps its own strip, cornered at
/// the caller's shared vertices, and the strips weld along their rails by
/// the tolerance the fit honestly carries.
struct SkinnedStrip {
    face: Shape,
    /// The border along the first station, from `corners.0` to `corners.1`.
    bottom: Shape,
    /// The border along the last station, from `corners.2` to `corners.3`.
    top: Shape,
    /// The rail along the profile edge's start, from `corners.0` to `corners.2`.
    rail0: Shape,
    /// The rail along the profile edge's end, from `corners.1` to `corners.3`.
    rail1: Shape,
}

/// Skin an open grid of samples (stations by profile-edge samples) into
/// one strip. `corners` are the caller's vertices at (first station, edge
/// start), (first, end), (last, start), (last, end), shared with the
/// neighbouring strips so the wires chain. `shared` are borders a
/// neighbouring strip already built (bottom, top, start rail, end rail),
/// adopted as they are (see `adopt_border`).
#[allow(clippy::too_many_arguments, reason = "one strip, spelled out")]
fn skinned_strip(
    model: &mut Model,
    skin: &Skin<'_>,
    corners: (&Shape, &Shape, &Shape, &Shape),
    shared: [Option<&Shape>; 4],
    outward_hint: Point,
    hole: bool,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<SkinnedStrip> {
    use ogeom_geom::Surface as _;
    let rows = &skin.rows;
    // A strip whose every row lies in one plane (a straight profile edge
    // down a straight run, a flat face of the profile along a planar
    // spine) is that plane, exactly: a coplanar neighbour then melts with
    // it on the one surface two fits of it would never agree on.
    if let Some(plane) = plane_of_rows(rows, tol) {
        return planar_strip(
            model,
            skin,
            plane,
            corners,
            shared,
            outward_hint,
            hole,
            tolerance,
            tol,
        );
    }
    // Sections a caller placed follow their own spacing across the skin;
    // stations a sweep placed keep the fit's centripetal assignment, or
    // their index where the sweep is known between them.
    let fitted = skin.fit(false, tolerance, tol)?;
    if !fitted.met {
        ogeom_bail!(
            NotDone,
            "the strip reached {} against a target of {tolerance}",
            fitted.error
        );
    }
    let error = fitted.error.max(tol.confusion());
    let surface = fitted.curve;
    let (u_knots, v_knots) = (surface.u_knots().clone(), surface.v_knots().clone());
    let (k, l, net) = {
        let grid = surface.grid();
        let net: Vec<Point> = grid.points().iter().map(|w| (*w).point()).collect();
        (grid.u_count(), grid.v_count(), net)
    };
    let point_at = |i: usize, j: usize| -> Point { net[i * l + j] };
    let (u_dom, v_dom) = surface.domain();

    let u_curve = |j: usize| -> OgeomResult<ogeom_geom::Curve> {
        let control: Vec<Point> = (0..k).map(|i| point_at(i, j)).collect();
        Ok(ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            u_knots.clone(),
            control,
            tol,
        )?))
    };
    let v_curve = |i: usize| -> OgeomResult<ogeom_geom::Curve> {
        let control: Vec<Point> = (0..l).map(|j| point_at(i, j)).collect();
        Ok(ogeom_geom::Curve::BSpline(ogeom_geom::BSplineCurve::new(
            v_knots.clone(),
            control,
            tol,
        )?))
    };
    let surface_geo: SurfaceGeometry = surface.into();
    let surface_id = model.geometry_mut().add_surface(surface_geo.clone());

    let (c00, c10, c01, c11) = corners;
    // A border the neighbouring strip already built is adopted, not
    // refitted (see `adopt_border`).
    let border = |model: &mut Model,
                  given: Option<&Shape>,
                  curve: ogeom_geom::Curve,
                  range: (f64, f64),
                  from: &Shape,
                  to: &Shape|
     -> OgeomResult<Shape> {
        match given {
            Some(edge) => {
                adopt_border(model, edge, &surface_geo, error + tol.confusion(), tol)?;
                Ok(edge.clone())
            }
            None => Ok(make_edge_between(model, curve, range, from, to, tol)?.shape),
        }
    };
    let bottom = border(model, shared[0], u_curve(0)?, u_dom, c00, c10)?;
    let top = border(model, shared[1], u_curve(l - 1)?, u_dom, c01, c11)?;
    let rail0 = border(model, shared[2], v_curve(0)?, v_dom, c00, c01)?;
    let rail1 = border(model, shared[3], v_curve(k - 1)?, v_dom, c10, c11)?;

    let row_line = |v: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(0.0, v), ogeom_math::Direction2::X),
            u_dom.0 - 1.0,
            u_dom.1 + 1.0,
        )?
        .into())
    };
    let column_line = |u: f64| -> OgeomResult<ogeom_geom::PlanarCurve> {
        Ok(Line2d::over(
            ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
            v_dom.0 - 1.0,
            v_dom.1 + 1.0,
        )?
        .into())
    };
    // A border this strip fitted runs along its own row or column, and its
    // image is that straight line. One adopted from the neighbour was fitted
    // at the neighbour's pace along the sweep, which is not this strip's:
    // its image here is read off this surface point by point.
    for (edge, given, straight, span) in [
        (&bottom, shared[0].is_some(), row_line(v_dom.0)?, u_dom),
        (&top, shared[1].is_some(), row_line(v_dom.1)?, u_dom),
        (&rail0, shared[2].is_some(), column_line(u_dom.0)?, v_dom),
        (&rail1, shared[3].is_some(), column_line(u_dom.1)?, v_dom),
    ] {
        let (image, range) = if given {
            let (image, range, off) = adopted_image(model, edge, &surface_geo, tol)?;
            // The image stands off the border by what it was measured at;
            // the edge and its ends carry that.
            if off > tol.confusion() {
                let held = ogeom_core::Tolerance::new(off)?;
                model.widen(edge, held)?;
                if let Some((a, b)) = ogeom_algo::edge_vertices(model, edge)? {
                    for v in [&a, &b] {
                        model.widen(v, held)?;
                    }
                }
            }
            (image, range)
        } else {
            (straight, span)
        };
        ogeom_algo::attach_pcurve(
            model,
            edge,
            image,
            surface_id,
            ogeom_topo::Location::identity(),
            range,
        )?;
    }
    // The rails carry the fit's honest budget: the neighbouring strip fitted
    // the same transported corners independently, and the weld between them
    // is only as tight as both fits.
    for edge in [&bottom, &top, &rail0, &rail1] {
        model.widen(edge, ogeom_core::Tolerance::new(error)?)?;
    }

    let wire = ogeom_algo::make_wire(
        model,
        &[
            bottom.clone(),
            rail1.clone(),
            top.reversed(),
            rail0.reversed(),
        ],
        tol,
    )?
    .shape;
    let face = ogeom_algo::make_face_on(model, surface_id, std::slice::from_ref(&wire), tol)?.shape;
    let mid_u = f64::midpoint(u_dom.0, u_dom.1);
    let mid_v = f64::midpoint(v_dom.0, v_dom.1);
    let s_mid = surface_geo.point_at(mid_u, mid_v, tol)?;
    let (du, dv) = surface_geo.d1_at(mid_u, mid_v, tol)?;
    let natural_out = du.cross(dv).dot(s_mid - outward_hint) >= 0.0;
    let face = if natural_out == !hole {
        face
    } else {
        face.reversed()
    };
    Ok(SkinnedStrip {
        face,
        bottom,
        top,
        rail0,
        rail1,
    })
}

/// The plane every point of the rows lies in, if there is one.
fn plane_of_rows(rows: &[Vec<Point>], tol: Tolerances) -> Option<Plane> {
    let first = rows.first()?;
    let last = rows.last()?;
    let origin = *first.first()?;
    let across = *first.last()? - origin;
    let along = *last.first()? - origin;
    let normal = across.cross(along);
    if normal.magnitude() <= tol.confusion() * across.magnitude().max(along.magnitude()) {
        return None;
    }
    let normal = Direction::new(normal, tol).ok()?;
    let plane = Plane::through(origin, normal);
    rows.iter()
        .flatten()
        .all(|p| plane.distance_to(*p) <= tol.confusion())
        .then_some(plane)
}

/// A border of a strip: the row or the column of the skin at an index.
#[derive(Clone, Copy)]
enum Side {
    Row(usize),
    Column(usize),
}

/// A strip on its own exact plane: the borders fitted through the rows and
/// the end columns, the face on the plane.
#[allow(clippy::too_many_arguments, reason = "one construction, all its data")]
fn planar_strip(
    model: &mut Model,
    skin: &Skin<'_>,
    plane: Plane,
    corners: (&Shape, &Shape, &Shape, &Shape),
    shared: [Option<&Shape>; 4],
    outward_hint: Point,
    hole: bool,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<SkinnedStrip> {
    let rows = &skin.rows;
    // Splines, as every swept border is: the caps and the neighbouring
    // strips read them so, and a spline through collinear points is the
    // straight segment itself. A row or a column whose geometry the skin
    // knows is fitted to it, measured between its samples too.
    let through = |points: &[Point], side: Side| -> OgeomResult<ogeom_geom::Curve> {
        let fitted = match (&skin.traced, side) {
            (Some(traced), Side::Row(j)) => {
                let v = traced.sampling.vs[j];
                ogeom_geom::fit::fit_curve_sampled(
                    |u| (traced.point)(u, v),
                    &traced.sampling.us,
                    false,
                    3,
                    tolerance * 0.5,
                    tol,
                )?
            }
            (Some(traced), Side::Column(i)) if traced.sampling.between.1 => {
                let u = traced.sampling.us[i];
                ogeom_geom::fit::fit_curve_sampled(
                    |v| (traced.point)(u, v),
                    &traced.sampling.vs,
                    false,
                    3,
                    tolerance * 0.5,
                    tol,
                )?
            }
            _ => ogeom_geom::fit::fit_points(points, 3, tolerance * 0.5, tol)?,
        };
        if !fitted.met {
            ogeom_bail!(
                NotDone,
                "a planar strip's border reached {} against a target of {tolerance}",
                fitted.error
            );
        }
        Ok(ogeom_geom::Curve::BSpline(fitted.curve))
    };
    let column = |i: usize| -> Vec<Point> { rows.iter().map(|row| row[i]).collect() };
    let last = rows[0].len() - 1;
    let (c00, c10, c01, c11) = corners;
    let border = |model: &mut Model,
                  given: Option<&Shape>,
                  points: Vec<Point>,
                  side: Side,
                  from: &Shape,
                  to: &Shape|
     -> OgeomResult<Shape> {
        if let Some(edge) = given {
            return Ok(edge.clone());
        }
        let curve = through(&points, side)?;
        let domain = curve.domain();
        Ok(make_edge_between(model, curve, domain, from, to, tol)?.shape)
    };
    let bottom = border(model, shared[0], rows[0].clone(), Side::Row(0), c00, c10)?;
    let top_row = rows.len() - 1;
    let top = border(
        model,
        shared[1],
        rows[top_row].clone(),
        Side::Row(top_row),
        c01,
        c11,
    )?;
    let rail0 = border(model, shared[2], column(0), Side::Column(0), c00, c01)?;
    let rail1 = border(model, shared[3], column(last), Side::Column(last), c10, c11)?;

    // The loop runs across, up, back and down: counter-clockwise about the
    // normal it turns about, read from the whole border sampled in that
    // order. The first row's chord and the first column's are no guide: on
    // a strip starting from a corner's join row they can lie along one line.
    let border: Vec<Point> = rows[0]
        .iter()
        .copied()
        .chain(rows.iter().skip(1).map(|row| row[last]))
        .chain(rows[top_row].iter().rev().skip(1).copied())
        .chain(
            rows.iter()
                .rev()
                .skip(1)
                .take(top_row.saturating_sub(1))
                .map(|row| row[0]),
        )
        .collect();
    let turn = (0..border.len())
        .map(|i| (border[i] - border[0]).cross(border[(i + 1) % border.len()] - border[0]))
        .fold(Vector::new(0.0, 0.0, 0.0), |sum, v| sum + v);
    let normal = if turn.dot(plane.normal().vector()) >= 0.0 {
        plane.normal()
    } else {
        plane.normal().reversed()
    };
    let wound = Plane::through(plane.origin(), normal);
    let reach = rows
        .iter()
        .flatten()
        .map(|p| p.distance(plane.origin()))
        .fold(1.0_f64, f64::max)
        * 2.0;
    let surface: SurfaceGeometry =
        PlaneSurface::over(wound, (-reach, reach), (-reach, reach))?.into();
    let face = ogeom_algo::make_face_with_pcurves(
        model,
        surface.clone(),
        &[vec![
            bottom.clone(),
            rail1.clone(),
            top.reversed(),
            rail0.reversed(),
        ]],
        tol,
    )?
    .shape;
    let mid = rows[rows.len() / 2][last / 2];
    let natural_out = normal.vector().dot(mid - outward_hint) >= 0.0;
    let face = if natural_out == !hole {
        face
    } else {
        face.reversed()
    };
    Ok(SkinnedStrip {
        face,
        bottom,
        top,
        rail0,
        rail1,
    })
}

/// A loft through circles standing coaxial on parallel planes: the solid of
/// revolution of the meridian through their radii, a spline through them
/// in the half-plane of the first circle's start. `None` where the
/// sections are anything else.
fn coaxial_circles_loft(
    model: &mut Model,
    sections: &[Shape],
    tol: Tolerances,
) -> OgeomResult<Option<Built>> {
    let mut circles = Vec::with_capacity(sections.len());
    for wire in sections {
        if model.kind_of(wire)? != ShapeType::Wire {
            return Ok(None);
        }
        let edges = model.ordered_children_of(wire)?;
        let [edge] = edges.as_slice() else {
            return Ok(None);
        };
        let (curve, _) = spine_curve_of(model, edge)?;
        let ogeom_geom::Curve::Circle(c) = curve else {
            return Ok(None);
        };
        let placed = c
            .circle()
            .transformed(&edge.transform(model.datums())?, tol)?;
        circles.push(placed);
    }
    let first = circles[0].frame();
    let (c0, z0) = (first.origin(), first.z().vector());
    let last = circles[circles.len() - 1].centre();
    let rise = last - c0;
    if rise.magnitude() <= tol.confusion() {
        return Ok(None);
    }
    let z = rise / rise.magnitude();
    if z.cross(z0).magnitude() > tol.angular() {
        return Ok(None);
    }
    let mut heights = Vec::with_capacity(circles.len());
    for c in &circles {
        let off = c.centre() - c0;
        if off.cross(z).magnitude() > tol.confusion() * 10.0
            || c.frame().z().vector().cross(z).magnitude() > tol.angular()
        {
            return Ok(None);
        }
        heights.push(off.dot(z));
    }
    if heights.windows(2).any(|w| w[1] <= w[0] + tol.confusion()) {
        return Ok(None);
    }
    let x = first.x().vector();
    let meridian: Vec<Point> = circles
        .iter()
        .zip(&heights)
        .map(|(c, h)| c0 + z * *h + x * c.radius())
        .collect();
    let degree = (meridian.len() - 1).min(3);
    let fitted = ogeom_geom::fit::fit_points(&meridian, degree, tol.confusion() * 1e-3, tol)?;
    let spline: ogeom_geom::Curve = fitted.curve.into();
    let domain = spline.domain();
    let top = c0 + z * heights[heights.len() - 1];
    let vertex = |model: &mut Model, p: Point| ogeom_algo::make_vertex(model, p).shape;
    let (v_axis0, v_axis1) = (vertex(model, c0), vertex(model, top));
    let (v_rim0, v_rim1) = (
        vertex(model, meridian[0]),
        vertex(model, meridian[meridian.len() - 1]),
    );
    let segment =
        |model: &mut Model, a: (&Shape, Point), b: (&Shape, Point)| -> OgeomResult<Shape> {
            let line: ogeom_geom::Curve = LineCurve::segment(a.1, b.1, tol)?.into();
            let range = line.domain();
            Ok(make_edge_between(model, line, range, a.0, b.0, tol)?.shape)
        };
    let bottom = segment(model, (&v_axis0, c0), (&v_rim0, meridian[0]))?;
    let side = make_edge_between(model, spline, domain, &v_rim0, &v_rim1, tol)?.shape;
    let top_edge = segment(
        model,
        (&v_rim1, meridian[meridian.len() - 1]),
        (&v_axis1, top),
    )?;
    let axis_edge = segment(model, (&v_axis1, top), (&v_axis0, c0))?;
    let wire = ogeom_algo::make_wire(model, &[bottom, side, top_edge, axis_edge], tol)?.shape;
    // Framed from a point inside the profile: a plane's own origin is
    // where its face is read when it carries no trims.
    let inside = c0
        + z * (heights[heights.len() - 1] * 0.5)
        + x * (circles
            .iter()
            .map(|c| c.radius())
            .fold(f64::INFINITY, f64::min)
            * 0.5);
    let plane = Plane::new(Frame::new(
        inside,
        Direction::new(z.cross(x), tol)?,
        Direction::new(x, tol)?,
        tol,
    )?);
    let face = ogeom_algo::make_face(model, PlaneSurface::new(plane).into(), &[wire], tol)?.shape;
    let axis = ogeom_math::Axis {
        location: c0,
        direction: Direction::new(z, tol)?,
    };
    let built = ogeom_algo::make_revolution(model, &face, axis, core::f64::consts::TAU, tol)?;
    Ok(Some(built))
}

/// A loft through sections of one edge count, every vertex a corner: one
/// strip per edge through all the sections, meeting its neighbours along
/// seams through the matched corners, each strip a plane wherever its rows
/// share one. `None` where the sections do not pair edge for edge. Where
/// `along` moves the first section onto the others, the strips are held to
/// that motion between the sections too.
fn cornered_loft(
    model: &mut Model,
    sections: &[Shape],
    along: Option<SectionMotion<'_>>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Option<Built>> {
    let mut rings: Vec<Vec<Shape>> = Vec::with_capacity(sections.len());
    for wire in sections {
        if model.kind_of(wire)? != ShapeType::Wire || !ogeom_algo::is_wire_closed(model, wire, tol)?
        {
            return Ok(None);
        }
        rings.push(model.ordered_children_of(wire)?);
    }
    let count = rings[0].len();
    if count < 2 || rings.iter().any(|r| r.len() != count) {
        return Ok(None);
    }
    let (Some(plane0), Some(plane1)) = (
        ogeom_algo::find_plane(model, &sections[0], tol)?,
        ogeom_algo::find_plane(model, &sections[sections.len() - 1], tol)?,
    ) else {
        return Ok(None);
    };
    const ALONG: usize = 16;
    // Every edge of every section, read in its ring's sense at a fraction
    // of its parameter range.
    let mut edge_curves: Vec<Vec<(ogeom_geom::Curve, (f64, f64))>> =
        Vec::with_capacity(rings.len());
    for ring in &rings {
        let mut per_edge = Vec::with_capacity(count);
        for edge in ring {
            let (curve, range) = spine_curve_of(model, edge)?;
            let curve = curve.transformed(&edge.transform(model.datums())?, tol)?;
            let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
            per_edge.push((curve, if reversed { (range.1, range.0) } else { range }));
        }
        edge_curves.push(per_edge);
    }
    let edge_at = |s: usize, e: usize, f: f64| -> OgeomResult<Point> {
        let (curve, (a, b)) = &edge_curves[s][e];
        curve.point_at(a + (b - a) * f, tol)
    };
    let samples: Vec<Vec<Vec<Point>>> = (0..rings.len())
        .map(|s| {
            (0..count)
                .map(|e| fractions(ALONG).iter().map(|f| edge_at(s, e, *f)).collect())
                .collect()
        })
        .collect::<OgeomResult<_>>()?;
    let corners = |model: &mut Model, s: usize| -> Vec<Shape> {
        (0..count)
            .map(|e| ogeom_algo::make_vertex(model, samples[s][e][0]).shape)
            .collect()
    };
    let (from, to) = (corners(model, 0), corners(model, sections.len() - 1));
    let middle = &samples[sections.len() / 2];
    let hint = {
        let all: Vec<Point> = middle.iter().flatten().copied().collect();
        #[allow(clippy::cast_precision_loss)]
        let n = all.len() as f64;
        Point::from_vector(
            all.iter()
                .fold(Vector::new(0.0, 0.0, 0.0), |acc, p| acc + p.to_vector())
                / n,
        )
    };
    let mut faces = Vec::with_capacity(count + 2);
    let (mut bottoms, mut tops) = (Vec::with_capacity(count), Vec::with_capacity(count));
    let mut first_rail: Option<Shape> = None;
    let mut prev_rail: Option<Shape> = None;
    for e in 0..count {
        let skin = match along {
            Some(motion) => Skin::swept(
                move |f, s| {
                    if s.fract() == 0.0 {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                        let i = s as usize;
                        return edge_at(i, e, f);
                    }
                    Ok(motion(s)?.apply(edge_at(0, e, f)?))
                },
                fractions(ALONG),
                (0, rings.len() - 1),
                false,
            )?,
            None => Skin::columns(
                |f| (0..rings.len()).map(|s| edge_at(s, e, f)).collect(),
                fractions(ALONG),
                false,
                true,
                false,
            )?,
        };
        let next = (e + 1) % count;
        let last_rail = if e + 1 == count {
            first_rail.clone()
        } else {
            None
        };
        let strip = skinned_strip(
            model,
            &skin,
            (&from[e], &from[next], &to[e], &to[next]),
            [None, None, prev_rail.as_ref(), last_rail.as_ref()],
            hint,
            false,
            tolerance,
            tol,
        )?;
        if e == 0 {
            first_rail = Some(strip.rail0.clone());
        }
        prev_rail = Some(strip.rail1.clone());
        faces.push(strip.face.clone());
        bottoms.push(strip.bottom);
        tops.push(strip.top);
    }
    let towards = hint - samples[0][0][0];
    let n0 = plane0.normal().vector();
    let n0 = if n0.dot(towards) > 0.0 { -n0 } else { n0 };
    let away = hint - samples[sections.len() - 1][0][0];
    let n1 = plane1.normal().vector();
    let n1 = if n1.dot(away) > 0.0 { -n1 } else { n1 };
    faces.push(plane_cap(model, samples[0][0][0], n0, &[bottoms], tol)?);
    faces.push(plane_cap(
        model,
        samples[sections.len() - 1][0][0],
        n1,
        &[tops],
        tol,
    )?);
    let sewn = sew(model, &faces, tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the cornered loft did not close");
    }
    Ok(Some(make_solid(model, &sewn.shells)?))
}

/// A planar cap through `at`, facing `outward`, bounded by loops of spline
/// or line edges lying in it; each edge's trim is its exact projection into
/// the plane's chart.
fn plane_cap(
    model: &mut Model,
    at: Point,
    outward: Vector,
    loops: &[Vec<Shape>],
    tol: Tolerances,
) -> OgeomResult<Shape> {
    let cap_plane = Plane::through(at, Direction::new(outward, tol)?);
    let mut reach = 1.0_f64;
    for edges in loops {
        for edge in edges {
            let (curve, range) = spine_curve_of(model, edge)?;
            for k in 0..8 {
                let p = curve.point_at(range.0 + (range.1 - range.0) * f64::from(k) / 8.0, tol)?;
                reach = reach.max(p.distance(at) * 2.0);
            }
        }
    }
    let surface: SurfaceGeometry =
        PlaneSurface::over(cap_plane, (-reach, reach), (-reach, reach))?.into();
    // Each loop keeps the material on its left about `outward`: the one
    // enclosing the most turns positively, any other negatively, and a loop
    // walked against that is walked back.
    let turns: Vec<f64> = loops
        .iter()
        .map(|edges| ring_turning(model, edges, outward, tol))
        .collect::<OgeomResult<_>>()?;
    let outer = turns
        .iter()
        .enumerate()
        .max_by(|a, b| a.1.abs().total_cmp(&b.1.abs()))
        .map_or(0, |(i, _)| i);
    let mut wires = Vec::with_capacity(loops.len());
    for (i, (edges, turn)) in loops.iter().zip(&turns).enumerate() {
        let ring = if (*turn > 0.0) == (i == outer) {
            edges.clone()
        } else {
            walked_back(edges)
        };
        wires.push(ogeom_algo::make_wire(model, &ring, tol)?.shape);
    }
    let face = ogeom_algo::make_face(model, surface, &wires, tol)?.shape;
    let cap_id = {
        let Some(ogeom_topo::NodeData::Face(data)) = model.node(&face).map(|n| n.data()) else {
            ogeom_bail!(Construction, "the cap holds no face data");
        };
        data.surface
    };
    let frame = cap_plane.frame();
    let flat = |p: Point| {
        let local = frame.to_local(p);
        Point2::new(local.x, local.y)
    };
    for edges in loops {
        for edge in edges {
            let (curve, range) = spine_curve_of(model, edge)?;
            let pcurve: ogeom_geom::PlanarCurve = match &curve {
                ogeom_geom::Curve::BSpline(bs) => {
                    let control2: Vec<Point2> = bs
                        .control_points()
                        .iter()
                        .map(|w| flat(w.point()))
                        .collect();
                    ogeom_geom::BSpline2d::new(bs.knots().clone(), control2, tol)?.into()
                }
                ogeom_geom::Curve::Line(line) => {
                    let axis = line.axis();
                    let origin = flat(axis.location);
                    let ahead = flat(axis.location + axis.direction.vector());
                    ogeom_geom::Line2d::over(
                        ogeom_math::Axis2::through(origin, ahead, tol)?,
                        range.0,
                        range.1,
                    )?
                    .into()
                }
                _ => ogeom_bail!(Construction, "a cap edge is neither a spline nor a line"),
            };
            ogeom_algo::attach_pcurve(
                model,
                edge,
                pcurve,
                cap_id,
                ogeom_topo::Location::identity(),
                range,
            )?;
        }
    }
    Ok(face)
}

/// Loft a solid through many closed planar sections, skinned smoothly.
///
/// The sections are sampled at matched arc-length fractions from their own
/// traversal starts (aligning those starts is the caller's authorship),
/// and the skin holds every section to `tolerance`, between the samples as
/// well as at them: the sampling round a section is refined where the skin
/// misses it. The caps are the first and last sections' own planes.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if fewer than
/// two sections, a section is open or not planar;
/// [`OgeomError::NotDone`](ogeom_core::OgeomError::NotDone) if
/// the skin cannot reach the tolerance.
pub fn make_loft_skinned(
    model: &mut Model,
    sections: &[Shape],
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    loft_skinned_along(model, sections, None, tolerance, tol)
}

/// The motion carrying a loft's first section to where the sections stand
/// at `s`, a section's index (a fraction of the way between two sections
/// between them): the sections of a sweep are one section moved.
type SectionMotion<'a> = &'a dyn Fn(f64) -> OgeomResult<Transform>;

/// [`make_loft_skinned`], and where `along` is given the sections are the
/// first one moved by it and the skin is held to that motion between them
/// as well as to the sections.
fn loft_skinned_along(
    model: &mut Model,
    sections: &[Shape],
    along: Option<SectionMotion<'_>>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if sections.len() < 2 {
        ogeom_bail!(Construction, "a loft needs at least two sections");
    }
    let to_point = model.kind_of(&sections[sections.len() - 1])? == ShapeType::Vertex;
    // The smooth skin through two sections is the ruled one, and that is
    // built exactly: a drum or cone between circles, planes between
    // polygons.
    if sections.len() == 2
        && !to_point
        && along.is_none()
        && let Ok(built) = make_loft(model, &sections[0], &sections[1], tol)
    {
        return Ok(built);
    }
    if sections.len() > 2 && !to_point {
        if let Some(built) = coaxial_circles_loft(model, sections, tol)? {
            return Ok(built);
        }
        if let Some(built) = cornered_loft(model, sections, along, tolerance, tol)? {
            return Ok(built);
        }
    }
    // A trailing vertex is the apex form: the skin narrows to a point and
    // the solid closes there without a cap.
    let apex = match model.kind_of(&sections[sections.len() - 1])? {
        ShapeType::Vertex => {
            if sections.len() < 2 {
                ogeom_bail!(
                    Construction,
                    "a loft to a point needs a section to start from"
                );
            }
            let Some(data) = model
                .node(&sections[sections.len() - 1])
                .and_then(|n| n.data().as_vertex())
            else {
                ogeom_bail!(Construction, "the apex vertex holds no point");
            };
            Some(data.point)
        }
        _ => None,
    };
    let wires = &sections[..sections.len() - usize::from(apex.is_some())];
    let mut loops: Vec<Section> = Vec::with_capacity(sections.len() + 1);
    let mut cap_planes: Vec<Option<Plane>> = Vec::with_capacity(wires.len());
    for wire in wires {
        if model.kind_of(wire)? != ShapeType::Wire {
            ogeom_bail!(Construction, "a loft section is a wire");
        }
        if !ogeom_algo::is_wire_closed(model, wire, tol)? {
            ogeom_bail!(Construction, "a loft section must be closed");
        }
        // Planarity is a *cap's* requirement, not the fit's: only the
        // sections a cap will stand on must hold a plane. A wavy middle
        // section skins fine.
        cap_planes.push(ogeom_algo::find_plane(model, wire, tol)?);
        loops.push(Section::Loop(section_loop(model, wire, None, tol)?));
    }
    // A planar end is capped by its plane; one that is not (a wavy rim),
    // by a patch skinned from the ring to a point inside it.
    let outward_at = |rows: &[Vec<Point>], planes: &[Option<Plane>], end: bool| -> EndCap {
        let (i, j) = if end {
            (rows.len() - 1, rows.len() - 2)
        } else {
            (0, 1)
        };
        let Some(plane) = &planes[i] else {
            return EndCap::Skinned;
        };
        let towards = rows[j][0] - rows[i][0];
        let n = plane.normal().vector();
        EndCap::Plane(if n.dot(towards) > 0.0 { -n } else { n })
    };
    let mut built = if let Some(apex) = apex {
        if loops.len() < 2
            && let Some(Section::Loop(ring)) = loops.first()
        {
            // One ring to a point is exact machinery's job when it can be;
            // the skin still needs two rows to shape the wall, so a middle
            // row is interpolated halfway toward the apex.
            let half = Section::Halfway(ring.clone(), apex);
            loops.push(half);
        }
        loops.push(Section::Point(apex));
        let skin = Skin::sections(loops, false)?;
        let rows = &skin.rows;
        let outward0 = match outward_at(rows, &cap_planes, false) {
            EndCap::Plane(n) => n,
            EndCap::Skinned => {
                ogeom_bail!(
                    Construction,
                    "a loft to a point starts from a planar section; a cap stands on it"
                );
            }
        };
        skinned_solid_to_apex(model, &skin, outward0, tolerance, tol)?
    } else {
        let skin = match along {
            Some(motion) => {
                let Some(Section::Loop(first)) = loops.first().cloned() else {
                    ogeom_bail!(Construction, "a loft's first section is a loop");
                };
                Skin::swept(
                    move |f, s| {
                        if s.fract() == 0.0 {
                            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                            let i = s as usize;
                            return Ok(loops[i].at(f));
                        }
                        Ok(motion(s)?.apply(first.at(f)))
                    },
                    fractions(AROUND_SECTION),
                    (0, sections.len() - 1),
                    true,
                )?
            }
            None => Skin::sections(loops, false)?,
        };
        let outward0 = outward_at(&skin.rows, &cap_planes, false);
        let outward1 = outward_at(&skin.rows, &cap_planes, true);
        skinned_solid(model, &skin, (outward0, outward1), tolerance, tol)?
    };
    for section in sections {
        built.history.generate(section, built.shape.clone());
    }
    Ok(built)
}

/// Sample a closed wire at `count` matched arc-length fractions.
fn sample_wire(
    model: &Model,
    wire: &Shape,
    count: usize,
    tol: Tolerances,
) -> OgeomResult<Vec<Point>> {
    sample_wire_from(model, wire, count, None, tol)
}

/// As [`sample_wire`], with the arc-length origin rotated to the dense
/// sample nearest `start_hint`: how a caller says which point of each
/// section rows up with which, instead of leaning on traversal starts.
fn sample_wire_from(
    model: &Model,
    wire: &Shape,
    count: usize,
    start_hint: Option<Point>,
    tol: Tolerances,
) -> OgeomResult<Vec<Point>> {
    let arc = section_loop(model, wire, start_hint, tol)?;
    Ok((0..count)
        .map(|s| {
            #[allow(clippy::cast_precision_loss, reason = "a small count")]
            let f = s as f64 / count as f64;
            arc.at(f)
        })
        .collect())
}

/// A closed wire read by arc length from its traversal start, or from the
/// dense sample nearest `start_hint` where one is given.
fn section_loop(
    model: &Model,
    wire: &Shape,
    start_hint: Option<Point>,
    tol: Tolerances,
) -> OgeomResult<ArcLoop> {
    let mut dense = dense_wire(model, wire, tol)?;
    if let Some(hint) = start_hint {
        let mut best = 0usize;
        let mut held = f64::INFINITY;
        for (i, p) in dense.iter().enumerate() {
            let d = p.distance(hint);
            if d < held {
                held = d;
                best = i;
            }
        }
        dense.rotate_left(best);
    }
    Ok(ArcLoop::new(dense))
}

/// A closed wire as a dense polyline, by traversal, without the closing
/// point.
fn dense_wire(model: &Model, wire: &Shape, tol: Tolerances) -> OgeomResult<Vec<Point>> {
    let mut dense: Vec<Point> = Vec::new();
    for edge in explore(model, wire, Filter::OfType(ShapeType::Edge))? {
        let Some(data) = model.node(&edge).and_then(|n| n.data().as_edge()) else {
            ogeom_bail!(Construction, "a section edge holds no data");
        };
        let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
            ogeom_bail!(Construction, "a section edge has no curve");
        };
        let Some(geometry) = model.geometry().curve(*curve) else {
            ogeom_bail!(Dangling, "curve is not in this model");
        };
        let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
        // Where the edge stands: a placed wire's edges carry its placement.
        let placement = edge.transform(model.datums())?;
        let at = |f: f64| -> OgeomResult<Point> {
            let t = if reversed {
                range.1 - (range.1 - range.0) * f
            } else {
                range.0 + (range.1 - range.0) * f
            };
            Ok(placement.apply(geometry.point_at(t, tol)?))
        };
        // Samples are read along the chords between these points, so the
        // chords keep within a micron of the curve: the sag measured over a
        // first pass, and the count raised by its square root (the sag
        // falls with the square of the count).
        const FIRST: u32 = 64;
        const MOST: u32 = 8192;
        let mut sag = 0.0_f64;
        for i in 0..FIRST {
            let (f0, f1) = (
                f64::from(i) / f64::from(FIRST),
                f64::from(i + 1) / f64::from(FIRST),
            );
            let (a, b) = (at(f0)?, at(f1)?);
            let mid = at(f64::midpoint(f0, f1))?;
            sag = sag.max(mid.distance(a.midpoint(b)));
        }
        let allowed = tol.confusion() * 10.0;
        #[allow(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "a sample count, bounded"
        )]
        let count = if sag <= allowed {
            FIRST
        } else {
            ((f64::from(FIRST) * (sag / allowed).sqrt()).ceil() as u32).clamp(FIRST, MOST)
        };
        for i in 0..count {
            dense.push(at(f64::from(i) / f64::from(count))?);
        }
    }
    if dense.is_empty() {
        ogeom_bail!(Construction, "a section has no edges");
    }
    Ok(dense)
}

/// A section's dense polyline in its own frame, started and run where its
/// `count` samples best match the section before (`previous`, in its
/// frame): a section's start and sense are accidents of how it was drawn,
/// and matched as given they twist the blend. Every start of the dense
/// polyline is a candidate both ways; the given start and sense win a tie.
///
/// A start's samples are read off one arc-length parametrisation per sense,
/// shifted by the start's length. The cost is a smooth function of that
/// shift, so it is read at about `8 * count` starts first and then at every
/// start next to a coarse local minimum, in the order an exhaustive scan
/// would visit them.
fn matched_loop(dense: &[Point], count: usize, previous: &[Point]) -> ArcLoop {
    let n = dense.len();
    let ways = [
        ArcLoop::new(dense.to_vec()),
        ArcLoop::new(dense.iter().rev().copied().collect()),
    ];
    #[allow(clippy::cast_precision_loss, reason = "a sample count")]
    fn samples(arc: &ArcLoop, start: usize, count: usize) -> impl Iterator<Item = Point> + '_ {
        let offset = arc.lengths[start] / arc.total;
        (0..count).map(move |k| {
            let f = offset + k as f64 / count as f64;
            arc.at(if f >= 1.0 { f - 1.0 } else { f })
        })
    }
    let cost = |arc: &ArcLoop, start: usize| -> f64 {
        samples(arc, start, count)
            .zip(previous)
            .map(|(p, q)| (p - *q).dot(p - *q))
            .sum()
    };
    let scale: f64 = previous
        .iter()
        .copied()
        .chain(samples(&ways[0], 0, count))
        .map(|p| (p - Point::ORIGIN).dot(p - Point::ORIGIN))
        .sum();
    let slack = scale * 1e-12;
    let coarse = 8 * count.max(1);
    let mut held = cost(&ways[0], 0);
    let mut best = (0, 0);
    for (w, arc) in ways.iter().enumerate() {
        let mut tried = vec![n <= 2 * coarse; n];
        if n > 2 * coarse {
            let picks: Vec<usize> = (0..coarse).map(|j| j * n / coarse).collect();
            let costs: Vec<f64> = picks.iter().map(|&i| cost(arc, i)).collect();
            for j in 0..coarse {
                let (before, after) = ((j + coarse - 1) % coarse, (j + 1) % coarse);
                if costs[j] <= costs[before] && costs[j] <= costs[after] {
                    let (from, to) = (picks[before], picks[after]);
                    let mut i = from;
                    loop {
                        tried[i] = true;
                        if i == to {
                            break;
                        }
                        i = (i + 1) % n;
                    }
                }
            }
        }
        for start in (0..n).filter(|&i| tried[i]) {
            let c = cost(arc, start);
            if c < held - slack {
                held = c;
                best = (w, start);
            }
        }
    }
    let [forward, backward] = ways;
    let (way, start) = best;
    let arc = if way == 0 { forward } else { backward };
    if start == 0 {
        return arc;
    }
    let mut turned = arc.dense;
    turned.rotate_left(start);
    ArcLoop::new(turned)
}

/// Sweep a circular profile along a free-form spine, skinned.
///
/// Frames along the spine are rotation-minimizing (the double-reflection
/// construction), so the tube neither twists nor kinks where the spine
/// bends; the skin holds the tube to `tolerance`, measured between its
/// stations and round its circles as well as at the samples and refined
/// where it misses, and the caps sit perpendicular to the spine's ends.
///
/// # Errors
///
/// As [`make_pipe`], plus [`OgeomError::NotDone`](ogeom_core::OgeomError::NotDone) if
/// the skin cannot reach the
/// tolerance.
pub fn make_pipe_skinned(
    model: &mut Model,
    spine: &Shape,
    radius: f64,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if !radius.is_finite() || radius <= tol.confusion() {
        ogeom_bail!(Construction, "a pipe of radius {radius} holds nothing");
    }
    let (curve, range) = {
        let Some(data) = model.node(spine).and_then(|n| n.data().as_edge()) else {
            ogeom_bail!(Construction, "a pipe runs along an edge");
        };
        let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
            ogeom_bail!(Construction, "the spine has no curve");
        };
        let Some(geometry) = model.geometry().curve(*curve) else {
            ogeom_bail!(Dangling, "curve is not in this model");
        };
        (geometry.clone(), *range)
    };
    // The skin starts from 33 stations; the frame is carried along 64
    // times as many, so the frame between stations turns smoothly enough
    // for the fit refining between them.
    const STATIONS: usize = 33;
    const FRAMES: usize = 64 * (STATIONS - 1) + 1;
    const AROUND: usize = 40;
    let mut stations: Vec<SpineStation> = Vec::with_capacity(FRAMES);
    for i in 0..FRAMES {
        #[allow(clippy::cast_precision_loss)]
        let t = range.0 + (range.1 - range.0) * (i as f64) / ((FRAMES - 1) as f64);
        let p = curve.point_at(t, tol)?;
        let d = curve.d1_at(t, tol)?;
        let m = d.magnitude();
        if m <= tol.confusion() {
            ogeom_bail!(Construction, "the spine is degenerate at {t}");
        }
        stations.push(SpineStation {
            at: p,
            tangent: d / m,
            edge: 0,
            t,
        });
    }
    let normals = rmf_normals(&stations);
    // The tube anywhere: the circle about the spine point at `t`, in the
    // frame carried one rotation-minimizing step from the frame station
    // behind, `u` the fraction of a turn. At a station that is the
    // station's own frame, so the tube runs continuously through every
    // station.
    let tube = |u: f64, t: f64| -> OgeomResult<Point> {
        let k = stations.partition_point(|s| s.t <= t).clamp(1, FRAMES) - 1;
        let p = curve.point_at(t, tol)?;
        let d = curve.d1_at(t, tol)?;
        let m = d.magnitude();
        if m <= tol.confusion() {
            ogeom_bail!(Construction, "the spine is degenerate at {t}");
        }
        let tangent = d / m;
        let x = rmf_step(stations[k].at, stations[k].tangent, normals[k], p, tangent);
        let y = tangent.cross(x);
        let ang = core::f64::consts::TAU * u;
        Ok(p + (x * ang.cos() + y * ang.sin()) * radius)
    };
    let fraction = |i: usize, n: usize| -> f64 {
        #[allow(clippy::cast_precision_loss, reason = "a small count")]
        let f = i as f64 / n as f64;
        f
    };
    let us: Vec<f64> = (0..=AROUND).map(|a| fraction(a, AROUND)).collect();
    let vs: Vec<f64> = stations.iter().step_by(64).map(|s| s.t).collect();
    let rows = vs
        .iter()
        .map(|&t| us[..AROUND].iter().map(|&u| tube(u, t)).collect())
        .collect::<OgeomResult<Vec<Vec<Point>>>>()?;
    let skin = Skin {
        rows,
        round: true,
        by_spacing: false,
        traced: Some(Traced {
            // The end of the way round is its start, to the bit, so the
            // seam closes exactly.
            point: Box::new(move |u, t| tube(if u >= 1.0 { 0.0 } else { u }, t)),
            sampling: ogeom_geom::fit::Sampling {
                us,
                vs,
                between: (true, true),
                closed_v: false,
                most: 512,
            },
        }),
    };
    let mut built = skinned_solid(
        model,
        &skin,
        (
            EndCap::Plane(-stations[0].tangent),
            EndCap::Plane(stations[FRAMES - 1].tangent),
        ),
        tolerance,
        tol,
    )?;
    built.history.generate(spine, built.shape.clone());
    Ok(built)
}

/// One sampled spine station: where the spine is and which way it runs.
#[derive(Clone, Copy)]
pub(crate) struct SpineStation {
    pub(crate) at: Point,
    /// The unit tangent, in the direction of travel.
    pub(crate) tangent: Vector,
    /// The spine edge this station stands on, by position in the spine.
    pub(crate) edge: usize,
    /// The station's parameter on that edge's curve.
    pub(crate) t: f64,
}

/// One profile wire's closed shell round the spine: smooth wires skin as a
/// single closed face, faceted ones as one ring strip per facet.
#[allow(clippy::too_many_arguments, reason = "one frame, spelled out")]
fn closed_loop_shell(
    model: &mut Model,
    profile_loop: &Shape,
    edges: &[Shape],
    smooth: bool,
    walk: &SpineWalk<'_>,
    frame0: (Point, Vector),
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    const AROUND: usize = 40;
    let (origin, x0) = frame0;
    let stations = walk.stations;
    let t0 = stations[0].tangent;
    let y0 = t0.cross(x0);
    // The way round runs from the first station to its return home, the
    // last of the walk's stations.
    let home = stations.len() - 1;
    // A point of the profile, in the start frame, at `s` along the way
    // round: a station's own frame at a station, the home station the
    // first again, the frame carried between them anywhere else.
    let carried = |s: f64, (a, b): (f64, f64)| -> OgeomResult<Point> {
        if s.fract() == 0.0 {
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let i = (s as usize) % home;
            let (station, x) = (&stations[i], walk.normals[i]);
            return Ok(station.at + x * a + station.tangent.cross(x) * b);
        }
        walk.generator(s, (0, home), (a, b), tol)
    };
    if !smooth {
        // A faceted profile: one ring strip per profile edge; a fit cannot
        // speak a corner, so each facet gets its own v-closed skin and the
        // strips sew along the corner loops they share within tolerance.
        const ALONG_EDGE: usize = 8;
        // Outward for a ring strip means away from the spine's own line,
        // not from the loop's centroid: a ring's inner side *faces* the
        // centroid. The hint is the station the strip's midpoint rides.
        let mid_station = stations[stations.len() / 2].at;
        let mut faces = Vec::with_capacity(edges.len());
        // Each corner loop is one rail edge shared by the two strips that
        // meet along it, the wrap included.
        let mut rails: Vec<Option<Shape>> = vec![None; edges.len()];
        for (index, edge) in edges.iter().enumerate() {
            let (curve, range) = spine_curve_of(model, edge)?;
            let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
            // rows[j = station][i = across the facet]: each column one
            // point of the edge, at a fraction of its parameter range,
            // carried through the stations.
            let skin = Skin::swept(
                |f, s| {
                    let t = if reversed {
                        range.1 - (range.1 - range.0) * f
                    } else {
                        range.0 + (range.1 - range.0) * f
                    };
                    let p = curve.point_at(t, tol)?;
                    carried(s, ((p - origin).dot(x0), (p - origin).dot(y0)))
                },
                fractions(ALONG_EDGE),
                (0, home),
                false,
            )?;
            let next = (index + 1) % edges.len();
            let shared = [rails[index].clone(), rails[next].clone()];
            let (face, rail0, rail1) = skinned_ring_strip(
                model,
                &skin,
                mid_station,
                [shared[0].as_ref(), shared[1].as_ref()],
                tolerance,
                tol,
            )?;
            rails[index] = Some(rail0);
            rails[next] = Some(rail1);
            faces.push(face);
        }
        let sewn = sew(model, &faces, tol)?;
        if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
            if std::env::var_os("OGEOM_DEBUG_RING").is_some() {
                use ogeom_geom::Curve3d as _;
                eprintln!(
                    "RING: {} shells from {} strips",
                    sewn.shells.len(),
                    faces.len()
                );
                for shell in &sewn.shells {
                    for edge in ogeom_topo::explore_unique(model, shell, ShapeType::Edge)? {
                        let mut uses = 0;
                        for f in explore(model, shell, Filter::OfType(ShapeType::Face))? {
                            for w in model.children_of(&f)? {
                                for e in model.children_of(&w)? {
                                    if e.node() == edge.node() {
                                        uses += 1;
                                    }
                                }
                            }
                        }
                        if uses == 1
                            && let Some(d) = model.node(&edge).and_then(|n| n.data().as_edge())
                            && let Some(ogeom_topo::EdgeRepr::Curve3d { curve, range, .. }) =
                                d.curve3d()
                            && let Some(g) = model.geometry().curve(*curve)
                        {
                            eprintln!(
                                "RING open edge tol {:.2e}: {:?} -> {:?}",
                                d.tolerance.get(),
                                g.point_at(range.0, tol)?,
                                g.point_at(range.1, tol)?
                            );
                        }
                    }
                }
            }
            ogeom_bail!(Construction, "the faceted ring did not close");
        }
        return Ok(sewn.shells[0].clone());
    }
    // Each column one point of the profile, read by arc length round it,
    // carried through the stations.
    let around = section_loop(model, profile_loop, None, tol)?;
    let skin = Skin::swept(
        |f, s| {
            let p = around.at(f);
            carried(s, ((p - origin).dot(x0), (p - origin).dot(y0)))
        },
        fractions(AROUND),
        (0, home),
        true,
    )?;
    closed_skinned_shell(model, &skin, tolerance, tol)
}

/// Rotation-minimizing normals along the stations, by double reflection:
/// reflect in each chord's plane, then in the plane bisecting the tangents.
/// Self-contained (it needs only the station list) and shared by every
/// sweep that must not twist where its spine bends.
fn rmf_normals(stations: &[SpineStation]) -> Vec<Vector> {
    let mut normals: Vec<Vector> = Vec::with_capacity(stations.len());
    let t0 = stations[0].tangent;
    let seed = if t0.cross(ogeom_math::Vector::Z).magnitude() > 0.5 {
        ogeom_math::Vector::Z
    } else {
        ogeom_math::Vector::X
    };
    let n0 = {
        let v = seed - t0 * seed.dot(t0);
        v / v.magnitude()
    };
    normals.push(n0);
    for i in 1..stations.len() {
        let (p0, t0) = (stations[i - 1].at, stations[i - 1].tangent);
        let (p1, t1) = (stations[i].at, stations[i].tangent);
        let n = normals[i - 1];
        let v1 = p1 - p0;
        let c1 = v1.dot(v1);
        if c1 <= 1e-20 {
            // A corner's twin station: no travel to reflect through. The
            // normal is reflected across the corner's mitre plane instead;
            // for a vector square to the incoming tangent that is exactly
            // the parallel transport about the corner's own axis, and the
            // mirror symmetry is what lands both legs' sheared sections on
            // one ring. A planar corner's normal lies in the mitre plane
            // already and carries straight across; a skew corner's does
            // not, and carried unchanged it leaves the far leg's section
            // off the mitre.
            let bisector = t0 + t1;
            let m = bisector.magnitude();
            if m <= 1e-12 {
                normals.push(n);
                continue;
            }
            let b = bisector / m;
            normals.push(n - b * (2.0 * n.dot(b)));
            continue;
        }
        normals.push(rmf_step(p0, t0, n, p1, t1));
    }
    normals
}

/// One rotation-minimizing step: the normal `n0` at `(p0, t0)` carried to
/// `(p1, t1)` by double reflection. No travel means no change.
fn rmf_step(p0: Point, t0: Vector, n0: Vector, p1: Point, t1: Vector) -> Vector {
    let v1 = p1 - p0;
    let c1 = v1.dot(v1);
    if c1 <= 1e-20 {
        return n0;
    }
    let nl = n0 - v1 * (2.0 / c1 * v1.dot(n0));
    let tl = t0 - v1 * (2.0 / c1 * v1.dot(t0));
    let v2 = t1 - tl;
    let c2 = v2.dot(v2);
    let next = if c2 > 1e-20 {
        nl - v2 * (2.0 / c2 * v2.dot(nl))
    } else {
        nl
    };
    next / next.magnitude()
}

/// A leg's generators, evaluated anywhere: the spine's own curve between
/// stations with the rotation-minimizing normal carried one step from the
/// station behind (turned to meet the next station's normal where the law
/// differs from that step), and a straight extension past either end in
/// the end frame: the surface a mitre trims against. Parameters are
/// station indices; a unit beyond an end is one station spacing.
struct SpineWalk<'a> {
    curves: Vec<WalkCurve>,
    stations: &'a [SpineStation],
    normals: &'a [Vector],
}

/// A spine edge's curve, range and whether it is travelled reversed.
type WalkCurve = (ogeom_geom::Curve, (f64, f64), bool);

/// Every spine edge as a [`WalkCurve`], in the spine's order.
fn walk_curves(model: &Model, spine: &Shape) -> OgeomResult<Vec<WalkCurve>> {
    let edges: Vec<Shape> = match model.kind_of(spine)? {
        ShapeType::Edge => vec![spine.clone()],
        _ => model.ordered_children_of(spine)?,
    };
    let mut out = Vec::with_capacity(edges.len());
    for edge in &edges {
        let (curve, range) = spine_curve_of(model, edge)?;
        out.push((
            curve,
            range,
            edge.orientation() == ogeom_topo::Orientation::Reversed,
        ));
    }
    Ok(out)
}

/// Where two legs' generators for one profile point meet at a corner: the
/// point, each leg's parameter, and how far the two generators actually
/// miss each other (zero when the corner turns in the plane).
struct CornerJoin {
    at: Point,
    s1: f64,
    s2: f64,
    gap: f64,
}

impl SpineWalk<'_> {
    /// The spine point, unit tangent and frame normal at `s` within the run
    /// `(rs, re)`.
    fn frame_at(
        &self,
        s: f64,
        (rs, re): (usize, usize),
        tol: Tolerances,
    ) -> OgeomResult<(Point, Vector, Vector)> {
        let st = self.stations;
        let at = |i: usize| (st[i].at, st[i].tangent, self.normals[i]);
        #[allow(clippy::cast_precision_loss)]
        let (rsf, ref_) = (rs as f64, re as f64);
        if s <= rsf {
            let (p, t, n) = at(rs);
            let h = st[rs].at.distance(st[(rs + 1).min(re)].at);
            return Ok((p + t * ((s - rsf) * h), t, n));
        }
        if s >= ref_ {
            let (p, t, n) = at(re);
            let h = st[re].at.distance(st[re.saturating_sub(1).max(rs)].at);
            return Ok((p + t * ((s - ref_) * h), t, n));
        }
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let j = s.floor() as usize;
        #[allow(clippy::cast_precision_loss)]
        let f = s - j as f64;
        if f <= 0.0 {
            return Ok(at(j));
        }
        let (curve, range, reversed) = &self.curves[st[j + 1].edge];
        let t_from = if st[j].edge == st[j + 1].edge {
            st[j].t
        } else if *reversed {
            range.1
        } else {
            range.0
        };
        let t = t_from + (st[j + 1].t - t_from) * f;
        let p = curve.point_at(t, tol)?;
        let d = curve.d1_at(t, tol)?;
        let m = d.magnitude();
        if m <= tol.confusion() {
            ogeom_bail!(Construction, "the spine is degenerate at {t}");
        }
        let tangent = if *reversed { -(d / m) } else { d / m };
        let n = rmf_step(st[j].at, st[j].tangent, self.normals[j], p, tangent);
        // A law whose normals are not carried by this step (Frenet, or a
        // ring's twist spread round it) turns from the carried normal by
        // the angle it reaches at the next station, a share of it in
        // proportion to the way there, so the frame meets both stations.
        let carried = rmf_step(
            st[j].at,
            st[j].tangent,
            self.normals[j],
            st[j + 1].at,
            st[j + 1].tangent,
        );
        let ahead = self.normals[j + 1];
        let turn = carried
            .cross(ahead)
            .dot(st[j + 1].tangent)
            .atan2(carried.dot(ahead));
        if turn == 0.0 {
            return Ok((p, tangent, n));
        }
        let phi = turn * f;
        let n = n * phi.cos() + tangent.cross(n) * phi.sin();
        let n = n - tangent * n.dot(tangent);
        Ok((p, tangent, n / n.magnitude()))
    }

    /// The generator of profile point `(a, b)` at `s` within the run.
    fn generator(
        &self,
        s: f64,
        run: (usize, usize),
        (a, b): (f64, f64),
        tol: Tolerances,
    ) -> OgeomResult<Point> {
        let (p, t, x) = self.frame_at(s, run, tol)?;
        let y = t.cross(x);
        Ok(p + x * a + y * b)
    }

    /// Where the generators of one profile point on the leg `before` and
    /// the leg `after` a corner meet: Gauss-Newton on both parameters from
    /// the corner itself, minimising the distance between the two.
    fn join(
        &self,
        before: (usize, usize),
        after: (usize, usize),
        ab: (f64, f64),
        tol: Tolerances,
    ) -> OgeomResult<CornerJoin> {
        const STEP: f64 = 1e-4;
        #[allow(clippy::cast_precision_loss)]
        let (mut s1, mut s2) = (before.1 as f64, after.0 as f64);
        for _ in 0..60 {
            let g1 = self.generator(s1, before, ab, tol)?;
            let g2 = self.generator(s2, after, ab, tol)?;
            let f = g1 - g2;
            let d1 = (self.generator(s1 + STEP, before, ab, tol)?
                - self.generator(s1 - STEP, before, ab, tol)?)
                / (2.0 * STEP);
            let d2 = (self.generator(s2 + STEP, after, ab, tol)?
                - self.generator(s2 - STEP, after, ab, tol)?)
                / (2.0 * STEP);
            let (a11, a12, a22) = (d1.dot(d1), -d1.dot(d2), d2.dot(d2));
            let (b1, b2) = (-f.dot(d1), f.dot(d2));
            let det = a11 * a22 - a12 * a12;
            if det.abs() <= 1e-30 {
                break;
            }
            let e1 = (b1 * a22 - a12 * b2) / det;
            let e2 = (a11 * b2 - a12 * b1) / det;
            s1 += e1;
            s2 += e2;
            if e1.abs().max(e2.abs()) <= 1e-12 {
                break;
            }
        }
        let g1 = self.generator(s1, before, ab, tol)?;
        let g2 = self.generator(s2, after, ab, tol)?;
        Ok(CornerJoin {
            at: g1.midpoint(g2),
            s1,
            s2,
            gap: g1.distance(g2),
        })
    }
}

/// Sweep a planar profile along a helix about `axis`: a screw motion,
/// every point of the profile running its own helix. The thread and spring
/// operation, with the profile in a plane through the axis; a profile in
/// any other plane clear of the axis (square to it, a ramp or a stair's
/// tread) climbs the same way.
///
/// `pitch` is the advance per turn along `axis`, `turns` how far the
/// profile turns, `left_handed` turns it the other way about the axis for
/// the same advance, and `taper_per_turn` moves every point away from the
/// axis by that much per turn (a conical helix; zero for a cylindrical
/// one). A pitch of zero with a taper is a flat spiral, every point
/// turning in its plane square to the axis while moving out. The walls are
/// fitted through each profile edge's exact screw images; the caps are the
/// profile where it starts and where it ends.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if
/// the profile is not a planar face, meets the axis, would meet itself one
/// turn on (its extent along the axis is not less than the pitch, or for a
/// flat spiral its extent away from the axis not less than the taper), is
/// carried partly forward through its own plane and partly back, or tapers
/// onto the axis; if a taper is asked of a profile whose plane neither
/// holds the axis nor stands square to it; if `turns` is not positive,
/// `pitch` is negative, or both `pitch` and the taper are zero.
/// [`OgeomError::NotDone`](ogeom_core::OgeomError::NotDone) if a wall
/// cannot be fitted.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
pub fn make_helical_sweep(
    model: &mut Model,
    profile: &Shape,
    axis: ogeom_math::Axis,
    pitch: f64,
    turns: f64,
    left_handed: bool,
    taper_per_turn: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if !(pitch.is_finite() && pitch >= 0.0) || !(turns.is_finite() && turns > 0.0) {
        ogeom_bail!(
            Construction,
            "a helical sweep needs a pitch of zero or more and a positive turn count; \
             got {pitch} and {turns}"
        );
    }
    if !taper_per_turn.is_finite() {
        ogeom_bail!(Construction, "a taper of {taper_per_turn} is not a length");
    }
    let flat = pitch <= tol.confusion();
    if flat && taper_per_turn.abs() <= tol.confusion() {
        ogeom_bail!(
            Construction,
            "a helical sweep with no pitch and no taper turns the profile onto itself"
        );
    }
    if model.kind_of(profile)? != ShapeType::Face {
        ogeom_bail!(Construction, "a helical sweep sweeps a planar face");
    }
    let Some(plane) = ogeom_algo::find_plane(model, profile, tol)? else {
        ogeom_bail!(Construction, "a helical sweep sweeps a planar face");
    };
    let z = axis.direction.vector();
    let n = plane.normal().vector();
    let holds_axis = n.dot(z).abs() <= tol.angular()
        && plane.distance_to(axis.location) <= tol.confusion() * 100.0;
    let level = (n.dot(z).abs() - 1.0).abs() <= tol.angular();
    // A taper moves every point away from the axis by the same amount, which
    // keeps a profile in a plane only where that plane holds the axis or
    // stands square to it.
    if taper_per_turn.abs() > tol.confusion() && !holds_axis && !level {
        ogeom_bail!(
            Construction,
            "a tapered helical sweep carries a profile in a plane through the \
             axis or square to it; an oblique profile would leave its plane"
        );
    }
    // A profile the axis runs through has points with no helix to follow:
    // where the axis pierces the plane is asked of the profile's rings,
    // read in the plane.
    if !holds_axis && n.dot(z).abs() > tol.angular() {
        let reach = (plane.origin() - axis.location).dot(n) / z.dot(n);
        let pierce = axis.location + z * reach;
        let frame = plane.frame();
        let flat = |p: Point| {
            let l = frame.to_local(p);
            Point2::new(l.x, l.y)
        };
        let at = flat(pierce);
        let mut inside = false;
        let mut touches = false;
        for wire in explore(model, profile, Filter::OfType(ShapeType::Wire))? {
            let ring: Vec<Point2> = sample_wire(model, &wire, 256, tol)?
                .into_iter()
                .map(flat)
                .collect();
            for (k, a) in ring.iter().enumerate() {
                let b = ring[(k + 1) % ring.len()];
                let (ab, ap) = (b - *a, at - *a);
                let t = (ap.dot(ab) / ab.dot(ab).max(f64::MIN_POSITIVE)).clamp(0.0, 1.0);
                touches |= (*a + ab * t).distance(at) <= tol.confusion() * 100.0;
                if (a.y > at.y) != (b.y > at.y) && at.x < a.x + (at.y - a.y) / (b.y - a.y) * ab.x {
                    inside = !inside;
                }
            }
        }
        if inside || touches {
            ogeom_bail!(
                Construction,
                "the profile meets the axis, where a helical sweep has no helix \
                 to follow"
            );
        }
    }
    let total = core::f64::consts::TAU * turns;
    let sense = if left_handed { -1.0 } else { 1.0 };
    // How a point sets off at the start of the turn: up the axis by the
    // pitch, round it, and out by the taper, each per radian.
    let travel = |p: Point| -> Vector {
        let foot = axis.project(p);
        let out = p - foot;
        let rho = out.magnitude().max(f64::MIN_POSITIVE);
        let radial = out / rho;
        (z * pitch + radial * taper_per_turn) / core::f64::consts::TAU
            + z.cross(radial) * (rho * sense)
    };
    // The screw image of a point after turning through `theta`.
    let screw = |p: Point, theta: f64| -> OgeomResult<Point> {
        let foot = axis.project(p);
        let out = p - foot;
        let rho = out.magnitude();
        let grown = rho + taper_per_turn * theta / core::f64::consts::TAU;
        if rho <= tol.confusion() || grown <= tol.confusion() {
            ogeom_bail!(
                Construction,
                "the profile reaches the axis, where a helical sweep has no \
                 helix to follow"
            );
        }
        let radial = out / rho;
        let across = z.cross(radial);
        let (sin, cos) = (sense * theta).sin_cos();
        let turned = radial * cos + across * sin;
        Ok(foot + z * (pitch * theta / core::f64::consts::TAU) + turned * grown)
    };

    // The profile's loops, their edges in ring order, each sampled.
    let loops = explore(model, profile, Filter::OfType(ShapeType::Wire))?;
    if loops.is_empty() {
        ogeom_bail!(Construction, "the profile has no loop to sweep");
    }
    // Every point leaves the profile's plane the same way, or the profile
    // sweeps back through where it has been; a plane the motion runs
    // along everywhere (a level profile with no pitch) sweeps nothing.
    {
        let (mut ahead, mut behind) = (0.0_f64, 0.0_f64);
        for wire in &loops {
            for p in sample_wire(model, wire, 64, tol)? {
                let t = travel(p);
                let across = t.dot(n) / t.magnitude().max(f64::MIN_POSITIVE);
                ahead = ahead.max(across);
                behind = behind.max(-across);
            }
        }
        if ahead > tol.angular() && behind > tol.angular() {
            ogeom_bail!(
                Construction,
                "the screw carries part of the profile forward through its plane \
                 and part back; the sweep runs into itself"
            );
        }
        if ahead <= tol.angular() && behind <= tol.angular() {
            ogeom_bail!(
                Construction,
                "the screw carries the profile along its own plane; it sweeps \
                 no volume"
            );
        }
    }
    // One turn on, the profile must clear itself: along the axis by the
    // pitch, or for a flat spiral away from it by the taper.
    if turns > 1.0 {
        let mut low = f64::INFINITY;
        let mut high = f64::NEG_INFINITY;
        for wire in &loops {
            for p in sample_wire(model, wire, 64, tol)? {
                let h = if flat {
                    p.distance(axis.project(p))
                } else {
                    (p - axis.location).dot(z)
                };
                low = low.min(h);
                high = high.max(h);
            }
        }
        let (clearance, across) = if flat {
            (taper_per_turn.abs(), "away from the axis")
        } else {
            (pitch, "along the axis")
        };
        if high - low >= clearance - tol.confusion() {
            ogeom_bail!(
                Construction,
                "the profile spans {} {across}, not less than the turn's advance \
                 {clearance}; a turn on it meets itself",
                high - low
            );
        }
    }
    let tolerance = tol.confusion() * 100.0;
    // The walls in quarter turns, each a strip of its own sharing its
    // borders with the next: one fit down many turns of a helix cannot
    // reach the tolerance, a quarter turn's can. The borders stand an
    // eighth of a turn off the profile's own plane and the planes square to
    // it: a strip's border is a copy of the profile, and a plane through the
    // axis at those angles (a block's face set on the axis) would otherwise
    // meet a strip only along its border, where no section starts.
    let quarter = core::f64::consts::FRAC_PI_2;
    let mut borders = vec![0.0];
    let mut next_border = quarter / 2.0;
    while next_border < total - quarter * 1e-3 {
        borders.push(next_border);
        next_border += quarter;
    }
    borders.push(total);
    let segments = borders.len() - 1;
    // The fit keeps fewer controls than samples, so its reach at the
    // samples is set by how many there are.
    const PER_SEGMENT: usize = 48;
    // The turn at `s` stations into a segment, `s` a whole station or any
    // fraction between.
    #[allow(clippy::cast_precision_loss)]
    let theta_at = |seg: usize, s: f64| {
        borders[seg] + (borders[seg + 1] - borders[seg]) * s / (PER_SEGMENT as f64)
    };

    let mut faces: Vec<Shape> = Vec::new();
    let mut cap_loops: [Vec<Vec<Shape>>; 2] = [Vec::new(), Vec::new()];
    for (li, wire) in loops.iter().enumerate() {
        let hole = li != 0;
        let edges = model.ordered_children_of(wire)?;
        let centre = {
            let samples = sample_wire(model, wire, 32, tol)?;
            #[allow(clippy::cast_precision_loss)]
            let n = samples.len() as f64;
            let sum = samples
                .iter()
                .fold(Vector::new(0.0, 0.0, 0.0), |acc, p| acc + p.to_vector());
            Point::from_vector(sum / n)
        };
        // The ring's pieces: every edge in the ring's sense, a closed one
        // (a circle, the whole ring) cut in quarters so each strip's fit
        // spans a quarter turn round it at most.
        let mut pieces: Vec<(ogeom_geom::Curve, f64, f64)> = Vec::new();
        for edge in &edges {
            let (curve, range) = spine_curve_of(model, edge)?;
            let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
            let (t0, t1) = if reversed { (range.1, range.0) } else { range };
            let closed =
                ogeom_algo::edge_vertices(model, edge)?.is_some_and(|(a, b)| a.is_same(&b));
            let parts = if closed { 4 } else { 1 };
            for k in 0..parts {
                #[allow(clippy::cast_precision_loss)]
                let (f0, f1) = (k as f64 / parts as f64, (k + 1) as f64 / parts as f64);
                pieces.push((curve.clone(), t0 + (t1 - t0) * f0, t0 + (t1 - t0) * f1));
            }
        }
        // Each piece's samples, in the ring's sense, ends on its corners
        // exactly.
        let starts: Vec<Point> = pieces
            .iter()
            .map(|(curve, a, _)| curve.point_at(*a, tol))
            .collect::<OgeomResult<_>>()?;
        let count = pieces.len();
        // A piece at a fraction of its range, its ends on its corners
        // exactly.
        let piece_at = |pi: usize, f: f64| -> OgeomResult<Point> {
            let (curve, a, b) = &pieces[pi];
            if f <= 0.0 {
                Ok(starts[pi])
            } else if f >= 1.0 {
                Ok(starts[(pi + 1) % count])
            } else {
                curve.point_at(a + (b - a) * f, tol)
            }
        };
        let along_of = |pi: usize| -> usize {
            if matches!(pieces[pi].0, ogeom_geom::Curve::Line(_)) {
                8
            } else {
                24
            }
        };
        // A piece's strip over one segment: the piece's points screwed
        // through the segment, the station index (an even step of the
        // turn) its parameter across, known between the stations as at
        // them.
        let skin_of = |pi: usize, seg: usize| -> OgeomResult<Skin<'_>> {
            Skin::swept(
                move |f, s| screw(piece_at(pi, f)?, theta_at(seg, s)),
                fractions(along_of(pi)),
                (0, PER_SEGMENT),
                false,
            )
        };

        // A vertex set at every segment boundary.
        let mut corners: Vec<Vec<Shape>> = Vec::with_capacity(segments + 1);
        for b in 0..=segments {
            let theta = if b == segments {
                total
            } else {
                theta_at(b, 0.0)
            };
            let mut set = Vec::with_capacity(count);
            for p in &starts {
                set.push(ogeom_algo::make_vertex(model, screw(*p, theta)?).shape);
            }
            corners.push(set);
        }
        let mut bottoms = Vec::with_capacity(count);
        let mut tops = Vec::with_capacity(count);
        // Per edge, the previous segment's top border, for the next to
        // start on.
        let mut held_tops: Vec<Option<Shape>> = vec![None; count];
        for seg in 0..segments {
            #[allow(clippy::cast_precision_loss)]
            let hint = screw(centre, theta_at(seg, (PER_SEGMENT / 2) as f64))?;
            let mut first_rail: Option<Shape> = None;
            let mut prev_rail: Option<Shape> = None;
            for ei in 0..count {
                let skin = skin_of(ei, seg)?;
                let next = (ei + 1) % count;
                let last_rail = if ei + 1 == count {
                    first_rail.clone()
                } else {
                    None
                };
                let (from, to) = (&corners[seg], &corners[seg + 1]);
                let strip = skinned_strip(
                    model,
                    &skin,
                    (&from[ei], &from[next], &to[ei], &to[next]),
                    [
                        held_tops[ei].as_ref(),
                        None,
                        prev_rail.as_ref(),
                        last_rail.as_ref(),
                    ],
                    hint,
                    hole,
                    tolerance,
                    tol,
                )?;
                if ei == 0 {
                    first_rail = Some(strip.rail0.clone());
                }
                prev_rail = Some(strip.rail1.clone());
                faces.push(strip.face.clone());
                if seg == 0 {
                    bottoms.push(strip.bottom.clone());
                }
                if seg + 1 == segments {
                    tops.push(strip.top.clone());
                }
                held_tops[ei] = Some(strip.top);
            }
        }
        cap_loops[0].push(bottoms);
        cap_loops[1].push(tops);
    }

    // The caps: the profile's plane where it starts, and that plane
    // screwed on to where it ends.
    for (end, loops) in cap_loops.iter().enumerate() {
        let theta = if end == 0 { 0.0 } else { total };
        let centre = centre_of(model, profile, tol)?;
        let at = screw(centre, theta)?;
        // The profile's plane, turned with it: out of the solid, back
        // against the motion at the start and on with it at the end.
        let normal = {
            let (sin, cos) = (sense * theta).sin_cos();
            let along = z * n.dot(z);
            let square = n - along;
            let turned = along + square * cos + z.cross(square) * sin;
            let forward = if turned.dot(travel(at)) >= 0.0 {
                turned
            } else {
                -turned
            };
            if end == 0 { -forward } else { forward }
        };
        let cap_plane = Plane::through(at, Direction::new(normal, tol)?);
        let mut reach = 1.0_f64;
        for edges in loops {
            for edge in edges {
                let (curve, range) = spine_curve_of(model, edge)?;
                for k in 0..8 {
                    let p =
                        curve.point_at(range.0 + (range.1 - range.0) * f64::from(k) / 8.0, tol)?;
                    reach = reach.max(p.distance(at) * 2.0);
                }
            }
        }
        let surface: SurfaceGeometry =
            PlaneSurface::over(cap_plane, (-reach, reach), (-reach, reach))?.into();
        // The material on the left of each ring about the outward normal:
        // the profile's first ring is its outer one.
        let mut wires = Vec::with_capacity(loops.len());
        for (li, edges) in loops.iter().enumerate() {
            let ring = walked_about(model, edges, normal, li == 0, tol)?;
            wires.push(ogeom_algo::make_wire(model, &ring, tol)?.shape);
        }
        let face = ogeom_algo::make_face(model, surface, &wires, tol)?.shape;
        let cap_id = {
            let Some(ogeom_topo::NodeData::Face(data)) = model.node(&face).map(|n| n.data()) else {
                ogeom_bail!(Construction, "the cap holds no face data");
            };
            data.surface
        };
        let frame = cap_plane.frame();
        for edges in loops {
            for edge in edges {
                let (curve, range) = spine_curve_of(model, edge)?;
                let ogeom_geom::Curve::BSpline(bs) = &curve else {
                    ogeom_bail!(Construction, "a swept ring is not a spline");
                };
                let control2: Vec<Point2> = bs
                    .control_points()
                    .iter()
                    .map(|w| {
                        let local = frame.to_local(w.point());
                        Point2::new(local.x, local.y)
                    })
                    .collect();
                let pcurve: ogeom_geom::PlanarCurve =
                    ogeom_geom::BSpline2d::new(bs.knots().clone(), control2, tol)?.into();
                ogeom_algo::attach_pcurve(
                    model,
                    edge,
                    pcurve,
                    cap_id,
                    ogeom_topo::Location::identity(),
                    range,
                )?;
            }
        }
        faces.push(face);
    }

    let sewn = sew(model, &faces, tol)?;
    if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
        ogeom_bail!(Construction, "the helical sweep did not close");
    }
    let solid = make_solid(model, &sewn.shells)?.shape;
    let mut history = History::new();
    history.generate(profile, solid.clone());
    Ok(Built::new(solid, history))
}

/// Revolve `profile` (a planar face) about `axis`, each point turning the
/// right-handed way about it until its circle first meets the surface of
/// `limit`, a face taken as its whole surface the way
/// [`make_half_space`](ogeom_algo::make_half_space) takes it: the revolution
/// "up to face", stopping on the target at a different angle for each
/// point.
///
/// Built as the half turn of the profile kept on the profile's side of the
/// limit: exact wherever every circle meets the surface within that half
/// turn and does not come back to the profile's side before it ends.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if the
/// profile is not a planar face whose plane holds the axis, a point's
/// circle never meets the surface, or one meets it only past half a turn or
/// crosses it back within the half turn; as the revolution, the half space
/// and the boolean otherwise.
pub fn make_revolution_until(
    model: &mut Model,
    profile: &Shape,
    axis: ogeom_math::Axis,
    limit: &Shape,
    tol: Tolerances,
) -> OgeomResult<Built> {
    use ogeom_geom::Surface as _;
    if model.kind_of(profile)? != ShapeType::Face {
        ogeom_bail!(
            Construction,
            "a revolution up to a face revolves a planar face"
        );
    }
    if model.kind_of(limit)? != ShapeType::Face {
        ogeom_bail!(Construction, "a revolution stops on a face");
    }
    let Some(plane) = ogeom_algo::find_plane(model, profile, tol)? else {
        ogeom_bail!(
            Construction,
            "a revolution up to a face revolves a planar face"
        );
    };
    let z = axis.direction.vector();
    if plane.normal().vector().dot(z).abs() > tol.angular()
        || plane.distance_to(axis.location) > tol.confusion() * 100.0
    {
        ogeom_bail!(
            Construction,
            "the profile's plane does not hold the axis; a revolution up to a \
             face turns a profile about an axis in its own plane"
        );
    }
    // The limit's surface, placed, and which side of it a point stands.
    let (surface, flip) = {
        let Some(data) = model.node(limit).and_then(|n| n.data().as_face()) else {
            ogeom_bail!(Construction, "the limit holds no face data");
        };
        let Some(surface) = model.geometry().surface(data.surface) else {
            ogeom_bail!(Dangling, "the limit's surface is not in this model");
        };
        (
            surface
                .clone()
                .transformed(&limit.transform(model.datums())?, tol)?,
            limit.orientation() == ogeom_topo::Orientation::Reversed,
        )
    };
    let side = |p: Point| -> OgeomResult<f64> {
        let foot = ogeom_algo::project_on_surface(&surface, p, 16, tol)?;
        let (u, v) = foot.parameters;
        let n = surface.normal_at(u, v, tol)?.vector();
        let s = (p - foot.point).dot(n);
        Ok(if flip { -s } else { s })
    };
    // Every boundary point's circle: its first meeting within half a turn,
    // and no return to the profile's side before the half turn ends.
    let turn_of = |p: Point, theta: f64| Transform::rotation(axis, theta).apply(p);
    let mut rings = Vec::new();
    for wire in explore(model, profile, Filter::OfType(ShapeType::Wire))? {
        rings.extend(sample_wire(model, &wire, 64, tol)?);
    }
    let start_side = side(centre_of(model, profile, tol)?)?.signum();
    const STEPS: u32 = 360;
    for p in &rings {
        let mut met: Option<f64> = None;
        for k in 1..=STEPS {
            let theta = core::f64::consts::TAU * f64::from(k) / f64::from(STEPS);
            let here = side(turn_of(*p, theta))?;
            match met {
                None if here.signum() != start_side && here.abs() > tol.confusion() => {
                    met = Some(theta);
                }
                Some(first)
                    if theta <= core::f64::consts::PI
                        && here.signum() == start_side
                        && here.abs() > tol.confusion() =>
                {
                    ogeom_bail!(
                        Construction,
                        "the circle through {p:?} meets the limit at {first} and \
                         crosses back within half a turn; a revolution up to it \
                         is not built there"
                    );
                }
                _ => {}
            }
        }
        match met {
            None => ogeom_bail!(
                Construction,
                "the circle through {p:?} never meets the limit's surface"
            ),
            Some(first) if first > core::f64::consts::PI => ogeom_bail!(
                Construction,
                "the circle through {p:?} meets the limit only past half a turn"
            ),
            _ => {}
        }
    }
    let half = ogeom_algo::make_revolution(model, profile, axis, core::f64::consts::PI, tol)?;
    let inside = centre_of(model, profile, tol)?;
    let bound = ogeom_algo::make_half_space(model, limit, inside, tol)?.shape;
    let mut built = ogeom_bool::common(model, &half.shape, &bound, tol)?;
    built.history.generate(profile, built.shape.clone());
    Ok(built)
}

/// The centroid of a face's outer ring's samples.
fn centre_of(model: &Model, profile: &Shape, tol: Tolerances) -> OgeomResult<Point> {
    let Some(wire) = explore(model, profile, Filter::OfType(ShapeType::Wire))?
        .into_iter()
        .next()
    else {
        ogeom_bail!(Construction, "the profile has no loop");
    };
    let samples = sample_wire(model, &wire, 32, tol)?;
    #[allow(clippy::cast_precision_loss)]
    let n = samples.len() as f64;
    let sum = samples
        .iter()
        .fold(Vector::new(0.0, 0.0, 0.0), |acc, p| acc + p.to_vector());
    Ok(Point::from_vector(sum / n))
}

/// The pipe along a spine of lines and circular arcs meeting tangent to
/// one another, built exactly: down a line the section is extruded, round
/// an arc it is revolved about the arc's axis (the rotation-minimizing
/// frame of a circle is its own rotation), and the legs are fused on the
/// sections they share. Every wall is then the closed form its profile
/// edge sweeps: a plane, drum, cone, ball or torus where the edge is a
/// line or circle. `None` where the spine or profile is not of that kind,
/// for the general construction to take.
fn exact_legs(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    frenet: bool,
    tol: Tolerances,
) -> OgeomResult<Option<Built>> {
    use ogeom_geom::{Curve, Curve3d as _};
    let edges: Vec<Shape> = match model.kind_of(spine)? {
        ShapeType::Edge => vec![spine.clone()],
        ShapeType::Wire => model.ordered_children_of(spine)?,
        _ => return Ok(None),
    };
    let solid = match model.kind_of(profile)? {
        ShapeType::Face => true,
        ShapeType::Wire => false,
        _ => return Ok(None),
    };
    if edges.is_empty() || (!solid && edges.len() > 1) {
        return Ok(None);
    }
    // Each leg: where it starts and ends, its heading at either end, and
    // the motion that carries the section down it.
    struct Leg {
        start: Point,
        heading: (Vector, Vector),
        motion: Transform,
        along: LegKind,
    }
    enum LegKind {
        Line(Vector),
        Arc(ogeom_math::Axis, f64),
    }
    let mut legs = Vec::with_capacity(edges.len());
    for edge in &edges {
        let (curve, range) = spine_curve_of(model, edge)?;
        let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
        let (t0, t1) = if reversed { (range.1, range.0) } else { range };
        let (a, b) = (curve.point_at(t0, tol)?, curve.point_at(t1, tol)?);
        let sense = if reversed { -1.0 } else { 1.0 };
        let heading = (curve.d1_at(t0, tol)? * sense, curve.d1_at(t1, tol)? * sense);
        let basis = match &curve {
            Curve::Trimmed(t) => t.basis().clone(),
            other => other.clone(),
        };
        let (motion, along) = match basis {
            Curve::Line(_) => {
                if frenet {
                    return Ok(None);
                }
                (Transform::translation(b - a), LegKind::Line(b - a))
            }
            Curve::Circle(c) => {
                let frame = c.circle().frame();
                // Turning the way the walk heads at its start.
                let turn = (a - frame.origin()).cross(heading.0);
                let direction = if turn.dot(frame.z().vector()) > 0.0 {
                    frame.z()
                } else {
                    -frame.z()
                };
                let axis = ogeom_math::Axis {
                    location: frame.origin(),
                    direction,
                };
                let angle = (t1 - t0).abs();
                (Transform::rotation(axis, angle), LegKind::Arc(axis, angle))
            }
            _ => return Ok(None),
        };
        legs.push(Leg {
            start: a,
            heading,
            motion,
            along,
        });
    }
    // Legs meet tangent, or all are straight and their corners are mitred
    // exactly below; any other corner is mitred by the general path.
    let cornered = legs.windows(2).any(|pair| {
        let (x, y) = (pair[0].heading.1, pair[1].heading.0);
        x.cross(y).magnitude() > tol.angular() * x.magnitude() * y.magnitude() || x.dot(y) <= 0.0
    });
    if cornered {
        let lines: Option<Vec<(Point, Vector)>> = legs
            .iter()
            .map(|leg| match leg.along {
                LegKind::Line(v) => Some((leg.start, v)),
                LegKind::Arc(..) => None,
            })
            .collect();
        return match lines {
            Some(lines) if solid && !frenet => mitred_lines(model, profile, spine, &lines, tol),
            _ => Ok(None),
        };
    }
    // The profile square to the spine's exact start tangent, and on it.
    let Some(plane) = ogeom_algo::find_plane(model, profile, tol)? else {
        return Ok(None);
    };
    let t0 = legs[0].heading.0;
    if plane.normal().vector().cross(t0).magnitude() > tol.angular() * t0.magnitude()
        || plane.distance_to(legs[0].start) > tol.confusion() * 100.0
    {
        return Ok(None);
    }

    let mut joined: Vec<Shape> = Vec::new();
    let mut carried = Transform::IDENTITY;
    for leg in &legs {
        // Rebuilt even where it stands: the caps are this face, and it
        // carries its trims on its own plane.
        let heading = carried.apply_vector(legs[0].heading.0);
        let section = realized_profile_wound(model, profile, &carried, Some(heading), tol)?;
        let piece = match leg.along {
            LegKind::Line(v) => ogeom_algo::make_prism(model, &section, v, tol)?.shape,
            LegKind::Arc(axis, angle) => {
                ogeom_algo::make_revolution(model, &section, axis, angle, tol)?.shape
            }
        };
        carried = leg.motion * carried;
        joined.push(piece);
    }
    let result = fuse_in_order(model, joined, tol)?;
    Ok(result.map(|shape| {
        let mut history = History::new();
        history.generate(spine, shape.clone());
        history.generate(profile, shape.clone());
        Built::new(shape, history)
    }))
}

/// A face swept down a spine of straight legs with corners, exactly: each
/// leg is the profile's prism, run on past its corners and trimmed by the
/// mitre plane that halves each corner, and the pieces are fused. The
/// section turns at each corner by the least rotation taking one leg's
/// heading to the next's, as the rotation-minimizing frame does, and every
/// wall is the closed form its profile edge sweeps along a line.
///
/// `None` where the spine closes on itself (a ring's section may come back
/// turned, which the general construction settles), a corner all but
/// doubles back, or a leg is too short for the corners at its ends to trim
/// it apart.
fn mitred_lines(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    legs: &[(Point, Vector)],
    tol: Tolerances,
) -> OgeomResult<Option<Built>> {
    if let (Some(first), Some(last)) = (legs.first(), legs.last())
        && first.0.distance(last.0 + last.1) <= tol.confusion() * 100.0
    {
        return Ok(None);
    }
    let bounds = ogeom_algo::shape_bounds(model, profile, tol)?;
    let (Some(low), Some(high)) = (bounds.low(), bounds.high()) else {
        return Ok(None);
    };
    let width = low.distance(high);
    let unit = |v: Vector| v / v.magnitude();
    // Each corner's mitre: its point and the normal of the plane halving it,
    // pointing on along the next leg.
    let mut mitres: Vec<(Point, Vector)> = Vec::with_capacity(legs.len().saturating_sub(1));
    for pair in legs.windows(2) {
        let (d0, d1) = (unit(pair[0].1), unit(pair[1].1));
        // A corner turning past a right angle and a half reaches too far
        // along its legs for the mitre to stay on them.
        if d0.dot(d1) < -0.7 {
            return Ok(None);
        }
        mitres.push((pair[1].0, unit(d0 + d1)));
    }
    // How far a section reaches along its leg from a corner's mitre.
    let reach = width * 2.0;
    for (i, (_, v)) in legs.iter().enumerate() {
        let corners = f64::from(u8::from(i > 0) + u8::from(i + 1 < legs.len()));
        if v.magnitude() <= reach * corners * 0.5 {
            return Ok(None);
        }
    }

    let mut carried = Transform::IDENTITY;
    let mut joined: Vec<Shape> = Vec::new();
    for (i, &(_, v)) in legs.iter().enumerate() {
        let d = unit(v);
        let before = if i > 0 { reach } else { 0.0 };
        let after = if i + 1 < legs.len() { reach } else { 0.0 };
        let section = realized_profile_wound(
            model,
            profile,
            &(Transform::translation(-d * before) * carried),
            Some(d),
            tol,
        )?;
        let mut piece =
            ogeom_algo::make_prism(model, &section, v + d * (before + after), tol)?.shape;
        // Trimmed back to the mitres at either end.
        for (at, normal, keep_ahead) in [
            (i > 0).then(|| (mitres[i - 1].0, mitres[i - 1].1, true)),
            (i + 1 < legs.len()).then(|| (mitres[i].0, mitres[i].1, false)),
        ]
        .into_iter()
        .flatten()
        {
            let plane = Plane::through(at, Direction::new(normal, tol)?);
            let face = ogeom_algo::make_natural_face(
                model,
                SurfaceGeometry::Plane(ogeom_geom::PlaneSurface::over(
                    plane,
                    (-reach * 4.0 - width, reach * 4.0 + width),
                    (-reach * 4.0 - width, reach * 4.0 + width),
                )?),
            )?
            .shape;
            let side = if keep_ahead { normal } else { -normal };
            let half = ogeom_algo::make_half_space(model, &face, at + side * width, tol)?.shape;
            piece = ogeom_bool::common(model, &piece, &half, tol)?.shape;
        }
        // On to the next leg: along this one, then turned at the corner by
        // the least rotation between the headings.
        carried = Transform::translation(v) * carried;
        if let Some(&(corner, next)) = legs.get(i + 1) {
            let n = unit(next);
            let axis = d.cross(n);
            if axis.magnitude() > tol.angular() {
                let angle = d.dot(n).clamp(-1.0, 1.0).acos();
                let rotation = Transform::rotation(
                    ogeom_math::Axis {
                        location: corner,
                        direction: Direction::new(axis, tol)?,
                    },
                    angle,
                );
                carried = rotation * carried;
            }
        }
        joined.push(piece);
    }
    let result = fuse_in_order(model, joined, tol)?;
    Ok(result.map(|shape| {
        let mut history = History::new();
        history.generate(spine, shape.clone());
        history.generate(profile, shape.clone());
        Built::new(shape, history)
    }))
}

/// Sweep a planar profile (a wire, or a face whose holes ride along)
/// down an arbitrary spine, one skinned wall per profile loop.
///
/// The spine may be a single edge or a wire of edges of any curve the
/// vocabulary evaluates: lines, arcs, splines, helices. Frames along it are
/// rotation-minimizing by default (the double-reflection construction), so
/// the profile neither twists nor kinks where the spine bends; `frenet`
/// asks for the Frenet frame instead, which turns with the spine's own
/// curvature, the law a thread wants. Stations are placed by each edge's
/// own turning, the skin holds every transported section to `tolerance`
/// (along the profile between its samples as well as at them, the
/// sampling refined where the skin misses), and the caps sit
/// perpendicular to the spine's ends, holes and all.
///
/// Each spine edge skins its own run of wall, and neighbouring runs share
/// the section where their edges meet, so a join where the curvature steps
/// (an arc running on into its tangent line) is followed exactly rather
/// than smoothed by one fit across it. A run whose sections all lie in one
/// plane is that plane.
///
/// A sharp corner is mitred. Between straight legs the mitre is a plane and
/// each wall is sheared onto it; where a leg is curved the two legs' walls
/// end on the crossing of their generators (each profile point's own path
/// down either leg, run straight on past the corner), which is exact where
/// the corner turns in the leg's plane. Where it turns a curved leg out of
/// its plane the generators miss, and the spine is swept in pieces instead:
/// each side runs on straight past the corner, is trimmed by the mitre
/// plane, and the pieces are fused, the difference between their sections
/// standing as a face of the mitre plane.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if the
/// profile is not planar, leans along the spine, or does not sit at the
/// spine's start; if `frenet` is asked of a spine that never bends, or of a
/// cornered one; if a wire (not a face) is swept round a corner that turns
/// a curved leg out of its plane, which only solid pieces can mitre; if the
/// spine all but doubles back at a corner; or if a leg is shorter than its
/// corner's reach.
/// [`OgeomError::NotDone`](ogeom_core::OgeomError::NotDone) if the skin
/// cannot reach the tolerance.
pub fn make_pipe_shell(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    frenet: bool,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    let law = if frenet {
        PipeLaw::Frenet
    } else {
        PipeLaw::RotationMinimizing
    };
    make_pipe_shell_with(
        model,
        profile,
        spine,
        &law,
        PipeCorners::Mitre,
        tolerance,
        tol,
    )
}

/// How a pipe's section turns about its spine.
#[derive(Debug, Clone, Copy)]
pub enum PipeLaw<'a> {
    /// Double-reflection rotation-minimizing frames: the section neither
    /// twists nor kinks where the spine bends.
    RotationMinimizing,
    /// The Frenet frame, turning with the spine's own curvature.
    Frenet,
    /// The section's normal axis points at `guide`, a curve running beside
    /// the spine: at each station, where the guide crosses the plane square
    /// to the spine there.
    Auxiliary {
        /// An edge or wire beside the spine.
        guide: &'a Shape,
    },
    /// The section keeps this direction as its binormal, square to the
    /// spine's tangent.
    Binormal(Direction),
    /// The section keeps the frame it has at the spine's start all the
    /// way: carried by translation along the spine, never turned.
    Fixed,
}

/// How a pipe turns a sharp corner of its spine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PipeCorners {
    /// The walls sheared onto the plane halving the corner.
    #[default]
    Mitre,
    /// Each leg runs on straight past the corner until its section clears
    /// the other leg's far side, and the legs are fused: the outside of the
    /// corner square.
    Extended,
    /// Each leg ends square at the corner and the section turns about the
    /// corner through its angle, joining the two ends: the outside of the
    /// corner rounded.
    Round,
}

/// [`make_pipe_shell`] with a frame law: the section turns about the spine
/// the way `law` says.
///
/// # Errors
///
/// As [`make_pipe_shell_with`].
pub fn make_pipe_shell_law(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    law: PipeLaw<'_>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    make_pipe_shell_with(
        model,
        profile,
        spine,
        &law,
        PipeCorners::Mitre,
        tolerance,
        tol,
    )
}

/// [`make_pipe_shell`] with a frame law and a way of turning corners.
///
/// The auxiliary and binormal laws sweep an open spine with no sharp
/// corner. Extended and round corners are built for a face swept down an
/// open spine of straight legs with the rotation-minimizing frame, each
/// leg a prism of the section and each round corner the section revolved
/// about the corner; on a spine with no sharp corner every way of turning
/// corners is the same solid.
///
/// # Errors
///
/// As [`make_pipe_shell`], and
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) where
/// the law or the corners are asked of a spine they do not serve, the guide
/// does not cross a station's plane, or the spine's tangent runs along the
/// binormal or toward the guide.
#[allow(clippy::too_many_arguments)]
pub fn make_pipe_shell_with(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    law: &PipeLaw<'_>,
    corners: PipeCorners,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    // A section carried by translation turns no corner: every way of
    // turning one is the same solid.
    if matches!(law, PipeLaw::Fixed) {
        return crate::fixed::fixed_pipe(model, profile, spine, tol);
    }
    if corners != PipeCorners::Mitre
        && let Some(legs) = straight_legs(model, spine, tol)?
        && legs.len() > 1
    {
        if !matches!(law, PipeLaw::RotationMinimizing) {
            ogeom_bail!(
                Construction,
                "extended and round corners turn the section with the \
                 rotation-minimizing frame"
            );
        }
        if model.kind_of(profile)? != ShapeType::Face {
            ogeom_bail!(Construction, "extended and round corners sweep a face");
        }
        return cornered_lines(model, profile, spine, &legs, corners, tol);
    }
    if corners != PipeCorners::Mitre && has_sharp_corner(model, spine, tol)? {
        ogeom_bail!(
            Construction,
            "extended and round corners are built along a spine of straight legs"
        );
    }
    pipe_shell_law(model, profile, spine, law, tolerance, tol)
}

/// The legs of a spine made only of straight edges, in order, each as its
/// start and its displacement; `None` where any edge is curved.
fn straight_legs(
    model: &Model,
    spine: &Shape,
    tol: Tolerances,
) -> OgeomResult<Option<Vec<(Point, Vector)>>> {
    use ogeom_geom::Curve;
    let edges: Vec<Shape> = match model.kind_of(spine)? {
        ShapeType::Edge => vec![spine.clone()],
        ShapeType::Wire => model.ordered_children_of(spine)?,
        _ => return Ok(None),
    };
    let mut legs = Vec::with_capacity(edges.len());
    for edge in &edges {
        let (curve, range) = spine_curve_of(model, edge)?;
        let basis = match &curve {
            Curve::Trimmed(t) => t.basis().clone(),
            other => other.clone(),
        };
        if !matches!(basis, Curve::Line(_)) {
            return Ok(None);
        }
        let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
        let (t0, t1) = if reversed { (range.1, range.0) } else { range };
        let (a, b) = (curve.point_at(t0, tol)?, curve.point_at(t1, tol)?);
        legs.push((a, b - a));
    }
    Ok(Some(legs))
}

/// Whether the spine turns sharply anywhere between its edges.
pub(crate) fn has_sharp_corner(model: &Model, spine: &Shape, tol: Tolerances) -> OgeomResult<bool> {
    let stations = shell_stations(model, spine, tol)?;
    Ok((0..stations.len() - 1).any(|i| {
        stations[i].at.distance(stations[i + 1].at) <= tol.confusion()
            && (stations[i]
                .tangent
                .cross(stations[i + 1].tangent)
                .magnitude()
                > tol.angular()
                || stations[i].tangent.dot(stations[i + 1].tangent) < 0.0)
    }))
}

/// A face down an open spine of straight legs with extended or round
/// corners: each leg the prism of its section, run on past its corners
/// for extended ones, and each round corner the section revolved about the
/// corner through its turn; the pieces fused.
fn cornered_lines(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    legs: &[(Point, Vector)],
    corners: PipeCorners,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if let (Some(first), Some(last)) = (legs.first(), legs.last())
        && first.0.distance(last.0 + last.1) <= tol.confusion() * 100.0
    {
        ogeom_bail!(
            Construction,
            "extended and round corners are built along an open spine"
        );
    }
    let unit = |v: Vector| v / v.magnitude();
    let Some(outer) = explore(model, profile, Filter::OfType(ShapeType::Wire))?
        .into_iter()
        .next()
    else {
        ogeom_bail!(Construction, "the profile has no loop");
    };
    let samples = sample_wire(model, &outer, 256, tol)?;
    // The motion carrying the profile to each leg's start: along the legs
    // before it, turned at each corner by the least rotation between the
    // headings.
    let mut carried: Vec<Transform> = Vec::with_capacity(legs.len());
    let mut turns: Vec<Option<(ogeom_math::Axis, f64)>> = Vec::with_capacity(legs.len());
    let mut motion = Transform::IDENTITY;
    for (i, &(_, v)) in legs.iter().enumerate() {
        carried.push(motion);
        motion = Transform::translation(v) * motion;
        let turn = match legs.get(i + 1) {
            Some(&(corner, next)) => {
                let (d, n) = (unit(v), unit(next));
                if d.dot(n) < -0.7 {
                    ogeom_bail!(
                        Construction,
                        "the spine all but doubles back at a corner; no corner \
                         of that kind turns it"
                    );
                }
                let axis = d.cross(n);
                if axis.magnitude() > tol.angular() {
                    let about = ogeom_math::Axis {
                        location: corner,
                        direction: Direction::new(axis, tol)?,
                    };
                    let angle = d.dot(n).clamp(-1.0, 1.0).acos();
                    motion = Transform::rotation(about, angle) * motion;
                    Some((about, angle))
                } else {
                    None
                }
            }
            None => None,
        };
        turns.push(turn);
    }
    // How far each leg runs on past a corner for an extended corner: until
    // its section passes the far side of the other leg's section there.
    let reach_past = |section: &Transform, corner: Point, along: Vector, turn: f64| {
        let far = samples
            .iter()
            .map(|p| (section.apply(*p) - corner).dot(along))
            .fold(0.0_f64, f64::max);
        far / turn.sin().max(1e-3)
    };
    let mut joined: Vec<Shape> = Vec::new();
    for (i, &(_, v)) in legs.iter().enumerate() {
        let d = unit(v);
        let (mut before, mut after) = (0.0, 0.0);
        if corners == PipeCorners::Extended {
            if i > 0
                && let Some((_, angle)) = turns[i - 1]
            {
                // The previous leg's section at the corner, reaching back.
                let at_corner = Transform::translation(legs[i - 1].1) * carried[i - 1];
                before = reach_past(&at_corner, legs[i].0, -d, angle);
            }
            if let Some((_, angle)) = turns[i] {
                // The next leg's section at the corner, reaching on.
                after = reach_past(&carried[i + 1], legs[i + 1].0, d, angle);
            }
        }
        let section = realized_profile_wound(
            model,
            profile,
            &(Transform::translation(-d * before) * carried[i]),
            Some(d),
            tol,
        )?;
        let mut piece =
            ogeom_algo::make_prism(model, &section, v + d * (before + after), tol)?.shape;
        if corners == PipeCorners::Round
            && let Some((axis, angle)) = turns[i]
        {
            let end = realized_profile_wound(
                model,
                profile,
                &(Transform::translation(v) * carried[i]),
                Some(d),
                tol,
            )?;
            // The half of the section inside the turn sweeps within the two
            // legs; the half outside it turns the corner's round. It
            // touches the axis along its cut, which the revolution takes.
            let next = unit(legs[i + 1].1);
            let inward = next - d * next.dot(d);
            let outer = outside_half(model, &end, axis.location, d, -inward, tol)?;
            let bend = ogeom_algo::make_revolution(model, &outer, axis, angle, tol)?.shape;
            piece = ogeom_bool::fuse(model, &piece, &bend, tol)?.shape;
        }
        joined.push(piece);
    }
    let result = fuse_in_order(model, joined, tol)?;
    let Some(shape) = result else {
        ogeom_bail!(Construction, "the spine has no leg");
    };
    let mut history = History::new();
    history.generate(spine, shape.clone());
    history.generate(profile, shape.clone());
    Ok(Built::new(shape, history))
}

/// The part of a planar section lying on the `outward` side of the line
/// through `at` square to it in the section's plane (whose normal is
/// `normal`), as a face on that plane: the section's slab kept on that
/// side by a half space, and the slab's face on the section's plane.
fn outside_half(
    model: &mut Model,
    section: &Shape,
    at: Point,
    normal: Vector,
    outward: Vector,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    let width = {
        let bounds = ogeom_algo::shape_bounds(model, section, tol)?;
        match (bounds.low(), bounds.high()) {
            (Some(a), Some(b)) => a.distance(b),
            _ => ogeom_bail!(Construction, "the section has no extent"),
        }
    };
    let n = normal / normal.magnitude();
    let slab = ogeom_algo::make_prism(model, section, n * width, tol)?.shape;
    let cut = Plane::through(at, Direction::new(outward, tol)?);
    let face = ogeom_algo::make_natural_face(
        model,
        SurfaceGeometry::Plane(ogeom_geom::PlaneSurface::over(
            cut,
            (-width * 4.0, width * 4.0),
            (-width * 4.0, width * 4.0),
        )?),
    )?
    .shape;
    let side = outward / outward.magnitude() * width;
    let half = ogeom_algo::make_half_space(model, &face, at + side, tol)?.shape;
    let kept = ogeom_bool::common(model, &slab, &half, tol)?.shape;
    for face in explore(model, &kept, Filter::OfType(ShapeType::Face))? {
        let Ok((point, facing)) = ogeom_algo::face_normal(model, &face, tol) else {
            continue;
        };
        if (point - at).dot(n).abs() <= tol.confusion() * 100.0
            && facing.cross(n).magnitude() <= tol.angular() * 10.0
        {
            // Facing along the section's own normal, as the section does.
            return Ok(if facing.dot(n) > 0.0 {
                face
            } else {
                face.reversed()
            });
        }
    }
    ogeom_bail!(
        Construction,
        "the section has no part outside the corner's axis to turn"
    )
}

/// Stations added between neighbours on one edge wherever a law's frame
/// turns by more than a few degrees between them: a straight spine has
/// stations only at its ends, and a section twisting down it would be
/// skinned straight across.
fn densified(
    model: &Model,
    spine: &Shape,
    stations: Vec<SpineStation>,
    law: &PipeLaw<'_>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Vec<SpineStation>> {
    const MOST: f64 = 0.05;
    let edges: Vec<Shape> = match model.kind_of(spine)? {
        ShapeType::Edge => vec![spine.clone()],
        ShapeType::Wire => model.ordered_children_of(spine)?,
        _ => return Ok(stations),
    };
    let mut curves = Vec::with_capacity(edges.len());
    for edge in &edges {
        curves.push(spine_curve_of(model, edge)?.0);
    }
    let mut stations = stations;
    for _ in 0..12 {
        let normals = law_normals(model, &stations, law, tolerance, tol)?;
        let mut out: Vec<SpineStation> = Vec::with_capacity(stations.len() * 2);
        let mut added = false;
        for i in 0..stations.len() {
            out.push(stations[i]);
            let Some(next) = stations.get(i + 1) else {
                continue;
            };
            let here = stations[i];
            if here.edge != next.edge || here.at.distance(next.at) <= tol.confusion() {
                continue;
            }
            let turn = normals[i].dot(normals[i + 1]).clamp(-1.0, 1.0).acos();
            if turn <= MOST {
                continue;
            }
            let curve = &curves[here.edge];
            let t = f64::midpoint(here.t, next.t);
            let d = curve.d1_at(t, tol)?;
            let sense = if curve.d1_at(here.t, tol)?.dot(here.tangent) >= 0.0 {
                1.0
            } else {
                -1.0
            };
            out.push(SpineStation {
                at: curve.point_at(t, tol)?,
                tangent: d * sense / d.magnitude(),
                edge: here.edge,
                t,
            });
            added = true;
        }
        stations = out;
        if !added {
            break;
        }
        // A law whose frame jumps (a guide's nearest point switching
        // branch) never settles: each round doubles the stations at the
        // jump. Past this many the skin is refused, not grown.
        if stations.len() > MOST_STATIONS {
            ogeom_bail!(
                NotDone,
                "the frame law turns faster than {MOST_STATIONS} sections can follow; \
                 it jumps somewhere along the spine"
            );
        }
    }
    Ok(stations)
}

/// The most sections a law pipe's skin is built through.
const MOST_STATIONS: usize = 2048;

/// The frame a law gives at a station: the spine's tangent as its `z`, the
/// law's normal as its `x`.
pub(crate) fn station_frame(
    station: &SpineStation,
    normal: Vector,
    tol: Tolerances,
) -> OgeomResult<Frame> {
    Frame::new(
        station.at,
        Direction::new(station.tangent, tol)?,
        Direction::new(normal, tol)?,
        tol,
    )
}

/// A copy of a closed wire moved by `motion`, its curves restated where
/// they land rather than placed: every edge in the wire's order and sense,
/// on vertices shared end to end.
fn moved_ring(
    model: &mut Model,
    ring: &Shape,
    motion: &Transform,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    let edges = model.ordered_children_of(ring)?;
    let mut vertices: Vec<(Point, Shape)> = Vec::new();
    let mut vertex = |model: &mut Model, at: Point| -> Shape {
        if let Some((_, v)) = vertices
            .iter()
            .find(|(p, _)| p.distance(at) <= tol.confusion() * 10.0)
        {
            return v.clone();
        }
        let v = ogeom_algo::make_vertex(model, at).shape;
        vertices.push((at, v.clone()));
        v
    };
    let mut moved = Vec::with_capacity(edges.len());
    for edge in &edges {
        let (curve, range) = spine_curve_of(model, edge)?;
        let placement = edge.transform(model.datums())?;
        let curve = curve.transformed(&(*motion * placement), tol)?;
        let (a, b) = (curve.point_at(range.0, tol)?, curve.point_at(range.1, tol)?);
        let (va, vb) = (vertex(model, a), vertex(model, b));
        let built = ogeom_algo::make_edge_between(model, curve, range, &va, &vb, tol)?.shape;
        moved.push(if edge.orientation() == ogeom_topo::Orientation::Reversed {
            built.reversed()
        } else {
            built
        });
    }
    Ok(ogeom_algo::make_wire(model, &moved, tol)?.shape)
}

/// A profile swept under a law that turns it about the spine, as the loft
/// through its outer ring placed at every station by the law's frame: the
/// section keeps the place it has in the frame at the spine's start.
#[allow(clippy::too_many_arguments)]
fn law_loft(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    stations: &[SpineStation],
    law: &PipeLaw<'_>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    let rings: Vec<Shape> = match model.kind_of(profile)? {
        ShapeType::Face => model.ordered_children_of(profile)?,
        ShapeType::Wire => vec![profile.clone()],
        _ => ogeom_bail!(Construction, "a pipe sweeps a planar face or wire"),
    };
    if rings.len() != 1 {
        ogeom_bail!(
            Construction,
            "an auxiliary or binormal law sweeps a profile with no hole"
        );
    }
    let normals = law_normals(model, stations, law, tolerance, tol)?;
    let start = station_frame(&stations[0], normals[0], tol)?;
    let mut kept: Vec<SpineStation> = Vec::with_capacity(stations.len());
    let mut kept_normals: Vec<Vector> = Vec::with_capacity(stations.len());
    let mut sections: Vec<Shape> = Vec::with_capacity(stations.len());
    for (station, normal) in stations.iter().zip(&normals) {
        if kept
            .last()
            .is_some_and(|p| p.at.distance(station.at) <= tol.confusion())
        {
            continue;
        }
        kept.push(*station);
        kept_normals.push(*normal);
        let frame = station_frame(station, *normal, tol)?;
        let motion = Transform::from_frame(&frame) * Transform::to_frame(&start);
        sections.push(moved_ring(model, &rings[0], &motion, tol)?);
    }
    // Between two stations the spine is read off its curve and the law
    // asked for its normal there, as at a station.
    let walk = SpineWalk {
        curves: walk_curves(model, spine)?,
        stations: &kept,
        normals: &kept_normals,
    };
    let held: std::cell::RefCell<ogeom_core::FastMap<u64, Transform>> =
        std::cell::RefCell::default();
    let guide = guide_curves(model, law)?;
    let motion = |s: f64| -> OgeomResult<Transform> {
        if let Some(m) = held.borrow().get(&s.to_bits()) {
            return Ok(*m);
        }
        let (at, tangent, _) = walk.frame_at(s, (0, kept.len() - 1), tol)?;
        let here = SpineStation {
            at,
            tangent,
            ..kept[0]
        };
        let normal = law_normals_on(&guide, &[here], law, tolerance, tol)?[0];
        let frame = station_frame(&here, normal, tol)?;
        let m = Transform::from_frame(&frame) * Transform::to_frame(&start);
        held.borrow_mut().insert(s.to_bits(), m);
        Ok(m)
    };
    let mut built = loft_skinned_along(model, &sections, Some(&motion), tolerance, tol)?;
    built.history.generate(spine, built.shape.clone());
    built.history.generate(profile, built.shape.clone());
    Ok(built)
}

/// Sweep several planar sections down one spine, the section changing
/// shape along the path: a multisection pipe.
///
/// Each section stands where the spine crosses its plane, and is read in
/// the spine's moving frame there (rotation-minimizing, or Frenet where
/// `frenet` asks). Between two sections the section is blended in that
/// frame by the length run along the spine, matched point to point from
/// each section's own start, so the result follows the spine rather than
/// the chord between the sections. The sections are closed wires, or
/// faces without holes; the ends are capped. The first or last section may
/// be a vertex where the spine starts or ends: the pipe closes to that
/// point, uncapped there.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if
/// there are fewer than two sections, a section is not planar or has a
/// hole, the spine does not cross a section's plane, or the sections stand
/// out of order along the spine;
/// [`OgeomError::NotDone`](ogeom_core::OgeomError::NotDone) if the skin
/// cannot reach `tolerance`.
pub fn make_pipe_sections(
    model: &mut Model,
    sections: &[Shape],
    spine: &Shape,
    frenet: bool,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    const AROUND: usize = 64;
    if sections.len() < 2 {
        ogeom_bail!(
            Construction,
            "a multisection pipe needs at least two sections"
        );
    }
    let law = if frenet {
        PipeLaw::Frenet
    } else {
        PipeLaw::RotationMinimizing
    };
    let stations = shell_stations(model, spine, tol)?;
    let stations = evenly(model, spine, stations, 24, false, tol)?;
    let normals = law_normals(model, &stations, &law, tolerance, tol)?;
    // Length run along the spine at each station.
    let mut run = vec![0.0_f64];
    for pair in stations.windows(2) {
        let held = run[run.len() - 1];
        run.push(held + pair[0].at.distance(pair[1].at));
    }
    // Each section: where along the spine it stands, and its samples in
    // the frame there.
    // Each section where it stands along the spine, read by arc length in
    // its own frame, and its samples there for the next to match.
    let mut placed: Vec<(f64, Section, Vec<Point>)> = Vec::with_capacity(sections.len());
    // A point section: where it stands, and whether at the spine's end.
    let mut apex: Option<(Point, bool)> = None;
    // The last section's ring read, for the straight pipe to a point.
    let mut last_ring: Option<Shape> = None;
    for (index, section) in sections.iter().enumerate() {
        if model.kind_of(section)? == ShapeType::Vertex {
            let Some(data) = model.node(section).and_then(|n| n.data().as_vertex()) else {
                ogeom_bail!(Dangling, "vertex is not in this model");
            };
            let point = section.transform(model.datums())?.apply(data.point);
            let reach = tolerance.max(tol.confusion() * 1e3);
            let (Some(head), Some(tail)) = (stations.first(), stations.last()) else {
                ogeom_bail!(Construction, "the spine has no stations");
            };
            let at_end = if index + 1 == sections.len() && point.distance(tail.at) <= reach {
                true
            } else if index == 0 && point.distance(head.at) <= reach {
                false
            } else {
                ogeom_bail!(
                    Construction,
                    "a point section stands first or last, where the spine \
                     starts or ends"
                );
            };
            apex = Some((point, at_end));
            // Every sample at the frame's origin: the section shrinks onto
            // the spine there.
            let along = if at_end { run[run.len() - 1] } else { 0.0 };
            placed.push((
                along,
                Section::Point(Point::ORIGIN),
                vec![Point::ORIGIN; AROUND],
            ));
            continue;
        }
        let ring = match model.kind_of(section)? {
            ShapeType::Face => {
                let rings = model.ordered_children_of(section)?;
                if rings.len() != 1 {
                    ogeom_bail!(Construction, "a multisection pipe's section has no hole");
                }
                rings[0].clone()
            }
            ShapeType::Wire => section.clone(),
            _ => ogeom_bail!(
                Construction,
                "a section is a planar face or wire, or a point at an end"
            ),
        };
        let Some(plane) = ogeom_algo::find_plane(model, &ring, tol)? else {
            ogeom_bail!(Construction, "a section is not planar");
        };
        last_ring = Some(ring.clone());
        let side = |p: Point| (p - plane.origin()).dot(plane.normal().vector());
        let mut found: Option<(f64, usize, f64)> = None;
        for i in 0..stations.len() {
            let here = side(stations[i].at);
            let crossing = if here.abs() <= tol.confusion() {
                Some((run[i], i, 0.0))
            } else if let Some(next) = stations.get(i + 1) {
                let there = side(next.at);
                (here.signum() != there.signum() && there.abs() > tol.confusion()).then(|| {
                    let f = here / (here - there);
                    (run[i] + (run[i + 1] - run[i]) * f, i, f)
                })
            } else {
                None
            };
            if crossing.is_some() {
                found = crossing;
                break;
            }
        }
        let Some((along, i, f)) = found else {
            ogeom_bail!(Construction, "the spine does not cross a section's plane");
        };
        // The frame there, between the two stations it falls between.
        let j = (i + 1).min(stations.len() - 1);
        let at = stations[i].at + (stations[j].at - stations[i].at) * f;
        let tangent = stations[i].tangent * (1.0 - f) + stations[j].tangent * f;
        let normal = normals[i] * (1.0 - f) + normals[j] * f;
        let normal = normal - tangent * normal.dot(tangent) / tangent.dot(tangent);
        let frame = Frame::new(
            at,
            Direction::new(tangent, tol)?,
            Direction::new(normal, tol)?,
            tol,
        )?;
        let into = Transform::to_frame(&frame);
        let dense: Vec<Point> = dense_wire(model, &ring, tol)?
            .iter()
            .map(|p| into.apply(*p))
            .collect();
        let around = match placed.last() {
            Some((_, _, previous)) => matched_loop(&dense, AROUND, previous),
            None => ArcLoop::new(dense),
        };
        let samples = fractions(AROUND)[..AROUND]
            .iter()
            .map(|f| around.at(*f))
            .collect();
        placed.push((along, Section::Loop(around), samples));
    }
    for pair in placed.windows(2) {
        if pair[1].0 <= pair[0].0 + tol.confusion() {
            ogeom_bail!(
                Construction,
                "the sections stand out of order along the spine"
            );
        }
    }
    // One section closing to a point down a straight spine: every sample
    // runs straight to the point, which is the exact pyramid or cone over
    // the section.
    if let (Some((point, _)), Some(ring), 2) = (apex, &last_ring, sections.len())
        && straight_legs(model, spine, tol)?.is_some_and(|legs| legs.len() == 1)
    {
        let tip = model.add_vertex(VertexData::new(point));
        let mut built = make_loft(model, ring, &tip, tol)?;
        built.history.generate(spine, built.shape.clone());
        for section in sections {
            built.history.generate(section, built.shape.clone());
        }
        return Ok(built);
    }
    // A ring at every station from the first section's to the last's, the
    // two sections either side blended by the length between them.
    let (first, last) = (placed[0].0, placed[placed.len() - 1].0);
    let mut rings: Vec<Shape> = Vec::new();
    let mut ring_at = |model: &mut Model, along: f64, frame: &Frame| -> OgeomResult<()> {
        let k = placed
            .windows(2)
            .position(|w| along <= w[1].0 + tol.confusion())
            .unwrap_or(placed.len() - 2);
        let (a, b) = (&placed[k], &placed[k + 1]);
        let f = ((along - a.0) / (b.0 - a.0)).clamp(0.0, 1.0);
        let out = Transform::from_frame(frame);
        // The blend round at a fraction of each section's length, held to
        // its share of the tolerance between the samples as well as at
        // them.
        let target = tolerance * 0.1;
        let fitted = ogeom_geom::fit::fit_curve_sampled(
            |g| {
                let (p, q) = (a.1.at(g), b.1.at(g));
                Ok(out.apply(p + (q - p) * f))
            },
            &fractions(AROUND),
            true,
            3,
            target,
            tol,
        )?;
        if !fitted.met {
            ogeom_bail!(
                NotDone,
                "a blended section reached {} against a target of {target}",
                fitted.error
            );
        }
        let curve: ogeom_geom::Curve = fitted.curve.into();
        let range = curve.domain();
        let edge = ogeom_algo::make_edge(model, curve, range, tol)?.shape;
        rings.push(ogeom_algo::make_wire(model, &[edge], tol)?.shape);
        Ok(())
    };
    let frame_at = |i: usize| station_frame(&stations[i], normals[i], tol);
    // The first section's own station, the stations strictly between, and
    // the last section's.
    let at_along = |along: f64| -> OgeomResult<Frame> {
        let i = run
            .windows(2)
            .position(|w| along <= w[1] + tol.confusion())
            .unwrap_or(run.len() - 2);
        let f = ((along - run[i]) / (run[i + 1] - run[i]).max(f64::MIN_POSITIVE)).clamp(0.0, 1.0);
        let at = stations[i].at + (stations[i + 1].at - stations[i].at) * f;
        let tangent = stations[i].tangent * (1.0 - f) + stations[i + 1].tangent * f;
        let normal = normals[i] * (1.0 - f) + normals[i + 1] * f;
        let normal = normal - tangent * normal.dot(tangent) / tangent.dot(tangent);
        Frame::new(
            at,
            Direction::new(tangent, tol)?,
            Direction::new(normal, tol)?,
            tol,
        )
    };
    // The end a point section stands at has no ring: the skin closes on the
    // point itself, which the loft takes last.
    if apex.is_none_or(|(_, at_end)| at_end) {
        ring_at(model, first, &at_along(first)?)?;
    }
    for (i, &along) in run.iter().enumerate() {
        if along > first + tol.confusion() && along < last - tol.confusion() {
            ring_at(model, along, &frame_at(i)?)?;
        }
    }
    if apex.is_none_or(|(_, at_end)| !at_end) {
        ring_at(model, last, &at_along(last)?)?;
    }
    if let Some((point, at_end)) = apex {
        if !at_end {
            rings.reverse();
        }
        rings.push(model.add_vertex(VertexData::new(point)));
    }
    let mut built = make_loft_skinned(model, &rings, tolerance, tol)?;
    built.history.generate(spine, built.shape.clone());
    for section in sections {
        built.history.generate(section, built.shape.clone());
    }
    Ok(built)
}

/// Stations added so every edge of the spine holds at least `count`
/// stations evenly along its parameter, besides the ones it has.
fn evenly(
    model: &Model,
    spine: &Shape,
    stations: Vec<SpineStation>,
    count: u32,
    keep: bool,
    tol: Tolerances,
) -> OgeomResult<Vec<SpineStation>> {
    evenly_by(model, spine, stations, &|_| count, keep, tol)
}

/// [`evenly`], with each edge's own count: `count(e)` for edge `e`.
fn evenly_by(
    model: &Model,
    spine: &Shape,
    stations: Vec<SpineStation>,
    count: &dyn Fn(usize) -> u32,
    keep: bool,
    tol: Tolerances,
) -> OgeomResult<Vec<SpineStation>> {
    let edges: Vec<Shape> = match model.kind_of(spine)? {
        ShapeType::Edge => vec![spine.clone()],
        ShapeType::Wire => model.ordered_children_of(spine)?,
        _ => return Ok(stations),
    };
    let mut out: Vec<SpineStation> = Vec::with_capacity(stations.len() + edges.len() * 32);
    for (e, edge) in edges.iter().enumerate() {
        let on: Vec<SpineStation> = stations.iter().copied().filter(|s| s.edge == e).collect();
        let (Some(first), Some(last)) = (on.first().copied(), on.last().copied()) else {
            continue;
        };
        let (curve, _) = spine_curve_of(model, edge)?;
        let sense = if curve.d1_at(first.t, tol)?.dot(first.tangent) >= 0.0 {
            1.0
        } else {
            -1.0
        };
        let mut ts: Vec<f64> = if keep {
            on.iter().map(|s| s.t).collect()
        } else {
            vec![first.t, last.t]
        };
        let count = count(e);
        for k in 1..count {
            ts.push(first.t + (last.t - first.t) * f64::from(k) / f64::from(count));
        }
        ts.sort_by(|a, b| {
            if first.t <= last.t {
                a.total_cmp(b)
            } else {
                b.total_cmp(a)
            }
        });
        ts.dedup_by(|a, b| (*a - *b).abs() <= tol.parametric());
        for t in ts {
            let d = curve.d1_at(t, tol)?;
            out.push(SpineStation {
                at: curve.point_at(t, tol)?,
                tangent: d * sense / d.magnitude(),
                edge: e,
                t,
            });
        }
    }
    Ok(out)
}

/// The frame normals a law gives at each station.
///
/// An auxiliary guide ending within `reach` of a station's plane (a
/// sketch's end in single precision) is taken to cross it, carried on
/// along its end tangent.
pub(crate) fn law_normals(
    model: &Model,
    stations: &[SpineStation],
    law: &PipeLaw<'_>,
    reach: f64,
    tol: Tolerances,
) -> OgeomResult<Vec<Vector>> {
    law_normals_on(&guide_curves(model, law)?, stations, law, reach, tol)
}

/// An auxiliary law's guide, each edge's curve and range in the guide's
/// order; nothing for any other law.
fn guide_curves(
    model: &Model,
    law: &PipeLaw<'_>,
) -> OgeomResult<Vec<(ogeom_geom::Curve, (f64, f64))>> {
    let PipeLaw::Auxiliary { guide } = law else {
        return Ok(Vec::new());
    };
    let edges: Vec<Shape> = match model.kind_of(guide)? {
        ShapeType::Edge => vec![(*guide).clone()],
        ShapeType::Wire => model.ordered_children_of(guide)?,
        _ => ogeom_bail!(Construction, "an auxiliary spine is an edge or a wire"),
    };
    let mut curves = Vec::with_capacity(edges.len());
    for edge in &edges {
        curves.push(spine_curve_of(model, edge)?);
    }
    Ok(curves)
}

/// [`law_normals`], an auxiliary law's guide read already
/// ([`guide_curves`]).
fn law_normals_on(
    curves: &[(ogeom_geom::Curve, (f64, f64))],
    stations: &[SpineStation],
    law: &PipeLaw<'_>,
    reach: f64,
    tol: Tolerances,
) -> OgeomResult<Vec<Vector>> {
    match law {
        // Carried by translation, the section has no frame turning with the
        // spine; the fixed pipe is built without stations.
        PipeLaw::Fixed => ogeom_bail!(
            Construction,
            "a fixed section keeps its own frame; it has no frame normals"
        ),
        PipeLaw::RotationMinimizing => Ok(rmf_normals(stations)),
        PipeLaw::Frenet => frenet_normals(stations, tol),
        PipeLaw::Binormal(b) => stations
            .iter()
            .map(|s| {
                let t = s.tangent;
                let b = b.vector() - t * b.vector().dot(t);
                if b.magnitude() <= tol.angular() {
                    ogeom_bail!(
                        Construction,
                        "the spine runs along the binormal at {:?}; no frame keeps it",
                        s.at
                    );
                }
                let n = (b / b.magnitude()).cross(t);
                Ok(n / n.magnitude())
            })
            .collect(),
        PipeLaw::Auxiliary { .. } => {
            let mut out = Vec::with_capacity(stations.len());
            let mut last: Option<Point> = None;
            for s in stations {
                let (p, t) = (s.at, s.tangent);
                // Where the guide crosses this station's plane: a sign
                // change of the height along each guide edge, refined; the
                // crossing nearest the last one found.
                let mut best: Option<Point> = None;
                for (curve, range) in curves {
                    const STEPS: u32 = 256;
                    let height = |u: f64| -> OgeomResult<(f64, Point)> {
                        let q = curve.point_at(u, tol)?;
                        Ok(((q - p).dot(t), q))
                    };
                    let at =
                        |k: u32| range.0 + (range.1 - range.0) * f64::from(k) / f64::from(STEPS);
                    let mut prev = height(at(0))?;
                    for k in 1..=STEPS {
                        let here = height(at(k))?;
                        if prev.0 == 0.0 || prev.0.signum() != here.0.signum() {
                            // A sample on the plane is the crossing itself.
                            let q = if prev.0 == 0.0 {
                                prev.1
                            } else {
                                let (mut lo, mut hi) = (at(k - 1), at(k));
                                let mut f_lo = prev.0;
                                for _ in 0..60 {
                                    let mid = f64::midpoint(lo, hi);
                                    let (f_mid, _) = height(mid)?;
                                    if f_mid.signum() == f_lo.signum() {
                                        lo = mid;
                                        f_lo = f_mid;
                                    } else {
                                        hi = mid;
                                    }
                                }
                                height(f64::midpoint(lo, hi))?.1
                            };
                            let near = last.unwrap_or(p);
                            if best.is_none_or(|b| q.distance(near) < b.distance(near)) {
                                best = Some(q);
                            }
                        }
                        prev = here;
                    }
                }
                if best.is_none() {
                    let near = last.unwrap_or(p);
                    for (curve, range) in curves {
                        for u in [range.0, range.1] {
                            let q = curve.point_at(u, tol)?;
                            let h = (q - p).dot(t);
                            if h.abs() > reach {
                                continue;
                            }
                            let d = curve.d1_at(u, tol)?;
                            let along = d.dot(t);
                            let onto = if along.abs() > tol.angular() * d.magnitude() {
                                q - d * (h / along)
                            } else {
                                q
                            };
                            // A tangent nearly in the plane carries the end
                            // far; the end itself is then as good.
                            let q = if onto.distance(q) <= 2.0 * reach {
                                onto
                            } else {
                                q
                            };
                            if best.is_none_or(|b| q.distance(near) < b.distance(near)) {
                                best = Some(q);
                            }
                        }
                    }
                }
                let Some(q) = best else {
                    ogeom_bail!(
                        Construction,
                        "the auxiliary spine does not cross the plane square to the \
                         spine at {p:?}"
                    );
                };
                last = Some(q);
                let toward = (q - p) - t * (q - p).dot(t);
                if toward.magnitude() <= tol.confusion() {
                    ogeom_bail!(
                        Construction,
                        "the auxiliary spine meets the spine at {p:?}; no direction \
                         points at it"
                    );
                }
                out.push(toward / toward.magnitude());
            }
            Ok(out)
        }
    }
}

/// The pipe shell under a frame law, mitred at corners.
#[allow(clippy::too_many_lines)]
fn pipe_shell_law(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    law: &PipeLaw<'_>,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    const AROUND: usize = 40;
    let frenet = matches!(law, PipeLaw::Frenet);
    let classic = matches!(law, PipeLaw::RotationMinimizing | PipeLaw::Frenet);

    if classic && let Some(exact) = exact_legs(model, profile, spine, frenet, tol)? {
        return Ok(exact);
    }
    let stations = shell_stations(model, spine, tol)?;
    let stations = if classic {
        stations
    } else {
        // As many stations as the law's turning asks, spread evenly: the
        // skin takes its sections at even steps of its own parameter.
        let wanted = densified(model, spine, stations.clone(), law, tolerance, tol)?.len();
        // Shared out along the spine by length, so the spacing is the same
        // on every edge: the skin steps evenly along its whole run.
        let mut lengths: Vec<f64> = Vec::new();
        for pair in stations.windows(2) {
            let e = pair[1].edge;
            if lengths.len() <= e {
                lengths.resize(e + 1, 0.0);
            }
            if pair[0].edge == e {
                lengths[e] += pair[0].at.distance(pair[1].at);
            }
        }
        let total: f64 = lengths.iter().sum();
        #[allow(
            clippy::cast_precision_loss,
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss
        )]
        let share = |e: usize| -> u32 {
            let length = lengths.get(e).copied().unwrap_or(0.0);
            if total <= 0.0 {
                return 2;
            }
            ((wanted as f64 * length / total).ceil() as u32).max(2)
        };
        evenly_by(model, spine, stations, &share, false, tol)?
    };
    // Corners: twin stations standing on one point with different headings.
    let corners: Vec<usize> = (0..stations.len() - 1)
        .filter(|&i| {
            stations[i].at.distance(stations[i + 1].at) <= tol.confusion()
                && (stations[i]
                    .tangent
                    .cross(stations[i + 1].tangent)
                    .magnitude()
                    > tol.angular()
                    || stations[i].tangent.dot(stations[i + 1].tangent) < 0.0)
        })
        .collect();
    // Every twin, corners and smooth junctions alike: each ends one run of
    // skin and starts the next, the two runs sharing the section there. A
    // smooth junction's mitre plane is its own section, so nothing shears.
    let kinks: Vec<usize> = (0..stations.len() - 1)
        .filter(|&i| stations[i].at.distance(stations[i + 1].at) <= tol.confusion())
        .collect();
    let ring = stations[0].at.distance(stations[stations.len() - 1].at) <= tol.confusion() * 10.0;
    if !classic && (ring || !corners.is_empty()) {
        ogeom_bail!(
            Construction,
            "an auxiliary or binormal law sweeps an open spine with no sharp corner"
        );
    }
    if !classic {
        return law_loft(model, profile, spine, &stations, law, tolerance, tol);
    }
    if ring && kinks.is_empty() {
        return closed_pipe_shell(model, profile, spine, stations, frenet, tolerance, tol);
    }
    // The cornered ring closes at its own wrap. Seamed on a corner, the
    // wrap is one more mitre; seamed mid-leg, the wrap's "mitre" plane is
    // the leg's own cross-section (both twin tangents are the leg's), and
    // the shear onto it moves nothing, so the two halves of that leg butt
    // together on the seam's own ring, coplanar walls meeting on it. The
    // solid is exact either way; the mid-leg seam merely leaves its leg in
    // two pieces.
    if frenet && !corners.is_empty() {
        ogeom_bail!(
            Construction,
            "a Frenet frame has no direction at a corner; sweep a cornered \
             spine with the rotation-minimizing frame"
        );
    }
    let normals = law_normals(model, &stations, law, tolerance, tol)?;
    // A ring's frame must come home: carry once more across the wrap
    // corner, read the twist between departure and return, and spread it
    // along the arc: the smooth loop's own reconciliation, ending at a
    // mitre instead of a tangent join.
    let normals = if ring {
        let mut extended = stations.clone();
        extended.push(stations[0]);
        let carried = rmf_normals(&extended);
        let (n0, n_home) = (carried[0], carried[carried.len() - 1]);
        let t0 = stations[0].tangent;
        let twist = (n0.cross(n_home).dot(t0)).atan2(n0.dot(n_home));
        let mut lengths = vec![0.0_f64];
        for pair in extended.windows(2) {
            let held = lengths[lengths.len() - 1];
            lengths.push(held + pair[0].at.distance(pair[1].at));
        }
        let total = lengths[lengths.len() - 1];
        carried
            .iter()
            .take(stations.len())
            .enumerate()
            .map(|(i, n)| {
                let phi = -twist * lengths[i] / total;
                let t = extended[i].tangent;
                let v = *n * phi.cos() + t.cross(*n) * phi.sin();
                let v = v - t * v.dot(t);
                v / v.magnitude()
            })
            .collect()
    } else {
        normals
    };
    // At each corner both twin sections are thrown onto the bisector plane
    // along their own tangents; the mirror symmetry of the rotation-
    // minimizing frame lands them on one ring, the mitre both runs share.
    let mitre: Vec<Option<(Point, Vector)>> = {
        let mut out: Vec<Option<(Point, Vector)>> = vec![None; stations.len()];
        for &k in &kinks {
            let n = stations[k].tangent + stations[k + 1].tangent;
            if n.magnitude() <= tol.angular() {
                ogeom_bail!(
                    Construction,
                    "the spine doubles straight back on itself; no mitre \
                     plane divides that corner"
                );
            }
            out[k] = Some((stations[k].at, n));
            out[k + 1] = Some((stations[k + 1].at, n));
        }
        if ring {
            let wrap = stations.len() - 1;
            let n = stations[wrap].tangent + stations[0].tangent;
            if n.magnitude() <= tol.angular() {
                ogeom_bail!(
                    Construction,
                    "the spine doubles straight back on itself; no mitre \
                     plane divides that corner"
                );
            }
            out[wrap] = Some((stations[wrap].at, n));
            out[0] = Some((stations[0].at, n));
        }
        out
    };
    let runs: Vec<(usize, usize)> = {
        let mut out = Vec::with_capacity(kinks.len() + 1);
        let mut start = 0;
        for &k in &kinks {
            out.push((start, k));
            start = k + 1;
        }
        out.push((start, stations.len() - 1));
        out
    };
    // A mitred end between straight legs is a *shear*: the honest wall is
    // the run's own surface trimmed by the mitre plane, which for a
    // straight leg is exactly the ruled skin between its two end rings.
    // Under a law that turns the section along a straight leg, the leg's
    // wall is no ruled skin between its end rings.
    let straight = |rs: usize, re: usize| -> bool {
        if !classic {
            return false;
        }
        let t0 = stations[rs].tangent;
        (rs..=re).all(|i| stations[i].tangent.cross(t0).magnitude() <= tol.angular())
    };
    // Every corner as the pair of runs it stands between, the wrap
    // included, and whether either leg is curved. A curved leg's trim is
    // not a loft of its rows: the two legs' generators for one profile
    // point are followed (the leg's own curve, run straight on past the
    // corner) to where they meet, and each wall ends on that crossing.
    // Where the corner turns in the plane the crossing is exact; a skew
    // corner's generators miss each other, and that miss is refused.
    struct CornerPair {
        before: (usize, usize),
        after: (usize, usize),
        curved: bool,
    }
    let corner_pairs: Vec<CornerPair> = {
        let mut out = Vec::new();
        // A smooth junction joins its runs on their shared section; only a
        // corner that turns asks the generators where the walls meet.
        for pair in runs.windows(2) {
            out.push(CornerPair {
                before: pair[0],
                after: pair[1],
                curved: corners.contains(&pair[0].1)
                    && (!straight(pair[0].0, pair[0].1) || !straight(pair[1].0, pair[1].1)),
            });
        }
        if ring && runs.len() > 1 {
            let (before, after) = (runs[runs.len() - 1], runs[0]);
            let turns = stations[before.1]
                .tangent
                .cross(stations[after.0].tangent)
                .magnitude()
                > tol.angular()
                || stations[before.1].tangent.dot(stations[after.0].tangent) < 0.0;
            out.push(CornerPair {
                before,
                after,
                curved: turns && (!straight(before.0, before.1) || !straight(after.0, after.1)),
            });
        }
        out
    };
    let walk = SpineWalk {
        curves: walk_curves(model, spine)?,
        stations: &stations,
        normals: &normals,
    };
    let join_reach = tolerance.max(tol.confusion() * 100.0);
    let curved_join = |pair: &CornerPair, ab: (f64, f64)| -> OgeomResult<CornerJoin> {
        let join = walk.join(pair.before, pair.after, ab, tol)?;
        if join.gap > join_reach {
            ogeom_bail!(
                Construction,
                "a skew corner against a curved leg is still owed its frame \
                 law: the legs' generators miss by {}; see docs/PARITY.md, \
                 offset.sweeps",
                join.gap
            );
        }
        Ok(join)
    };
    // Across a curved corner the two legs' skins share the join row as one
    // edge: a run adopts the previous run's end row at its start, and the
    // last run of a cornered ring adopts the first run's start row at its
    // end.
    let shares_start = |ri: usize| -> bool {
        ri > 0
            && corner_pairs
                .iter()
                .any(|pair| pair.curved && pair.after == runs[ri])
    };
    let shares_end = |ri: usize| -> bool {
        ring && ri + 1 == runs.len()
            && corner_pairs
                .iter()
                .any(|pair| pair.curved && pair.before == runs[ri] && pair.after == runs[0])
    };
    // The curved corner a station is a twin of, if any.
    let curved_at = |i: usize| -> Option<&CornerPair> {
        corner_pairs
            .iter()
            .find(|pair| pair.curved && (pair.before.1 == i || pair.after.0 == i))
    };

    // The profile's loops: a face contributes every wire, holes included;
    // a bare wire is one loop.
    let loops: Vec<Shape> = match model.kind_of(profile)? {
        ShapeType::Face => explore(model, profile, Filter::OfType(ShapeType::Wire))?,
        ShapeType::Wire => vec![profile.clone()],
        other => ogeom_bail!(
            Construction,
            "a pipe shell sweeps a planar wire or face, not a {other:?}"
        ),
    };
    if loops.is_empty() {
        ogeom_bail!(Construction, "the profile has no loop to sweep");
    }
    let Some(plane) = ogeom_algo::find_plane(model, profile, tol)? else {
        ogeom_bail!(Construction, "a pipe shell sweeps a planar profile");
    };
    let t0 = stations[0].tangent;
    // Square to the spine's own start tangent, read exactly off its first
    // edge, to an angle's tolerance.
    let exact_t0 = {
        let first = match model.kind_of(spine)? {
            ShapeType::Edge => spine.clone(),
            _ => model.ordered_children_of(spine)?[0].clone(),
        };
        let (curve, range) = spine_curve_of(model, &first)?;
        let reversed = first.orientation() == ogeom_topo::Orientation::Reversed;
        let d = curve.d1_at(if reversed { range.1 } else { range.0 }, tol)?;
        let d = if reversed { -d } else { d };
        d / d.magnitude()
    };
    if plane.normal().vector().cross(exact_t0).magnitude() > tol.angular() {
        ogeom_bail!(
            Construction,
            "the profile leans along its spine; a pipe shell runs square to \
             the start"
        );
    }
    if plane.distance_to(stations[0].at) > tol.confusion() * 100.0 {
        ogeom_bail!(
            Construction,
            "the profile does not sit at the spine's start"
        );
    }

    // Transport: each loop expressed in the start frame's own 2D
    // coordinates, then re-expressed in every station's frame. A loop of one
    // smooth closed edge skins as one wall; a faceted loop skins one strip
    // per edge, cornered at shared vertices, because no single fit can
    // speak a corner.
    let x0 = normals[0];
    let y0 = t0.cross(x0);
    let origin = stations[0].at;
    let flat = |p: Point| -> (f64, f64) { ((p - origin).dot(x0), (p - origin).dot(y0)) };
    // A skew corner against a curved leg: the legs' generators miss, so
    // no join row closes the walls. Such a corner is a mitre instead: the
    // spine is split there, each side swept on straight past the corner
    // and trimmed by the mitre plane, and the pieces fused.
    let skew: Vec<(usize, usize)> = {
        let mut probes: Vec<(f64, f64)> = Vec::new();
        for wire in &loops {
            probes.extend(sample_wire(model, wire, AROUND, tol)?.into_iter().map(flat));
        }
        let mut out = Vec::new();
        for pair in corner_pairs.iter().filter(|pair| pair.curved) {
            let mut worst = 0.0_f64;
            for ab in &probes {
                worst = worst.max(walk.join(pair.before, pair.after, *ab, tol)?.gap);
            }
            if worst > join_reach {
                out.push((pair.before.1, pair.after.0));
            }
        }
        out
    };
    if !skew.is_empty() {
        let probes: Vec<(f64, f64)> = {
            let mut out = Vec::new();
            for wire in &loops {
                out.extend(sample_wire(model, wire, AROUND, tol)?.into_iter().map(flat));
            }
            out
        };
        return mitred_pieces(
            model, profile, spine, &stations, &skew, ring, &probes, tolerance, tol,
        );
    }
    let place = |i: usize, (a, b): (f64, f64)| -> OgeomResult<Point> {
        if let Some(pair) = curved_at(i) {
            return Ok(curved_join(pair, (a, b))?.at);
        }
        let x = normals[i];
        let y = stations[i].tangent.cross(x);
        let p = stations[i].at + x * a + y * b;
        Ok(match mitre[i] {
            Some((corner, n)) => {
                let t = stations[i].tangent;
                p + t * ((corner - p).dot(n) / t.dot(n))
            }
            None => p,
        })
    };
    // One profile point's generator along a re-rowed run: its parameter
    // against the length run from the column's start, and the whole length.
    struct RerowColumn {
        along: Vec<(f64, f64)>,
        length: f64,
    }
    // Where one profile point's generator on `run` meets the next leg's (at
    // its end) or the previous leg's (at its start), at a curved corner.
    let crossing =
        |run: (usize, usize), ab: (f64, f64), at_start: bool| -> OgeomResult<Option<CornerJoin>> {
            let pair = corner_pairs.iter().find(|pair| {
                pair.curved
                    && if at_start {
                        pair.after == run
                    } else {
                        pair.before == run
                    }
            });
            pair.map(|pair| curved_join(pair, ab)).transpose()
        };
    // Each end of one profile point's column on `run`: the crossing where
    // the run meets a curved corner there, else the end station. A crossing
    // past the middle of the run means the leg is shorter than the corner's
    // reach.
    let column_ends = |(rs, re): (usize, usize),
                       ab: (f64, f64)|
     -> OgeomResult<(Option<CornerJoin>, Option<CornerJoin>)> {
        let run = (rs, re);
        let (start, end) = (crossing(run, ab, true)?, crossing(run, ab, false)?);
        #[allow(clippy::cast_precision_loss)]
        let (rsf, ref_) = (rs as f64, re as f64);
        if start.as_ref().is_some_and(|j| j.s2 >= ref_ - 0.5)
            || end.as_ref().is_some_and(|j| j.s1 <= rsf + 0.5)
        {
            ogeom_bail!(
                Construction,
                "a leg is shorter than its corner's reach; the mitre would \
                 run off its far end"
            );
        }
        Ok((start, end))
    };
    // A straight run's column is its two ends, ruled: the trimmed prism
    // itself, whether an end is sheared onto a mitre plane or stands on a
    // curved corner's crossing.
    let straight_column = |(rs, re): (usize, usize), ab: (f64, f64)| -> OgeomResult<Vec<Point>> {
        let (start, end) = column_ends((rs, re), ab)?;
        Ok(vec![
            match start {
                Some(j) => j.at,
                None => place(rs, ab)?,
            },
            match end {
                Some(j) => j.at,
                None => place(re, ab)?,
            },
        ])
    };
    // A curved run with a crossing at either end is re-rowed whole: every
    // column runs its own generator from its start to its end, read at
    // fractions of its own arc length, so the skin's parameter across is
    // one for all columns. A column's pace differs between the leg's curve
    // and its straight extension, and a stretch skewed only near the corner
    // would pace each column differently. The skin is known everywhere
    // along its columns, so it is checked between its rows as well.
    let rerow_column = |(rs, re): (usize, usize), ab: (f64, f64)| -> OgeomResult<RerowColumn> {
        let run = (rs, re);
        let (start, end) = column_ends(run, ab)?;
        #[allow(clippy::cast_precision_loss)]
        let lo = start.map_or(rs as f64, |j| j.s2);
        #[allow(clippy::cast_precision_loss)]
        let hi = end.map_or(re as f64, |j| j.s1);
        // The length is read in eighths of a station on the stations' own
        // grid, so the run's end station, where the leg's curve gives way to
        // its straight extension and a generator off the spine changes its
        // pace, is a step's end. Read across it, one step would mix the two
        // paces and kink the column's parameter, which a cubic fit cannot
        // follow.
        let mut nodes: Vec<f64> = vec![lo];
        #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
        {
            let mut m = (lo * 8.0).floor() as i64 + 1;
            while (m as f64) / 8.0 < hi {
                let sp = (m as f64) / 8.0;
                if sp - lo > 1e-9 && hi - sp > 1e-9 {
                    nodes.push(sp);
                }
                m += 1;
            }
        }
        nodes.push(hi);
        let mut along: Vec<(f64, f64)> = Vec::with_capacity(nodes.len());
        let mut prev: Option<Point> = None;
        let mut length = 0.0;
        for sp in nodes {
            let p = walk.generator(sp, run, ab, tol)?;
            if let Some(q) = prev {
                length += q.distance(p);
            }
            along.push((length, sp));
            prev = Some(p);
        }
        Ok(RerowColumn { along, length })
    };
    // The point a fraction `f` of the way along a re-rowed column.
    let rerowed_at =
        |run: (usize, usize), column: &RerowColumn, ab: (f64, f64), f: f64| -> OgeomResult<Point> {
            let along = &column.along;
            let target = column.length * f;
            let at = along
                .partition_point(|(l, _)| *l < target)
                .clamp(1, along.len() - 1);
            let ((l0, s0), (l1, s1)) = (along[at - 1], along[at]);
            let g = if l1 > l0 {
                ((target - l0) / (l1 - l0)).clamp(0.0, 1.0)
            } else {
                0.0
            };
            walk.generator(s0 + (s1 - s0) * g, run, ab, tol)
        };
    // A re-rowed run's skin known everywhere: the point `s` stations' worth
    // of the way along the column of profile point `ab` at `u`, each column
    // built once into `held`.
    #[allow(clippy::type_complexity)]
    let rerowed_point = |(rs, re): (usize, usize),
                         held: &std::cell::RefCell<ogeom_core::FastMap<u64, RerowColumn>>,
                         u: f64,
                         ab: (f64, f64),
                         s: f64|
     -> OgeomResult<Point> {
        if !held.borrow().contains_key(&u.to_bits()) {
            let column = rerow_column((rs, re), ab)?;
            held.borrow_mut().insert(u.to_bits(), column);
        }
        let held = held.borrow();
        #[allow(clippy::cast_precision_loss)]
        let f = (s - rs as f64) / (re - rs) as f64;
        rerowed_at((rs, re), &held[&u.to_bits()], ab, f)
    };
    // A curved run with no crossing at either end has its stations for
    // rows, and the frame carried between them places the profile anywhere
    // along it: its skin is checked between the stations too, its
    // parameter across even in the station index (an affine image of the
    // spine's own parameter along the run).
    let plain = |run: (usize, usize)| -> bool {
        !straight(run.0, run.1)
            && !corner_pairs
                .iter()
                .any(|pair| pair.curved && (pair.after == run || pair.before == run))
    };
    let along_run = |run: (usize, usize), s: f64, ab: (f64, f64)| -> OgeomResult<Point> {
        if s.fract() == 0.0 {
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let i = s as usize;
            place(i, ab)
        } else {
            walk.generator(s, run, ab, tol)
        }
    };
    let last = stations.len() - 1;

    enum LoopWall {
        Ring {
            ring0: Shape,
            ring1: Shape,
        },
        Chain {
            bottoms: Vec<Shape>,
            tops: Vec<Shape>,
        },
    }
    let mut faces: Vec<Shape> = Vec::new();
    let mut ends: Vec<LoopWall> = Vec::with_capacity(loops.len());
    for (li, wire) in loops.iter().enumerate() {
        let hole = li != 0;
        let edges = model.ordered_children_of(wire)?;
        let single_smooth = edges.len() == 1 && {
            let (curve, _) = spine_curve_of(model, &edges[0])?;
            !matches!(curve, ogeom_geom::Curve::Line(_))
                && ogeom_algo::edge_vertices(model, &edges[0])?.is_some_and(|(a, b)| a.is_same(&b))
        };
        if single_smooth {
            let profile_loop = section_loop(model, wire, None, tol)?;
            // One wall per smooth run: a fit across a corner speaks nothing,
            // and the twin stations put both runs' boundary rows on the one
            // mitred ring, where the sew joins them.
            let mut ring0: Option<Shape> = None;
            let mut ring1: Option<Shape> = None;
            for (ri, &(rs, re)) in runs.iter().enumerate() {
                // Each column the run's rows of one point of the profile,
                // read by arc length round it.
                let held = std::cell::RefCell::default();
                let skin = if plain((rs, re)) {
                    Skin::swept(
                        |f, s| along_run((rs, re), s, flat(profile_loop.at(f))),
                        fractions(AROUND),
                        (rs, re),
                        true,
                    )?
                } else if straight(rs, re) {
                    Skin::columns(
                        |f| straight_column((rs, re), flat(profile_loop.at(f))),
                        fractions(AROUND),
                        true,
                        false,
                        false,
                    )?
                } else {
                    Skin::swept(
                        |f, s| rerowed_point((rs, re), &held, f, flat(profile_loop.at(f)), s),
                        fractions(AROUND),
                        (rs, re),
                        true,
                    )?
                };
                let shared_start = shares_start(ri).then_some(()).and(ring1.as_ref());
                let shared_end = shares_end(ri).then_some(()).and(ring0.as_ref());
                let wall = skinned_wall(model, &skin, (shared_start, shared_end), tolerance, tol)?;
                faces.push(if hole {
                    wall.face.reversed()
                } else {
                    wall.face.clone()
                });
                if ring0.is_none() {
                    ring0 = Some(wall.ring0);
                }
                ring1 = Some(wall.ring1);
            }
            let (Some(ring0), Some(ring1)) = (ring0, ring1) else {
                ogeom_bail!(Construction, "the sweep produced no wall");
            };
            ends.push(LoopWall::Ring { ring0, ring1 });
        } else {
            // Shared corner vertices at both ends of every edge junction.
            let count = edges.len();
            let mut corner_flat: Vec<(f64, f64)> = Vec::with_capacity(count);
            for edge in &edges {
                // Already in the ring's own sense: a reversed edge's
                // vertices come back end first.
                let Some((start, _)) = ogeom_algo::edge_vertices(model, edge)? else {
                    ogeom_bail!(Construction, "a profile edge has no vertices");
                };
                let Some(data) = model.node(&start).and_then(|n| n.data().as_vertex()) else {
                    ogeom_bail!(Construction, "a profile vertex holds no data");
                };
                corner_flat.push(flat(data.point));
            }
            let make_corners = |model: &mut Model, station: usize| -> OgeomResult<Vec<Shape>> {
                let mut out = Vec::with_capacity(corner_flat.len());
                for ab in &corner_flat {
                    out.push(ogeom_algo::make_vertex(model, place(station, *ab)?).shape);
                }
                Ok(out)
            };
            // Corner vertex sets at every run boundary; a kink's twin
            // stations land on the same mitred points, so both runs take
            // the same vertex objects.
            let mut corners_at: Vec<Option<Vec<Shape>>> = vec![None; stations.len()];
            if ring {
                // The wrap is one corner: both runs take the same vertex
                // objects. Every corner's two sheared sections must land on
                // one ring for the loop to close; a planar ring's do
                // exactly, and a skew ring's (whose parallel-carried frame
                // leaves the far tangent's plane) do not, so the residue
                // is measured and the skew ring refused by name rather
                // than sewn hoping.
                let mut worst = 0.0_f64;
                for ab in &corner_flat {
                    worst = worst.max(place(last, *ab)?.distance(place(0, *ab)?));
                    for &k in &kinks {
                        worst = worst.max(place(k, *ab)?.distance(place(k + 1, *ab)?));
                    }
                }
                if worst > tolerance.max(tol.confusion() * 100.0) {
                    ogeom_bail!(
                        Construction,
                        "a skew-cornered ring's sections do not meet on \
                         their mitres; the out-of-plane corner's frame law \
                         is still owed; see docs/PARITY.md, offset.sweeps"
                    );
                }
                let set = make_corners(model, 0)?;
                if worst > tol.confusion() {
                    for v in &set {
                        model.widen(v, ogeom_core::Tolerance::new(worst * 2.0)?)?;
                    }
                }
                corners_at[0] = Some(set.clone());
                corners_at[last] = Some(set);
            } else {
                corners_at[0] = Some(make_corners(model, 0)?);
                corners_at[last] = Some(make_corners(model, last)?);
            }
            for &k in &kinks {
                let set = make_corners(model, k)?;
                corners_at[k] = Some(set.clone());
                corners_at[k + 1] = Some(set);
            }

            // The loop's own centroid line, for orienting each strip.
            let hint_flat = {
                let mut a = 0.0;
                let mut b = 0.0;
                for (fa, fb) in &corner_flat {
                    a += fa;
                    b += fb;
                }
                #[allow(clippy::cast_precision_loss)]
                let n = count as f64;
                (a / n, b / n)
            };

            let mut bottoms = Vec::with_capacity(count);
            let mut tops = Vec::with_capacity(count);
            // Per run: the first strip's start rail, for the last strip to
            // close the loop on, and the previous strip's end rail, for
            // the next to start from: one edge for both, never two fits.
            let mut run_rails: Vec<(Option<Shape>, Option<Shape>)> = vec![(None, None); runs.len()];
            for (ei, edge) in edges.iter().enumerate() {
                let (curve, range) = spine_curve_of(model, edge)?;
                let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
                const ALONG_EDGE: usize = 8;
                let edge_flat = |f: f64| -> OgeomResult<(f64, f64)> {
                    let t = if reversed {
                        range.1 - (range.1 - range.0) * f
                    } else {
                        range.0 + (range.1 - range.0) * f
                    };
                    Ok(flat(curve.point_at(t, tol)?))
                };
                let next = (ei + 1) % count;
                let mut bottom: Option<Shape> = None;
                let mut top: Option<Shape> = None;
                for (ri, &(rs, re)) in runs.iter().enumerate() {
                    // Each column the run's rows of one point of the edge,
                    // at a fraction of its parameter range.
                    let held = std::cell::RefCell::default();
                    let skin = if plain((rs, re)) {
                        Skin::swept(
                            |f, s| along_run((rs, re), s, edge_flat(f)?),
                            fractions(ALONG_EDGE),
                            (rs, re),
                            false,
                        )?
                    } else if straight(rs, re) {
                        Skin::columns(
                            |f| straight_column((rs, re), edge_flat(f)?),
                            fractions(ALONG_EDGE),
                            false,
                            false,
                            false,
                        )?
                    } else {
                        Skin::swept(
                            |f, s| rerowed_point((rs, re), &held, f, edge_flat(f)?, s),
                            fractions(ALONG_EDGE),
                            (rs, re),
                            false,
                        )?
                    };
                    let shared_start = shares_start(ri).then_some(()).and(top.as_ref());
                    let shared_end = shares_end(ri).then_some(()).and(bottom.as_ref());
                    let mid_i = usize::midpoint(rs, re);
                    let hint = {
                        let x = normals[mid_i];
                        let y = stations[mid_i].tangent.cross(x);
                        stations[mid_i].at + x * hint_flat.0 + y * hint_flat.1
                    };
                    let (Some(from), Some(to)) = (&corners_at[rs], &corners_at[re]) else {
                        ogeom_bail!(Construction, "a run boundary has no corners");
                    };
                    let (first_rail0, prev_rail1) = run_rails[ri].clone();
                    let shared_rail0 = if ei > 0 { prev_rail1 } else { None };
                    let shared_rail1 = if ei + 1 == count && count > 1 {
                        first_rail0.clone()
                    } else {
                        None
                    };
                    let strip = skinned_strip(
                        model,
                        &skin,
                        (&from[ei], &from[next], &to[ei], &to[next]),
                        [
                            shared_start,
                            shared_end,
                            shared_rail0.as_ref(),
                            shared_rail1.as_ref(),
                        ],
                        hint,
                        hole,
                        tolerance,
                        tol,
                    )?;
                    run_rails[ri] = (
                        if ei == 0 {
                            Some(strip.rail0.clone())
                        } else {
                            first_rail0
                        },
                        Some(strip.rail1.clone()),
                    );
                    faces.push(strip.face.clone());
                    if bottom.is_none() {
                        bottom = Some(strip.bottom);
                    }
                    top = Some(strip.top);
                }
                let (Some(bottom), Some(top)) = (bottom, top) else {
                    ogeom_bail!(Construction, "the sweep produced no strip");
                };
                bottoms.push(bottom);
                tops.push(top);
            }
            ends.push(LoopWall::Chain { bottoms, tops });
        }
    }

    // A cap per end: one plane, one wire per loop, each edge's pcurve the
    // exact projection of its control net into the plane's chart. A ring
    // has no ends: its two boundary rings stand on one mitre plane and the
    // sew joins them.
    for end in 0..if ring { 0 } else { 2 } {
        let (at, outward) = if end == 0 {
            (stations[0].at, -stations[0].tangent)
        } else {
            (stations[last].at, stations[last].tangent)
        };
        let cap_plane = Plane::through(at, Direction::new(outward, tol)?);
        let mut loop_edges: Vec<Vec<Shape>> = Vec::with_capacity(ends.len());
        for wall in &ends {
            loop_edges.push(match wall {
                LoopWall::Ring { ring0, ring1 } => {
                    vec![if end == 0 {
                        ring0.clone()
                    } else {
                        ring1.clone()
                    }]
                }
                LoopWall::Chain { bottoms, tops } => {
                    if end == 0 {
                        bottoms.clone()
                    } else {
                        tops.clone()
                    }
                }
            });
        }
        let mut reach = 1.0_f64;
        for edges in &loop_edges {
            for edge in edges {
                let (curve, range) = spine_curve_of(model, edge)?;
                for t in 0..8 {
                    let p =
                        curve.point_at(range.0 + (range.1 - range.0) * f64::from(t) / 8.0, tol)?;
                    reach = reach.max(p.distance(at) * 2.0);
                }
            }
        }
        let cap_surface: SurfaceGeometry =
            PlaneSurface::over(cap_plane, (-reach, reach), (-reach, reach))?.into();
        // The material on the left of each ring about the outward normal:
        // the profile's first loop is its outer one.
        let mut wires: Vec<Shape> = Vec::with_capacity(loop_edges.len());
        for (li, edges) in loop_edges.iter().enumerate() {
            let ring = walked_about(model, edges, outward, li == 0, tol)?;
            wires.push(ogeom_algo::make_wire(model, &ring, tol)?.shape);
        }
        let face = ogeom_algo::make_face(model, cap_surface.clone(), &wires, tol)?.shape;
        let cap_id = {
            let Some(node) = model.node(&face) else {
                ogeom_bail!(Dangling, "the cap just built is not in this model");
            };
            let ogeom_topo::NodeData::Face(data) = node.data() else {
                ogeom_bail!(Construction, "the cap holds no face data");
            };
            data.surface
        };
        let frame = cap_plane.frame();
        for edges in &loop_edges {
            for edge in edges {
                let (curve, range) = spine_curve_of(model, edge)?;
                let ogeom_geom::Curve::BSpline(bs) = &curve else {
                    ogeom_bail!(Construction, "a swept ring is not a spline");
                };
                // A planar polynomial spline's chart image is the same-degree
                // spline of the projected control points: affine, so exact.
                let control2: Vec<Point2> = bs
                    .control_points()
                    .iter()
                    .map(|w| {
                        let local = frame.to_local(w.point());
                        Point2::new(local.x, local.y)
                    })
                    .collect();
                let pcurve: ogeom_geom::PlanarCurve =
                    ogeom_geom::BSpline2d::new(bs.knots().clone(), control2, tol)?.into();
                ogeom_algo::attach_pcurve(
                    model,
                    edge,
                    pcurve,
                    cap_id,
                    ogeom_topo::Location::identity(),
                    range,
                )?;
            }
        }
        faces.push(face);
    }

    let sewn = sew(model, &faces, tol)?;
    let mut built = if ring {
        // A holed ring sews into one shell per profile loop: the outer
        // bounds the material, each hole a void tunnel. Largest bound
        // first, the voids' faces already turned at build.
        if sewn.shells.is_empty() {
            ogeom_bail!(Construction, "the pipe shell did not close");
        }
        for shell in &sewn.shells {
            if !ogeom_algo::is_shell_closed(model, shell)? {
                ogeom_bail!(Construction, "the pipe shell did not close");
            }
        }
        let mut ordered = sewn.shells.clone();
        let mut sized: Vec<(f64, Shape)> = Vec::with_capacity(ordered.len());
        for shell in ordered.drain(..) {
            let bound = ogeom_algo::shape_bounds(model, &shell, tol)?;
            sized.push((bound.diagonal(), shell));
        }
        sized.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(core::cmp::Ordering::Equal));
        let shells: Vec<Shape> = sized.into_iter().map(|(_, s)| s).collect();
        make_solid(model, &shells)?
    } else {
        if sewn.shells.len() != 1 || !ogeom_algo::is_shell_closed(model, &sewn.shells[0])? {
            if std::env::var_os("OGEOM_DEBUG_SWEEP").is_some() {
                eprintln!(
                    "SWEEP: {} shells, {} free edges from {} faces",
                    sewn.shells.len(),
                    sewn.free_edges.len(),
                    faces.len()
                );
                for edge in &sewn.free_edges {
                    let (curve, range) = spine_curve_of(model, edge)?;
                    let a = curve.point_at(range.0, tol)?;
                    let b = curve.point_at(range.1, tol)?;
                    let m = curve.point_at(f64::midpoint(range.0, range.1), tol)?;
                    let t = model.tolerance_of(edge)?.map_or(0.0, |t| t.get());
                    eprintln!(
                        "  free ({:.3},{:.3},{:.3}) -> ({:.3},{:.3},{:.3}) via ({:.3},{:.3},{:.3}) tol {t:.2e}",
                        a.x, a.y, a.z, b.x, b.y, b.z, m.x, m.y, m.z
                    );
                }
            }
            ogeom_bail!(Construction, "the pipe shell did not close");
        }
        make_solid(model, std::slice::from_ref(&sewn.shells[0]))?
    };
    built.history.generate(profile, built.shape.clone());
    built.history.generate(spine, built.shape.clone());
    Ok(built)
}

/// An edge's 3D curve and range, cloned out of the model.
/// A pipe shell whose spine turns a skew corner against a curved leg,
/// built as pieces between such corners and fused.
///
/// With the frame reflected across the mitre plane, a straight leg's walls
/// and a curved leg's cut that plane in sections that differ on the inside
/// of the turn: no single join row closes both. Each piece is swept on
/// straight past its corners (the frame carries unchanged along a straight
/// run), trimmed by each corner's mitre plane, and the pieces fused: where
/// their sections on the plane coincide the caps melt, and where they
/// differ the difference stands as a face of the mitre plane. Exact, and
/// the plain mitre wherever the two sections agree.
#[allow(clippy::too_many_arguments, reason = "one construction, all its data")]
fn mitred_pieces(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    stations: &[SpineStation],
    skew: &[(usize, usize)],
    ring: bool,
    probes: &[(f64, f64)],
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    if model.kind_of(profile)? == ShapeType::Wire {
        // A closed planar wire sweeps the walls of the face it bounds: the
        // solid pieces are mitred and fused as for that face, and its end
        // caps (on the planes square to the spine's ends) are taken off.
        if !ogeom_algo::is_wire_closed(model, profile, tol)? {
            ogeom_bail!(
                Construction,
                "a skew corner against a curved leg is mitred by fusing solid \
                 pieces; an open wire bounds no face to sweep round it"
            );
        }
        let Some(plane) = ogeom_algo::find_plane(model, profile, tol)? else {
            ogeom_bail!(Construction, "a pipe shell sweeps a planar profile");
        };
        let reach = 1e4_f64;
        let surface: SurfaceGeometry =
            PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?.into();
        let face = ogeom_algo::make_face(model, surface, std::slice::from_ref(profile), tol)?.shape;
        let face = realized_profile(model, &face, &Transform::IDENTITY, tol)?;
        let solid = mitred_pieces(
            model, &face, spine, stations, skew, ring, probes, tolerance, tol,
        )?
        .shape;
        let ends: Vec<(Point, Vector)> = if ring {
            Vec::new()
        } else {
            vec![
                (stations[0].at, stations[0].tangent),
                (
                    stations[stations.len() - 1].at,
                    stations[stations.len() - 1].tangent,
                ),
            ]
        };
        let mut walls = Vec::new();
        for f in explore(model, &solid, Filter::OfType(ShapeType::Face))? {
            let Some(ogeom_topo::NodeData::Face(data)) = model.node(&f).map(|n| n.data()) else {
                continue;
            };
            let cap = match model.geometry().surface(data.surface) {
                Some(SurfaceGeometry::Plane(p)) => {
                    let placed = p.plane();
                    ends.iter().any(|(at, n)| {
                        placed.normal().vector().cross(*n).magnitude() <= tol.angular()
                            && placed.distance_to(*at) <= tol.confusion() * 100.0
                    })
                }
                _ => false,
            };
            if !cap {
                walls.push(f);
            }
        }
        let sewn = sew(model, &walls, tol)?;
        let shape = match sewn.shells.as_slice() {
            [shell] => shell.clone(),
            _ => ogeom_algo::make_compound(model, &sewn.shells)?.shape,
        };
        let mut history = History::new();
        history.generate(profile, shape.clone());
        history.generate(spine, shape.clone());
        return Ok(Built::new(shape, history));
    }
    if model.kind_of(profile)? != ShapeType::Face {
        ogeom_bail!(Construction, "a pipe shell sweeps a planar wire or face");
    }
    let edges: Vec<Shape> = match model.kind_of(spine)? {
        ShapeType::Edge => vec![spine.clone()],
        _ => model.ordered_children_of(spine)?,
    };
    let normals = rmf_normals(stations);
    let reach_out = probes
        .iter()
        .map(|(a, b)| a.hypot(*b))
        .fold(0.0_f64, f64::max);

    // Each split corner: the junction's edges, its point, the tangents
    // either side, the frame the far side starts in, and how far each side
    // runs on past it to cover the mitre plane across the whole profile.
    struct Split {
        edge_before: usize,
        at: Point,
        before: Vector,
        after: Vector,
        frame_after: Vector,
        run_on: f64,
    }
    let mut splits: Vec<Split> = Vec::with_capacity(skew.len());
    for &(k, next) in skew {
        let (before, after) = (stations[k].tangent, stations[next].tangent);
        let turn = before.dot(after).clamp(-1.0, 1.0).acos();
        let half = (turn * 0.5).cos();
        if half < 0.05 {
            ogeom_bail!(
                Construction,
                "the spine all but doubles back at a corner; a mitre there \
                 runs off to infinity"
            );
        }
        splits.push(Split {
            edge_before: stations[k].edge,
            at: stations[k].at,
            before,
            after,
            frame_after: normals[next],
            // The mitre plane stands at most `R·tan(φ/2)` past the corner
            // along either leg for a profile reaching `R` from the spine;
            // half as far again clears it with room.
            run_on: reach_out * ((turn * 0.5).tan() * 1.5 + 0.1),
        });
    }
    splits.sort_by_key(|s| s.edge_before);

    // Pieces as runs of spine edges, each between split corners (or the
    // open spine's own ends).
    let count = edges.len();
    let mut pieces: Vec<(Vec<usize>, Option<usize>, Option<usize>)> = Vec::new();
    if ring {
        for (i, split) in splits.iter().enumerate() {
            let next = &splits[(i + 1) % splits.len()];
            let mut run = Vec::new();
            let mut e = (split.edge_before + 1) % count;
            loop {
                run.push(e);
                if e == next.edge_before {
                    break;
                }
                e = (e + 1) % count;
            }
            pieces.push((run, Some(i), Some((i + 1) % splits.len())));
        }
    } else {
        let mut first = 0;
        for (i, split) in splits.iter().enumerate() {
            pieces.push((
                (first..=split.edge_before).collect(),
                i.checked_sub(1),
                Some(i),
            ));
            first = split.edge_before + 1;
        }
        pieces.push(((first..count).collect(), splits.len().checked_sub(1), None));
    }

    let x0 = normals[0];
    let start_frame = Frame::new(
        stations[0].at,
        Direction::new(stations[0].tangent, tol)?,
        Direction::new(x0, tol)?,
        tol,
    )?;
    // One block per split, standing on the mitre plane on the far side of
    // the corner: the piece before the corner is cut by it and the piece
    // after keeps what it shares with it, so both sides' caps are pieces
    // of the block's one face, on one surface and one chart, which is what
    // lets the fuse melt them.
    let mut blocks: Vec<Shape> = Vec::with_capacity(splits.len());
    for split in &splits {
        let n = (split.before + split.after) / (split.before + split.after).magnitude();
        let normal = Direction::new(n, tol)?;
        let plane = Plane::through(split.at, normal);
        let reach = (split.run_on + reach_out) * 4.0;
        let frame = plane.frame();
        let (u, v) = (frame.x().vector(), frame.y().vector());
        let corners: Vec<Point> = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]
            .iter()
            .map(|(a, b)| split.at + u * (a * reach) + v * (b * reach))
            .collect();
        let wire = ogeom_algo::make_polygon(model, &corners, true, tol)?.shape;
        let edges = explore(model, &wire, Filter::OfType(ShapeType::Edge))?;
        let surface: SurfaceGeometry = PlaneSurface::over(
            plane,
            (-reach * 2.0, reach * 2.0),
            (-reach * 2.0, reach * 2.0),
        )?
        .into();
        let base = ogeom_algo::make_face_with_pcurves(model, surface, &[edges], tol)?.shape;
        let block = ogeom_algo::make_prism(model, &base, n * (reach * 2.0), tol)?.shape;
        blocks.push(block);
    }

    let mut joined: Vec<Shape> = Vec::new();
    for (run, start, end) in pieces {
        let mut wire_edges: Vec<Shape> = Vec::new();
        let traversal = |model: &Model, e: usize, at_start: bool| -> OgeomResult<Shape> {
            // In the spine's own sense: a reversed edge's vertices come
            // back end first.
            let Some((a, b)) = ogeom_algo::edge_vertices(model, &edges[e])? else {
                ogeom_bail!(Construction, "a spine edge has no vertices");
            };
            Ok(if at_start { a } else { b })
        };
        if let Some(i) = start {
            let split = &splits[i];
            let far = ogeom_algo::make_vertex(model, split.at - split.after * split.run_on).shape;
            let near = traversal(model, run[0], true)?;
            let line: ogeom_geom::Curve =
                LineCurve::segment(split.at - split.after * split.run_on, split.at, tol)?.into();
            let domain = line.domain();
            wire_edges
                .push(ogeom_algo::make_edge_between(model, line, domain, &far, &near, tol)?.shape);
        }
        wire_edges.extend(run.iter().map(|&e| edges[e].clone()));
        if let Some(i) = end {
            let split = &splits[i];
            let near = traversal(model, run[run.len() - 1], false)?;
            let far = ogeom_algo::make_vertex(model, split.at + split.before * split.run_on).shape;
            let line: ogeom_geom::Curve =
                LineCurve::segment(split.at, split.at + split.before * split.run_on, tol)?.into();
            let domain = line.domain();
            wire_edges
                .push(ogeom_algo::make_edge_between(model, line, domain, &near, &far, tol)?.shape);
        }
        let sub_spine = ogeom_algo::make_wire(model, &wire_edges, tol)?.shape;
        // The profile where this piece starts: the spine's own start keeps
        // the caller's; a piece starting past a corner takes the profile
        // moved into the frame the corner's far side starts in, set back
        // along its run-on.
        let placed = match start {
            None => profile.clone(),
            Some(i) => {
                let split = &splits[i];
                let target = Frame::new(
                    split.at - split.after * split.run_on,
                    Direction::new(split.after, tol)?,
                    Direction::new(split.frame_after, tol)?,
                    tol,
                )?;
                let motion = Transform::from_frame(&target) * Transform::to_frame(&start_frame);
                realized_profile(model, profile, &motion, tol)?
            }
        };
        let mut piece = make_pipe_shell(model, &placed, &sub_spine, false, tolerance, tol)?.shape;
        if model.kind_of(&piece)? != ShapeType::Solid {
            ogeom_bail!(Construction, "a mitred piece did not sweep into a solid");
        }
        if let Some(i) = start {
            piece = ogeom_bool::common(model, &piece, &blocks[i], tol)?.shape;
        }
        if let Some(i) = end {
            piece = ogeom_bool::cut(model, &piece, &blocks[i], tol)?.shape;
        }
        joined.push(piece);
    }
    let result = fuse_in_order(model, joined, tol)?;
    let Some(shape) = result else {
        ogeom_bail!(Construction, "the spine produced no piece to sweep");
    };
    let mut history = History::new();
    history.generate(profile, shape.clone());
    for edge in &edges {
        history.generate(edge, shape.clone());
    }
    Ok(Built::new(shape, history))
}

/// A planar profile face rebuilt under a rigid motion: every edge's curve
/// moved and re-bounded, vertices shared, the face on the moved plane.
fn realized_profile(
    model: &mut Model,
    profile: &Shape,
    motion: &Transform,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    realized_profile_wound(model, profile, motion, None, tol)
}

/// As [`realized_profile`], each ring wound about `about` where given: the
/// outer ring turning positively, every hole the other way.
fn realized_profile_wound(
    model: &mut Model,
    profile: &Shape,
    motion: &Transform,
    about: Option<Vector>,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    use ogeom_geom::Transformable as _;
    let Some(plane) = ogeom_algo::find_plane(model, profile, tol)? else {
        ogeom_bail!(Construction, "a pipe shell sweeps a planar profile");
    };
    let moved_plane = Plane::through(
        motion.apply(plane.origin()),
        Direction::new(motion.apply_vector(plane.normal().vector()), tol)?,
    );
    let mut vertices: ogeom_core::FastMap<ogeom_topo::TShapeId, Shape> =
        ogeom_core::FastMap::default();
    let mut edge_copies: ogeom_core::FastMap<ogeom_topo::TShapeId, Shape> =
        ogeom_core::FastMap::default();
    let mut wires: Vec<Vec<Shape>> = Vec::new();
    for wire in explore(model, profile, Filter::OfType(ShapeType::Wire))? {
        let mut ring = Vec::new();
        for edge in model.ordered_children_of(&wire)? {
            let copy = match edge_copies.get(&edge.node()) {
                Some(done) => done.clone(),
                None => {
                    let (curve, range) = spine_curve_of(model, &edge)?;
                    let placed = curve.transformed(&edge.transform(model.datums())?, tol)?;
                    let moved = placed.transformed(motion, tol)?;
                    // The copy is of the edge itself, in its own sense; the
                    // ring's use of it is reapplied below.
                    let own = if edge.orientation() == ogeom_topo::Orientation::Reversed {
                        edge.reversed()
                    } else {
                        edge.clone()
                    };
                    let Some((a, b)) = ogeom_algo::edge_vertices(model, &own)? else {
                        ogeom_bail!(Construction, "a profile edge has no vertices");
                    };
                    let mut ends = Vec::with_capacity(2);
                    for v in [a, b] {
                        let key = v.node();
                        let held = match vertices.get(&key) {
                            Some(done) => done.clone(),
                            None => {
                                let Some(data) = model.node(&v).and_then(|n| n.data().as_vertex())
                                else {
                                    ogeom_bail!(Construction, "a profile vertex holds no data");
                                };
                                let at = v.transform(model.datums())?.apply(data.point);
                                let fresh = ogeom_algo::make_vertex(model, motion.apply(at)).shape;
                                vertices.insert(key, fresh.clone());
                                fresh
                            }
                        };
                        ends.push(held);
                    }
                    let fresh = ogeom_algo::make_edge_between(
                        model, moved, range, &ends[0], &ends[1], tol,
                    )?
                    .shape;
                    edge_copies.insert(edge.node(), fresh.clone());
                    fresh
                }
            };
            ring.push(if edge.orientation() == ogeom_topo::Orientation::Reversed {
                copy.reversed()
            } else {
                copy
            });
        }
        if let Some(axis) = about {
            let turning = ring_turning(model, &ring, axis, tol)?;
            let outer = wires.is_empty();
            if (turning > 0.0) != outer {
                ring = ring.iter().rev().map(Shape::reversed).collect();
            }
        }
        wires.push(ring);
    }
    let reach = 1e4_f64;
    let surface: SurfaceGeometry =
        PlaneSurface::over(moved_plane, (-reach, reach), (-reach, reach))?.into();
    Ok(ogeom_algo::make_face_with_pcurves(model, surface, &wires, tol)?.shape)
}

/// `ring` walked so it turns about `axis` positively where `outer`,
/// negatively otherwise: a face whose normal is `axis` keeps its material
/// on the left of an outer ring walked so, and of a hole walked the other
/// way.
fn walked_about(
    model: &Model,
    ring: &[Shape],
    axis: Vector,
    outer: bool,
    tol: Tolerances,
) -> OgeomResult<Vec<Shape>> {
    let turn = ring_turning(model, ring, axis, tol)?;
    Ok(if (turn > 0.0) == outer {
        ring.to_vec()
    } else {
        walked_back(ring)
    })
}

/// `ring` walked the other way round: its edges in reverse order, each
/// reversed.
fn walked_back(ring: &[Shape]) -> Vec<Shape> {
    ring.iter().rev().map(Shape::reversed).collect()
}

/// Twice the signed area a ring of edges encloses about `axis`, from its
/// edges sampled in the ring's own sense.
fn ring_turning(model: &Model, ring: &[Shape], axis: Vector, tol: Tolerances) -> OgeomResult<f64> {
    let mut points: Vec<Point> = Vec::new();
    for edge in ring {
        let (curve, range) = spine_curve_of(model, edge)?;
        let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
        for i in 0..32 {
            let f = f64::from(i) / 32.0;
            let t = if reversed {
                range.1 - (range.1 - range.0) * f
            } else {
                range.0 + (range.1 - range.0) * f
            };
            points.push(curve.point_at(t, tol)?);
        }
    }
    let Some(&origin) = points.first() else {
        return Ok(0.0);
    };
    let n = points.len();
    Ok((0..n)
        .map(|i| {
            (points[i] - origin)
                .cross(points[(i + 1) % n] - origin)
                .dot(axis)
        })
        .sum())
}

pub(crate) fn spine_curve_of(
    model: &Model,
    edge: &Shape,
) -> OgeomResult<(ogeom_geom::Curve, (f64, f64))> {
    let Some(data) = model.node(edge).and_then(|n| n.data().as_edge()) else {
        ogeom_bail!(Construction, "an edge holds no data");
    };
    let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
        ogeom_bail!(Construction, "an edge has no curve");
    };
    let Some(geometry) = model.geometry().curve(*curve) else {
        ogeom_bail!(Dangling, "curve is not in this model");
    };
    Ok((geometry.clone(), *range))
}

/// The pipe shell around a spine that loops back on itself: one wall,
/// closed both ways round, no caps at all.
///
/// The frames are rotation-minimizing with the loop's holonomy paid off:
/// transported round a closed spine, the frame comes home twisted by some
/// angle, and that twist is spread back along the arc so the last station's
/// frame *is* the first's; without it the closed fit fights a helical
/// grid. The profile may be smooth or faceted, and each hole sweeps a void
/// tunnel of its own shell; the Frenet law rides the loop as well.
fn closed_pipe_shell(
    model: &mut Model,
    profile: &Shape,
    spine: &Shape,
    mut stations: Vec<SpineStation>,
    frenet: bool,
    tolerance: f64,
    tol: Tolerances,
) -> OgeomResult<Built> {
    // The walk visits the join twice; the loop owns it once.
    let Some(home) = stations.pop() else {
        ogeom_bail!(Construction, "a closed spine needs room to turn");
    };
    if stations.len() < 3 {
        ogeom_bail!(Construction, "a closed spine needs room to turn");
    }
    // A sharp corner is a kink, and a kinked ring is mitred by the caller;
    // one arriving here has a heading that jumps between two stations.
    for i in 0..stations.len() {
        let next = &stations[(i + 1) % stations.len()];
        if stations[i].tangent.dot(next.tangent) < 0.9 {
            ogeom_bail!(
                Construction,
                "a closed spine turns too sharply between two of its stations to skin"
            );
        }
    }

    let loops: Vec<Shape> = match model.kind_of(profile)? {
        ShapeType::Face => explore(model, profile, Filter::OfType(ShapeType::Wire))?,
        ShapeType::Wire => vec![profile.clone()],
        other => ogeom_bail!(
            Construction,
            "a pipe shell sweeps a planar wire or face, not a {other:?}"
        ),
    };
    // Every wire sweeps its own closed shell: the outer boundary first,
    // each hole a void tunnel inside it.
    let profile_loop = &loops[0];
    let edges = model.ordered_children_of(profile_loop)?;
    let smooth = edges.len() == 1
        && ogeom_algo::edge_vertices(model, &edges[0])?.is_some_and(|(a, b)| a.is_same(&b));
    let Some(plane) = ogeom_algo::find_plane(model, profile, tol)? else {
        ogeom_bail!(Construction, "a pipe shell sweeps a planar profile");
    };
    let t0 = stations[0].tangent;
    // Square to the spine's own start tangent, read exactly off its first
    // edge, to an angle's tolerance.
    let exact_t0 = {
        let first = match model.kind_of(spine)? {
            ShapeType::Edge => spine.clone(),
            _ => model.ordered_children_of(spine)?[0].clone(),
        };
        let (curve, range) = spine_curve_of(model, &first)?;
        let reversed = first.orientation() == ogeom_topo::Orientation::Reversed;
        let d = curve.d1_at(if reversed { range.1 } else { range.0 }, tol)?;
        let d = if reversed { -d } else { d };
        d / d.magnitude()
    };
    if plane.normal().vector().cross(exact_t0).magnitude() > tol.angular() {
        ogeom_bail!(
            Construction,
            "the profile leans along its spine; a pipe shell runs square to \
             the start"
        );
    }
    if plane.distance_to(stations[0].at) > tol.confusion() * 100.0 {
        ogeom_bail!(
            Construction,
            "the profile does not sit at the spine's start"
        );
    }

    // Frames with the loop's mismatch paid off: carry once more back to the
    // start, read the twist between departure and return, and spread it
    // along the arc. Rotation-minimizing frames owe this for their
    // holonomy; the Frenet law owes it too, because straight stretches
    // carry the frame through by continuation and the continuation is
    // path-dependent. One reconciliation serves both.
    let mut normals: Vec<Vector> = if frenet {
        // The Frenet frame is the spine's own, single-valued round a loop:
        // read with wrapped neighbours it closes on itself and owes no
        // reconciliation. Read from a walk that visits the join twice it
        // does not: the one-sided differences at the walk's two ends
        // disagree with the interior, and the strips built on them miss
        // each other at the join by that kink.
        frenet_normals_closed(&stations, tol)?
    } else {
        let mut extended = stations.clone();
        extended.push(stations[0]);
        let carried = rmf_normals(&extended);
        let (n0, n_home) = (carried[0], carried[carried.len() - 1]);
        let twist = (n0.cross(n_home).dot(t0)).atan2(n0.dot(n_home));
        let mut lengths = vec![0.0_f64];
        for pair in extended.windows(2) {
            let last = lengths[lengths.len() - 1];
            lengths.push(last + pair[0].at.distance(pair[1].at));
        }
        let total = lengths[lengths.len() - 1];
        carried
            .iter()
            .take(stations.len())
            .enumerate()
            .map(|(i, n)| {
                let phi = -twist * lengths[i] / total;
                let t = extended[i].tangent;
                *n * phi.cos() + t.cross(*n) * phi.sin()
            })
            .collect()
    };
    for (n, station) in normals.iter_mut().zip(&stations) {
        // Re-square each corrected normal against its own tangent.
        let v = *n - station.tangent * n.dot(station.tangent);
        *n = v / v.magnitude();
    }

    let x0 = normals[0];
    let origin = stations[0].at;
    // The way round once more to its start, at the end of the spine's
    // range, so the frame is carried between the last station and home.
    let (round, round_normals) = {
        let mut round = stations.clone();
        round.push(SpineStation {
            tangent: stations[0].tangent,
            ..home
        });
        let mut normals = normals.clone();
        normals.push(normals[0]);
        (round, normals)
    };
    let walk = SpineWalk {
        curves: walk_curves(model, spine)?,
        stations: &round,
        normals: &round_normals,
    };
    let mut shells: Vec<Shape> = Vec::with_capacity(loops.len());
    for (li, wire) in loops.iter().enumerate() {
        let wire_edges = model.ordered_children_of(wire)?;
        let wire_smooth = wire_edges.len() == 1
            && ogeom_algo::edge_vertices(model, &wire_edges[0])?
                .is_some_and(|(a, b)| a.is_same(&b));
        let shell = closed_loop_shell(
            model,
            wire,
            &wire_edges,
            wire_smooth,
            &walk,
            (origin, x0),
            tolerance,
            tol,
        )?;
        // The material side follows each loop's own winding, so it is
        // read off the shell itself: the outer shell faces out of what it
        // encloses, a void's faces toward its tunnel.
        let enclosed = shell_signed_volume(model, &shell, tol)?;
        let outward = enclosed > 0.0;
        shells.push(if outward == (li == 0) {
            shell
        } else {
            shell.reversed()
        });
    }
    let mut built = make_solid(model, &shells)?;
    built.history.generate(profile, built.shape.clone());
    built.history.generate(spine, built.shape.clone());
    let _ = (smooth, profile_loop, edges);
    Ok(built)
}

/// The volume a closed shell encloses as it faces, from its mesh: negative
/// where its faces point into what it bounds.
fn shell_signed_volume(model: &Model, shell: &Shape, tol: Tolerances) -> OgeomResult<f64> {
    Ok(ogeom_mesh::triangulate(model, shell, ogeom_mesh::Deflection::default(), tol)?.volume())
}

/// Sample a spine (one edge or a wire of them) into stations, each edge
/// given a station count by its own turning.
fn shell_stations(model: &Model, spine: &Shape, tol: Tolerances) -> OgeomResult<Vec<SpineStation>> {
    let edges: Vec<Shape> = match model.kind_of(spine)? {
        ShapeType::Edge => vec![spine.clone()],
        ShapeType::Wire => model.ordered_children_of(spine)?,
        other => ogeom_bail!(
            Construction,
            "a pipe shell runs along an edge or a wire, not a {other:?}"
        ),
    };
    if edges.is_empty() {
        ogeom_bail!(Construction, "the spine has no edge to run along");
    }
    let mut stations: Vec<SpineStation> = Vec::new();
    for (ei, edge) in edges.iter().enumerate() {
        let (curve, range) = {
            let Some(data) = model.node(edge).and_then(|n| n.data().as_edge()) else {
                ogeom_bail!(Construction, "a spine edge holds no data");
            };
            let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
                ogeom_bail!(Construction, "a spine edge has no curve");
            };
            let Some(geometry) = model.geometry().curve(*curve) else {
                ogeom_bail!(Dangling, "curve is not in this model");
            };
            (geometry.clone(), *range)
        };
        let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
        // Stations by turning: sample tangents coarsely, sum the angles, and
        // give each edge enough stations that no step turns more than a few
        // degrees. A straight edge keeps a healthy minimum for the fit.
        let turning = {
            let mut sum = 0.0_f64;
            let mut last: Option<Vector> = None;
            for i in 0..=16 {
                let t = range.0 + (range.1 - range.0) * f64::from(i) / 16.0;
                let d = curve.d1_at(t, tol)?;
                let m = d.magnitude();
                if m <= tol.confusion() {
                    continue;
                }
                let u = d / m;
                if let Some(prev) = last {
                    sum += prev.dot(u).clamp(-1.0, 1.0).acos() * 16.0 / 16.0;
                }
                last = Some(u);
            }
            sum
        };
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let count = (turning / (core::f64::consts::TAU / 64.0)).ceil().max(8.0) as usize;
        for i in 0..=count {
            #[allow(clippy::cast_precision_loss)]
            let f = (i as f64) / (count as f64);
            let t = if reversed {
                range.1 - (range.1 - range.0) * f
            } else {
                range.0 + (range.1 - range.0) * f
            };
            let p = curve.point_at(t, tol)?;
            let d = curve.d1_at(t, tol)?;
            let m = d.magnitude();
            if m <= tol.confusion() {
                ogeom_bail!(Construction, "the spine is degenerate at {t}");
            }
            let tangent = if reversed { -(d / m) } else { d / m };
            if let Some(prev) = stations.last()
                && prev.edge == ei
                && prev.at.distance(p) <= tol.confusion()
                && prev.tangent.cross(tangent).magnitude() <= tol.angular()
                && prev.tangent.dot(tangent) > 0.0
            {
                continue;
            }
            // A station coincident with the last but on the next edge is a
            // twin: heading elsewhere it is a *corner* the sweep mitres, and
            // heading on it is a smooth junction where the next edge's own
            // run of skin begins, since one fit across two curves' joins
            // cannot follow the step in their curvature.
            stations.push(SpineStation {
                at: p,
                tangent,
                edge: ei,
                t,
            });
        }
    }
    if stations.len() < 2 {
        ogeom_bail!(Construction, "the spine collapses to a point");
    }
    Ok(stations)
}

/// Frenet normals: each station's frame turns with the spine's own
/// curvature, read from the tangents' finite differences. Straight runs
/// carry the last bending station's normal forward; a spine that never
/// bends has no Frenet frame at all and is refused by name.
fn frenet_normals(stations: &[SpineStation], tol: Tolerances) -> OgeomResult<Vec<Vector>> {
    let mut normals: Vec<Option<Vector>> = Vec::with_capacity(stations.len());
    for i in 0..stations.len() {
        let (before, after) = (
            &stations[i.saturating_sub(1)],
            &stations[(i + 1).min(stations.len() - 1)],
        );
        let dt = after.tangent - before.tangent;
        let t = stations[i].tangent;
        let bend = dt - t * dt.dot(t);
        let m = bend.magnitude();
        normals.push(if m > tol.angular().max(1e-9) {
            Some(bend / m)
        } else {
            None
        });
    }
    // Carry forward, then backward, so straight lead-ins take the first
    // bend's frame rather than none.
    let mut carried: Vec<Vector> = Vec::with_capacity(stations.len());
    let mut last: Option<Vector> = None;
    for n in &normals {
        if let Some(n) = n {
            last = Some(*n);
        }
        carried.push(last.unwrap_or(Vector::new(0.0, 0.0, 0.0)));
    }
    let mut ahead: Option<Vector> = None;
    for i in (0..stations.len()).rev() {
        if let Some(n) = normals[i] {
            ahead = Some(n);
        } else if carried[i].magnitude() < 0.5
            && let Some(n) = ahead
        {
            carried[i] = n;
        }
    }
    if carried.iter().any(|n| n.magnitude() < 0.5) {
        ogeom_bail!(
            Construction,
            "a straight spine has no Frenet frame; use the \
             rotation-minimizing default"
        );
    }
    Ok(carried)
}

/// Frenet normals round a closed loop: each station's bend read from its
/// neighbours across the join as well, so the field is periodic. A loop
/// with a straight stretch carries the last bend's normal through it, as
/// the open form does; a loop that never bends has no Frenet frame.
fn frenet_normals_closed(stations: &[SpineStation], tol: Tolerances) -> OgeomResult<Vec<Vector>> {
    let n = stations.len();
    let mut normals: Vec<Option<Vector>> = Vec::with_capacity(n);
    for i in 0..n {
        let (before, after) = (&stations[(i + n - 1) % n], &stations[(i + 1) % n]);
        let dt = after.tangent - before.tangent;
        let t = stations[i].tangent;
        let bend = dt - t * dt.dot(t);
        let m = bend.magnitude();
        normals.push(if m > tol.angular().max(1e-9) {
            Some(bend / m)
        } else {
            None
        });
    }
    let Some(first_bend) = normals.iter().position(Option::is_some) else {
        ogeom_bail!(
            Construction,
            "a straight spine has no Frenet frame; use the \
             rotation-minimizing default"
        );
    };
    // Carry forward round the loop from the first bend, so a straight
    // stretch anywhere takes the bend behind it.
    let mut carried: Vec<Vector> = vec![Vector::new(0.0, 0.0, 0.0); n];
    let mut last = normals[first_bend].unwrap_or_else(|| unreachable!());
    for k in 0..n {
        let i = (first_bend + k) % n;
        if let Some(bend) = normals[i] {
            last = bend;
        }
        carried[i] = last;
    }
    Ok(carried)
}

// --- the evolved shape -------------------------------------------------------

/// One station of the spine: where it is, which way it runs, and how it gets
/// there.
struct Station {
    /// Where the traversal enters and leaves this edge.
    from: Point,
    to: Point,
    /// The unit tangent at each end, in the direction of travel.
    tangent_in: Vector,
    tangent_out: Vector,
    /// A straight run, or a turn about an axis through an angle.
    turn: Option<(ogeom_math::Axis, f64)>,
}

/// Sweep a profile along a spine, the way a moulding runs round a frame.
///
/// The spine is a **planar** wire, or a planar face whose outer wire is taken.
/// The profile is a wire standing in a plane that contains the spine's own
/// normal, positioned where the spine starts. What comes back is what the
/// profile sweeps out as it travels the spine, always square to it:
///
/// - a straight spine edge extrudes the profile (a prism);
/// - a circular one turns it about that arc's own axis (a revolution);
/// - and each corner between them turns it about the corner, through exactly
///   the angle the spine turns there, which is the join the 2D offset makes
///   for the same reason.
///
/// Every piece is exact: the surfaces are the ones a prism and a revolution
/// give for the profile's own curves, and nothing is fitted. The pieces are
/// then unioned, which is the assembly's real name: consecutive pieces meet
/// on the *same* placed profile, and a coincident face is what the boolean
/// identifies rather than probes across.
///
/// # Volume or shell
///
/// The result is always a volume, and which spine is given is what says
/// whether there is one to have. A **closed** profile bounds its own section
/// and sweeps a solid along either kind of spine. An **open** one does not,
/// and there is exactly one honest way to close it: against the plane a
/// **face** spine was drawn in, whose own plane the profile's two ends must
/// reach. An open profile along a wire spine is refused, and the refusal says
/// which spine would close it.
///
/// # Errors
///
/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if the spine is
/// not a planar wire or face, if it carries an edge that is neither straight
/// nor circular, if the profile is not planar, if the profile's plane does not
/// contain the spine's normal or does not cut across it (a profile that leans
/// or lies along is not square to the spine), or if an open profile has no
/// spine plane to close against.
/// [`OgeomError::NotDone`](ogeom_core::OgeomError::NotDone) where a corner's turn
/// would sweep the profile across the corner itself, which no revolution can
/// express.
pub fn make_evolved(
    model: &mut Model,
    spine: &Shape,
    profile: &Shape,
    tol: Tolerances,
) -> OgeomResult<Built> {
    use ogeom_algo::{make_prism, make_revolution, transformed};

    let (wire, capped_by_spine_plane) = match model.kind_of(spine)? {
        ShapeType::Face => {
            let wires = explore(model, spine, Filter::OfType(ShapeType::Wire))?;
            let Some(outer) = wires.first().cloned() else {
                ogeom_bail!(Construction, "a face with no wire has no spine to run");
            };
            (outer, true)
        }
        ShapeType::Wire => (spine.clone(), false),
        other => ogeom_bail!(
            Construction,
            "a {other:?} is not a spine; sweep along a wire or a planar face"
        ),
    };

    let stations = spine_stations(model, &wire, tol)?;
    if stations.is_empty() {
        ogeom_bail!(Construction, "a spine with no edges goes nowhere");
    }
    let normal = spine_normal(&stations, tol)?;
    let (profile_origin, profile_normal) = profile_plane(model, profile, tol)?;
    if profile_normal.dot(normal.vector()).abs() > tol.angular() {
        ogeom_bail!(
            Construction,
            "the profile's plane must contain the spine's normal, or the \
             profile is not square to the spine it travels"
        );
    }
    let start = &stations[0];
    if profile_normal.cross(start.tangent_in).magnitude() > tol.angular() {
        ogeom_bail!(
            Construction,
            "the profile's plane must cut the spine across, not run along it: \
             the profile is not square to the spine it travels"
        );
    }
    let _ = profile_origin;
    let reference = (start.from, start.tangent_in);

    // The profile as a face, which is what makes each swept piece a *solid*
    // and the assembly a union rather than a hopeful sew. An open profile is
    // closed against the spine's own plane, which is exactly what a face
    // spine offers and a wire spine does not.
    let section = profile_face(
        model,
        profile,
        profile_normal,
        capped_by_spine_plane.then(|| Plane::through(start.from, normal)),
        tol,
    )?;

    let mut pieces: Vec<Shape> = Vec::new();
    for (index, station) in stations.iter().enumerate() {
        // The corner *before* this station, so the pieces come out in the
        // order the spine runs them.
        if index > 0 {
            let previous = &stations[index - 1];
            if let Some(piece) = corner_piece(
                model,
                &section,
                reference,
                previous.to,
                previous.tangent_out,
                station.tangent_in,
                normal,
                tol,
            )? {
                pieces.push(piece);
            }
        }
        let placed = transformed(
            model,
            &section,
            station_transform(reference, station.from, station.tangent_in, normal, tol)?,
        )?
        .shape;
        pieces.push(match station.turn {
            None => make_prism(model, &placed, station.to - station.from, tol)?.shape,
            Some((axis, angle)) => make_revolution(model, &placed, axis, angle, tol)?.shape,
        });
    }
    // A closed spine turns at the join between its last edge and its first
    // just as it does anywhere else.
    let last = &stations[stations.len() - 1];
    if last.to.distance(start.from) <= tol.confusion()
        && let Some(piece) = corner_piece(
            model,
            &section,
            reference,
            last.to,
            last.tangent_out,
            start.tangent_in,
            normal,
            tol,
        )?
    {
        pieces.push(piece);
    }

    // The union, in the order the spine runs: consecutive pieces meet on the
    // *same* placed profile, which is the coincident-face case the boolean
    // resolves by identifying it rather than by probing across it.
    let mut history = History::new();
    let Some(shape) = fuse_in_order(model, pieces, tol)? else {
        ogeom_bail!(Construction, "the spine produced no piece to sweep");
    };
    history.generate(spine, shape.clone());
    history.generate(profile, shape.clone());
    Ok(Built::new(shape, history))
}

/// The profile as a face.
///
/// A closed profile bounds its own area. An open one does not, and there is
/// exactly one honest way to close it: against the plane the spine was given
/// as a face *in*, which is what a face spine says to do and a wire spine has
/// no answer for. The closing segment runs between the profile's two ends, and
/// both have to be on that plane or the profile does not reach it.
fn profile_face(
    model: &mut Model,
    profile: &Shape,
    profile_normal: Vector,
    against: Option<Plane>,
    tol: Tolerances,
) -> OgeomResult<Shape> {
    if model.kind_of(profile)? == ShapeType::Face {
        return Ok(profile.clone());
    }
    if model.kind_of(profile)? != ShapeType::Wire {
        ogeom_bail!(Construction, "a profile is a wire or a face");
    }
    let mut edges = ogeom_topo::explore(model, profile, Filter::OfType(ShapeType::Edge))?;
    let closed = ogeom_algo::is_wire_closed(model, profile, tol)?;
    if !closed {
        let Some(plane) = against else {
            ogeom_bail!(
                Construction,
                "an open profile sweeps a shell, not a volume; give the spine \
                 as a planar face for its plane to close the profile against, \
                 or close the profile itself"
            );
        };
        let [(from, v0), (to, v1)] = wire_ends(model, profile, tol)?;
        for end in [from, to] {
            if plane.signed_distance_to(end).abs() > tol.confusion() * 1e2 {
                ogeom_bail!(
                    Construction,
                    "an open profile is closed against the spine face's own \
                     plane, and this one does not reach it"
                );
            }
        }
        // Built on the profile's *own* end vertices, so the closed ring is a
        // wire rather than edges that merely touch.
        let line = LineCurve::new(ogeom_math::Axis {
            location: from,
            direction: Direction::new(to - from, tol)?,
        });
        edges.push(
            make_edge_between(model, line.into(), (0.0, from.distance(to)), &v0, &v1, tol)?.shape,
        );
    }
    let ordered = ogeom_algo::order_edges(model, &edges, tol)?;
    let mut bound = ogeom_math::Aabb::EMPTY;
    for edge in &ordered {
        bound = bound.union(&ogeom_algo::shape_bounds(model, edge, tol)?);
    }
    let Some(centre) = bound.centre() else {
        ogeom_bail!(Construction, "a profile with no extent sweeps nothing");
    };
    let reach = bound.diagonal().mul_add(2.0, 1.0);
    let plane = Plane::through(centre, Direction::new(profile_normal, tol)?);
    let surface = PlaneSurface::over(plane, (-reach, reach), (-reach, reach))?;
    Ok(make_face_with_pcurves(model, surface.into(), &[ordered], tol)?.shape)
}

/// Where an open wire begins and ends: the point, and the vertex there.
fn wire_ends(model: &Model, wire: &Shape, tol: Tolerances) -> OgeomResult<[(Point, Shape); 2]> {
    let mut counts: Vec<(Point, Shape, usize)> = Vec::new();
    for edge in explore(model, wire, Filter::OfType(ShapeType::Edge))? {
        for v in explore(model, &edge, Filter::OfType(ShapeType::Vertex))? {
            let Some(data) = model.node(&v).and_then(|n| n.data().as_vertex()) else {
                continue;
            };
            let at = v.transform(model.datums())?.apply(data.point);
            match counts
                .iter_mut()
                .find(|(p, _, _)| p.distance(at) <= tol.confusion() * 10.0)
            {
                Some((_, _, n)) => *n += 1,
                None => counts.push((at, v.clone(), 1)),
            }
        }
    }
    let free: Vec<(Point, Shape)> = counts
        .into_iter()
        .filter(|(_, _, n)| *n == 1)
        .map(|(p, v, _)| (p, v))
        .collect();
    if free.len() != 2 {
        ogeom_bail!(
            Construction,
            "an open profile has exactly two ends; this one has {}",
            free.len()
        );
    }
    let mut ends = free.into_iter();
    let (Some(a), Some(b)) = (ends.next(), ends.next()) else {
        ogeom_bail!(Construction, "the profile lost an end between checks");
    };
    Ok([a, b])
}

/// The spine, edge by edge, in the order the wire runs it.
fn spine_stations(model: &Model, wire: &Shape, tol: Tolerances) -> OgeomResult<Vec<Station>> {
    let mut out = Vec::new();
    for edge in explore(model, wire, Filter::OfType(ShapeType::Edge))? {
        let Some(data) = model.node(&edge).and_then(|n| n.data().as_edge()) else {
            ogeom_bail!(Construction, "a spine edge is not in this model");
        };
        let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
            ogeom_bail!(Construction, "a spine edge with no curve runs nowhere");
        };
        let Some(geometry) = model.geometry().curve(*curve) else {
            ogeom_bail!(Dangling, "curve is not in this model");
        };
        let placed = geometry.transformed(&edge.transform(model.datums())?, tol)?;
        let reversed = edge.orientation() == ogeom_topo::Orientation::Reversed;
        let (t0, t1) = if reversed {
            (range.1, range.0)
        } else {
            (range.0, range.1)
        };
        let sign = if reversed { -1.0 } else { 1.0 };
        let unit = |t: f64| -> OgeomResult<Vector> {
            let d = placed.d1_at(t, tol)? * sign;
            if d.magnitude() <= tol.confusion() {
                ogeom_bail!(Construction, "a spine edge has no direction at {t}");
            }
            Ok(d / d.magnitude())
        };
        let station = match &placed {
            Curve::Line(_) => Station {
                from: placed.point_at(t0, tol)?,
                to: placed.point_at(t1, tol)?,
                tangent_in: unit(t0)?,
                tangent_out: unit(t1)?,
                turn: None,
            },
            Curve::Circle(c) => {
                let circle = c.circle();
                let swept = (range.1 - range.0).abs();
                let axis = ogeom_math::Axis {
                    location: circle.centre(),
                    direction: if reversed {
                        -circle.frame().z()
                    } else {
                        circle.frame().z()
                    },
                };
                Station {
                    from: placed.point_at(t0, tol)?,
                    to: placed.point_at(t1, tol)?,
                    tangent_in: unit(t0)?,
                    tangent_out: unit(t1)?,
                    turn: Some((axis, swept)),
                }
            }
            other => ogeom_bail!(
                Construction,
                "a spine runs on straight and circular edges; a {:?} sweeps a \
                 surface this construction does not have",
                other.kind()
            ),
        };
        out.push(station);
    }
    Ok(out)
}

/// The spine's own normal, and the check that it has one.
///
/// Taken from the first turn the spine makes (a corner or an arc) because
/// that is exact, and then measured against every station: a spine that
/// leaves its own plane has no square profile to carry, and says so here
/// rather than by producing a shape nobody asked for.
fn spine_normal(stations: &[Station], tol: Tolerances) -> OgeomResult<Direction> {
    let mut best: Option<(f64, Vector)> = None;
    let mut consider = |a: Vector, b: Vector| {
        let cross = a.cross(b);
        let magnitude = cross.magnitude();
        if magnitude > best.map_or(tol.angular(), |(m, _)| m) {
            best = Some((magnitude, cross / magnitude));
        }
    };
    for (index, station) in stations.iter().enumerate() {
        consider(station.tangent_in, station.tangent_out);
        if index + 1 < stations.len() {
            consider(station.tangent_out, stations[index + 1].tangent_in);
        }
    }
    if stations.len() > 1 {
        consider(
            stations[stations.len() - 1].tangent_out,
            stations[0].tangent_in,
        );
    }
    let Some((_, normal)) = best else {
        ogeom_bail!(
            Construction,
            "a spine that never turns has no plane of its own; give the \
             profile's own orientation a spine with at least one corner or arc"
        );
    };
    for station in stations {
        for tangent in [station.tangent_in, station.tangent_out] {
            if tangent.dot(normal).abs() > tol.angular() {
                ogeom_bail!(
                    Construction,
                    "the spine leaves its own plane; an evolved sweep runs a \
                     planar spine"
                );
            }
        }
        if let Some((axis, _)) = &station.turn
            && axis.direction.vector().cross(normal).magnitude() > tol.angular()
        {
            ogeom_bail!(
                Construction,
                "a spine arc turns about an axis off the spine's own normal"
            );
        }
    }
    Direction::new(normal, tol)
}

/// The profile's plane: a point on it and its normal.
fn profile_plane(model: &Model, profile: &Shape, tol: Tolerances) -> OgeomResult<(Point, Vector)> {
    let mut points: Vec<Point> = Vec::new();
    for edge in explore(model, profile, Filter::OfType(ShapeType::Edge))? {
        let Some(data) = model.node(&edge).and_then(|n| n.data().as_edge()) else {
            continue;
        };
        let Some(EdgeRepr::Curve3d { curve, range, .. }) = data.curve3d() else {
            continue;
        };
        let Some(geometry) = model.geometry().curve(*curve) else {
            ogeom_bail!(Dangling, "curve is not in this model");
        };
        let placed = geometry.transformed(&edge.transform(model.datums())?, tol)?;
        for i in 0..=8 {
            let t = range.0 + (range.1 - range.0) * f64::from(i) / 8.0;
            points.push(placed.point_at(t, tol)?);
        }
    }
    if points.len() < 3 {
        ogeom_bail!(Construction, "a profile needs an extent to sweep");
    }
    let origin = points[0];
    // The widest cross product among the sampled offsets: the plane's normal,
    // taken where it is best conditioned rather than from the first three
    // points that happen to be there.
    let mut best: Option<(f64, Vector)> = None;
    for (i, a) in points.iter().enumerate() {
        for b in points.iter().skip(i + 1) {
            let cross = (*a - origin).cross(*b - origin);
            let magnitude = cross.magnitude();
            if magnitude > best.map_or(tol.confusion(), |(m, _)| m) {
                best = Some((magnitude, cross / magnitude));
            }
        }
    }
    let Some((_, normal)) = best else {
        ogeom_bail!(Construction, "a profile with no area has no plane");
    };
    for p in &points {
        if (*p - origin).dot(normal).abs() > tol.confusion() * 1e2 {
            ogeom_bail!(Construction, "the profile is not planar");
        }
    }
    Ok((origin, normal))
}

/// The rigid motion that carries the profile from the spine's start to a
/// station: a turn about the spine's normal, then a translation.
fn station_transform(
    reference: (Point, Vector),
    at: Point,
    tangent: Vector,
    normal: Direction,
    tol: Tolerances,
) -> OgeomResult<Transform> {
    let (origin, from) = reference;
    let n = normal.vector();
    let angle = from.cross(tangent).dot(n).atan2(from.dot(tangent));
    let turn = if angle.abs() <= tol.angular() {
        Transform::IDENTITY
    } else {
        Transform::rotation(
            ogeom_math::Axis {
                location: origin,
                direction: normal,
            },
            angle,
        )
    };
    Ok(Transform::translation(at - origin) * turn)
}

/// The wedge a corner adds: the profile turned about the corner, through
/// exactly the angle the spine turns there.
///
/// `None` where the spine does not turn; two edges meeting smoothly leave no
/// wedge to fill.
#[allow(clippy::too_many_arguments)]
fn corner_piece(
    model: &mut Model,
    profile: &Shape,
    reference: (Point, Vector),
    corner: Point,
    incoming: Vector,
    outgoing: Vector,
    normal: Direction,
    tol: Tolerances,
) -> OgeomResult<Option<Shape>> {
    let n = normal.vector();
    let angle = incoming
        .cross(outgoing)
        .dot(n)
        .atan2(incoming.dot(outgoing));
    if angle.abs() <= tol.angular() {
        return Ok(None);
    }
    let placed = ogeom_algo::transformed(
        model,
        profile,
        station_transform(reference, corner, incoming, normal, tol)?,
    )?
    .shape;
    let axis = ogeom_math::Axis {
        location: corner,
        direction: if angle > 0.0 { normal } else { -normal },
    };
    let turned = ogeom_algo::make_revolution(model, &placed, axis, angle.abs(), tol);
    match turned {
        Ok(built) => Ok(Some(built.shape)),
        Err(_) => ogeom_bail!(
            NotDone,
            "the profile straddles the spine at a corner, so turning it about \
             that corner sweeps it through itself; there is no revolution for \
             that wedge"
        ),
    }
}

/// Pieces laid end to end, fused: pairs of neighbours first, then pairs of
/// those, so each fuse joins two runs of about equal size where one at a
/// time fused every piece onto everything before it, redoing the whole run
/// so far each time. Neighbours stay neighbours, so every fuse still meets
/// its partner across the shared section. `None` for no pieces.
fn fuse_in_order(
    model: &mut Model,
    pieces: Vec<Shape>,
    tol: Tolerances,
) -> OgeomResult<Option<Shape>> {
    let mut runs = pieces;
    while runs.len() > 1 {
        let mut next = Vec::with_capacity(runs.len().div_ceil(2));
        let mut pending = runs.into_iter();
        while let Some(first) = pending.next() {
            match pending.next() {
                Some(second) => next.push(ogeom_bool::fuse(model, &first, &second, tol)?.shape),
                None => next.push(first),
            }
        }
        runs = next;
    }
    Ok(runs.pop())
}