BREP_construction 0.26.0

Solid construction of the BREP kernel: extrusions, revolutions, sweeps and lofts.
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
//! Gear sections and gear solids.
//!
//! An involute gear is built the way it is cut: its section is the envelope of a
//! rack cutter rolled round the pitch circle. A rack point `q` with outward normal
//! `n` touches the gear when its normal passes through the pitch point; with the
//! gear's tooth 0 centred on +x, the rack's rolling line on `x = r` and the rack
//! displaced by `s` along +y, that is
//!
//! ```text
//!   s = (q.x - r) n.y / n.x - q.y,      gear point = Rot(-s / r) (q.x, q.y + s).
//! ```
//!
//! The cutter's straight flank generates the involute; its tip fillet (radius
//! `rho`) generates the root fillet, the equidistant of the trochoid traced by
//! the fillet's centre, and so the real undercut when the tooth count is small.
//! Neither curve is rational: each is fitted by a cubic B-spline (C1 Hermite
//! spans, refined until every span is within the fit bound of the closed form at
//! its sample parameters), while the tip and root lands are exact circular arcs.
use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
use std::f64::consts::{PI, TAU};

/// The fit bound of every fitted gear curve, as a fraction of the module: the
/// largest distance, at the span sample parameters, between a fitted curve and
/// its closed form.
pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;

/// An external spur gear generated by a standard rack cutter. Lengths in model
/// units, angles in radians; coefficients are multiples of the module.
#[derive(Clone, Debug)]
pub struct SpurGear {
    pub module: f64,
    pub teeth: usize,
    pub pressure_angle: f64,
    /// Profile shift coefficient x (the cutter moved out by x · module).
    pub profile_shift: f64,
    /// Addendum coefficient ha* (tip radius = r + (ha* + x) m).
    pub addendum: f64,
    /// Dedendum coefficient hf* (root radius = r - (hf* - x) m).
    pub dedendum: f64,
    /// Cutter tip radius coefficient rho_f*.
    pub root_fillet: f64,
    /// Circumferential backlash taken off the tooth thickness on the reference circle.
    pub backlash: f64,
    pub face_width: f64,
}

impl Default for SpurGear {
    fn default() -> Self {
        Self {
            module: 2.0,
            teeth: 20,
            pressure_angle: 20f64.to_radians(),
            profile_shift: 0.0,
            addendum: 1.0,
            dedendum: 1.25,
            root_fillet: 0.38,
            backlash: 0.0,
            face_width: 10.0,
        }
    }
}

/// Derived data of a generated gear (diameters in model units).
#[derive(Clone, Debug, Default)]
pub struct GearData {
    pub pitch_diameter: f64,
    pub base_diameter: f64,
    pub tip_diameter: f64,
    pub root_diameter: f64,
    /// Diameter where the involute flank meets the root fillet.
    pub form_diameter: f64,
    /// Tooth thickness on the reference (pitch) circle, arc length.
    pub tooth_thickness: f64,
    /// Tooth thickness on the tip circle, arc length.
    pub tip_thickness: f64,
    /// Whether the root fillet cuts into the involute (generated undercut).
    pub undercut: bool,
    /// The smallest profile shift at which this gear has no undercut.
    pub min_shift_without_undercut: f64,
}

/// One curve of a gear section with the face role it gives the solid.
#[derive(Clone, Debug)]
pub struct SectionCurve {
    pub curve: NurbsCurve,
    /// Face role: `V`/`W` root fillets, `R`/`L` flanks, `K` tip land, `G` root land.
    pub role: &'static str,
    pub tooth: usize,
}

impl SectionCurve {
    /// The face-name suffix this curve's face carries (`R3`, `K0`, …).
    pub fn suffix(&self) -> String {
        format!("{}{}", self.role, self.tooth)
    }
}

/// A closed gear section in the z = 0 plane, counter-clockwise about +z.
#[derive(Clone, Debug)]
pub struct GearSection {
    pub curves: Vec<SectionCurve>,
    pub data: GearData,
}

fn refuse(code: &str, message: String) -> KernelRefusal {
    KernelRefusal::input(KernelStage::Collect, code, message)
}

fn rotate(point: [f64; 2], angle: f64) -> [f64; 2] {
    let (s, c) = angle.sin_cos();
    [c * point[0] - s * point[1], s * point[0] + c * point[1]]
}

fn polar_angle(point: [f64; 2]) -> f64 {
    point[1].atan2(point[0])
}

fn radius_of(point: [f64; 2]) -> f64 {
    point[0].hypot(point[1])
}

/// The rack cutter of a spur gear in the generating frame, and its envelope.
struct RackCutter {
    r: f64,
    alpha: f64,
    /// Reference line of the cutter (x).
    x_ref: f64,
    /// The cutter flank's y on the reference line.
    y0: f64,
    /// Root radius = the cutter tip line (x).
    r_f: f64,
    rho: f64,
    /// Tip fillet centre.
    centre: [f64; 2],
}

impl RackCutter {
    fn new(gear: &SpurGear) -> Self {
        let m = gear.module;
        let r = m * gear.teeth as f64 / 2.0;
        let p = PI * m;
        let alpha = gear.pressure_angle;
        let x_ref = r + gear.profile_shift * m;
        let y0 = p / 4.0 - gear.backlash / 2.0;
        let r_f = x_ref - gear.dedendum * m;
        let rho = gear.root_fillet * m;
        let x_c = r_f + rho;
        let y_c = y0 + (rho + (x_ref - x_c) * alpha.sin()) / alpha.cos();
        Self { r, alpha, x_ref, y0, r_f, rho, centre: [x_c, y_c] }
    }

    /// The gear point generated by the rack point `q` with outward normal `n`.
    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
        let s = (q[0] - self.r) * n[1] / n[0] - q[1];
        rotate([q[0], q[1] + s], -s / self.r)
    }

    /// The involute flank (left side of tooth 0) generated by the flank point at `x`.
    fn flank(&self, x: f64) -> [f64; 2] {
        let a = self.alpha;
        let q = [x, self.y0 + (self.x_ref - x) * a.tan()];
        self.envelope(q, [-a.sin(), -a.cos()])
    }

    /// The root fillet (left side of tooth 0) generated by the cutter tip fillet
    /// at normal angle `psi` (0 = the tip line, pi/2 - alpha = the flank).
    fn fillet(&self, psi: f64) -> [f64; 2] {
        let n = [-psi.cos(), -psi.sin()];
        if self.rho == 0.0 {
            // A sharp cutter corner: the point is fixed, its normal still sweeps.
            return self.envelope(self.centre, n);
        }
        let q = [self.centre[0] + self.rho * n[0], self.centre[1] + self.rho * n[1]];
        self.envelope(q, n)
    }

    /// The flank point x whose generated point lies at radius `radius` (the involute branch).
    fn flank_x_at_radius(&self, radius: f64) -> f64 {
        let c = 1.0 / self.alpha.tan();
        let c2 = c * c;
        let disc = (self.r * self.r * c2 * c2 - (1.0 + c2) * (self.r * self.r * c2 - radius * radius)).max(0.0);
        (self.r * c2 + disc.sqrt()) / (1.0 + c2)
    }
}

/// A cubic B-spline (C1 Hermite spans) through `f` on `[a, b]`, refined until each
/// span is within `tolerance` of `f` at its sample parameters.
fn fit_planar(f: &dyn Fn(f64) -> [f64; 2], a: f64, b: f64, tolerance: f64) -> Result<NurbsCurve, KernelRefusal> {
    let derivative = |t: f64| {
        let h = 1e-6 * (b - a).abs().max(1e-12);
        let p = f(t + h);
        let q = f(t - h);
        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
    };
    let span_points = |t0: f64, t1: f64| {
        let (p0, p1) = (f(t0), f(t1));
        let (d0, d1) = (derivative(t0), derivative(t1));
        let k = (t1 - t0) / 3.0;
        [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
    };
    let bezier = |c: &[[f64; 2]; 4], u: f64| {
        let v = 1.0 - u;
        let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
        [
            w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0],
            w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1],
        ]
    };
    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| {
        let t0 = a + (b - a) * i as f64 / 4.0;
        let t1 = a + (b - a) * (i + 1) as f64 / 4.0;
        (t0, t1, 0)
    }).collect();
    let mut spans: Vec<(f64, f64, [[f64; 2]; 4])> = Vec::new();
    while let Some((t0, t1, depth)) = pending.pop() {
        let c = span_points(t0, t1);
        let worst = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
            .iter()
            .map(|&u| {
                let exact = f(t0 + (t1 - t0) * u);
                let fitted = bezier(&c, u);
                (exact[0] - fitted[0]).hypot(exact[1] - fitted[1])
            })
            .fold(0.0, f64::max);
        if worst > tolerance && depth < 16 {
            let mid = 0.5 * (t0 + t1);
            pending.push((mid, t1, depth + 1));
            pending.push((t0, mid, depth + 1));
        } else if worst > tolerance {
            return Err(refuse("gear_fit", format!("gear curve fit did not converge ({worst:.3e} > {tolerance:.3e})")));
        } else {
            spans.push((t0, t1, c));
        }
    }
    // Knots in [0, 1] (normalised). The Hermite spans join with C1 continuity,
    // so each interior knot is doubled and the shared span end, which lies on
    // the segment between its two neighbours, is implied rather than stored.
    let scale = 1.0 / (b - a);
    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
    let mut knots = vec![0.0; 4];
    let mut points = vec![to_point(spans[0].2[0])];
    for (index, (_, t1, c)) in spans.iter().enumerate() {
        points.push(to_point(c[1]));
        points.push(to_point(c[2]));
        if index + 1 < spans.len() {
            let k = (t1 - a) * scale;
            knots.extend([k, k]);
        } else {
            points.push(to_point(c[3]));
        }
    }
    knots.extend([1.0; 4]);
    NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))
}

fn mirrored(curve: &NurbsCurve) -> NurbsCurve {
    let mut copy = curve.clone();
    for point in &mut copy.control_points {
        point.y = -point.y;
    }
    NurbsCurve::new(copy.degree, copy.knots, copy.control_points).expect("a mirrored curve is a valid curve")
}

fn rotated(curve: &NurbsCurve, angle: f64) -> NurbsCurve {
    let (s, c) = angle.sin_cos();
    let points = curve
        .control_points
        .iter()
        .map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w })
        .collect();
    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a rotated curve is a valid curve")
}

fn arc(radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
    make_arc(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
        .map_err(|error| refuse("gear_arc", error))
}

fn check_spur(gear: &SpurGear, max_pressure_degrees: f64) -> Result<(), KernelRefusal> {
    let positive = |value: f64, what: &str| {
        if value.is_finite() && value > 0.0 {
            Ok(())
        } else {
            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
        }
    };
    positive(gear.module, "module")?;
    positive(gear.face_width, "face width")?;
    positive(gear.addendum, "addendum coefficient")?;
    positive(gear.dedendum, "dedendum coefficient")?;
    if gear.teeth < 3 {
        return Err(refuse("gear_input", format!("A gear needs at least 3 teeth (it has {}).", gear.teeth)));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
    }
    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    Ok(())
}

/// The section of an external spur gear, generated by its rack cutter.
pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
    check_spur(gear, 35.0)?;
    generated_section(gear)
}

/// [`spur_section`] for a helical gear's transverse section, whose pressure
/// angle (already checked in the normal section) may exceed 35°.
fn transverse_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
    check_spur(gear, 60.0)?;
    generated_section(gear)
}

fn generated_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    let z = gear.teeth as f64;
    let rack = RackCutter::new(gear);
    let alpha = rack.alpha;
    let r = rack.r;
    let r_b = r * alpha.cos();
    let r_a = r + (gear.addendum + gear.profile_shift) * m;
    let r_f = rack.r_f;
    let half_pitch = PI / z;
    let tolerance = GEAR_FIT_TOLERANCE * m;

    if r_f <= 1e-9 * m {
        return Err(refuse(
            "root_below_centre",
            format!("The root circle diameter is zero or negative (d = {:.4}): too few teeth for this dedendum.", 2.0 * r_f),
        ));
    }
    // The cutter's tip land must stay; with too large a tip radius the two fillets cross.
    let rho_max = ((PI * m / 2.0 - rack.y0) * alpha.cos() - (rack.x_ref - r_f) * alpha.sin()) / (1.0 - alpha.sin());
    if rack.rho > rho_max + 1e-9 * m {
        return Err(refuse(
            "root_fillet_too_large",
            format!(
                "The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.",
                gear.root_fillet,
                rho_max / m
            ),
        ));
    }
    let psi_end = PI / 2.0 - alpha;
    let x_flank_tangent = rack.centre[0] - rack.rho * alpha.sin();
    let x_interference = r * alpha.cos().powi(2);
    let min_shift = gear.dedendum - gear.root_fillet * (1.0 - alpha.sin()) - z / 2.0 * alpha.sin().powi(2);
    let undercut = x_flank_tangent < x_interference - 1e-12 * m;

    // The junction J of the left flank and its root fillet.
    let (x_join, psi_join) = if !undercut {
        (x_flank_tangent, psi_end)
    } else {
        // The fillet cuts the involute. Above the base circle the fillet lies
        // outside the involute at the flank tangency (psi_end) and inside it
        // just above the base circle, so the crossing is in [psi_base, psi_end],
        // where psi_base is the fillet's base-circle crossing (its radius rises
        // from the root, which is below the base circle here). Search that
        // interval at a resolution relative to its own width, so a gear just
        // past the undercut limit (a very short interval) is found too.
        let difference = |psi: f64| -> Option<f64> {
            let point = rack.fillet(psi);
            let radius = radius_of(point);
            if radius <= r_b {
                return None;
            }
            Some(polar_angle(point) - polar_angle(rack.flank(rack.flank_x_at_radius(radius))))
        };
        let (mut below, mut above) = (0.0, psi_end);
        for _ in 0..200 {
            let mid = 0.5 * (below + above);
            if radius_of(rack.fillet(mid)) <= r_b { below = mid } else { above = mid }
        }
        let psi_base = above;
        let steps = 4000;
        let mut found = None;
        let mut previous: Option<(f64, f64)> = None;
        for step in 0..=steps {
            let psi = psi_end - (psi_end - psi_base) * step as f64 / steps as f64;
            if let Some(value) = difference(psi) {
                if let Some((last_psi, last_value)) = previous {
                    if (value <= 0.0) != (last_value <= 0.0) {
                        found = Some((psi, last_psi));
                        break;
                    }
                }
                previous = Some((psi, value));
            }
        }
        // No crossing resolvable above the base circle: the fillet meets the
        // flank at the base circle itself (the undercut limit).
        let (mut lo, mut hi) = found.unwrap_or((psi_base, psi_base));
        let sign_lo = difference(lo).unwrap_or(-1.0) <= 0.0;
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            match difference(mid) {
                Some(value) if (value <= 0.0) == sign_lo => lo = mid,
                Some(_) => hi = mid,
                None => lo = mid,
            }
        }
        let psi = 0.5 * (lo + hi);
        (rack.flank_x_at_radius(radius_of(rack.fillet(psi))), psi)
    };
    let join = rack.fillet(psi_join);
    let form_radius = radius_of(join);
    if r_a <= form_radius + 1e-9 * m {
        return Err(refuse(
            "tip_below_form",
            format!(
                "The tip circle (d = {:.4}) does not reach above the form circle (d = {:.4}); raise the addendum or lower the dedendum.",
                2.0 * r_a,
                2.0 * form_radius
            ),
        ));
    }
    let x_tip = rack.flank_x_at_radius(r_a);
    let tip = rack.flank(x_tip);
    // Half the tooth thickness angle at a radius (the textbook involute form,
    // unwrapped: a polar angle read off a crossed flank wraps round and would
    // pass a tooth whose flanks crossed below the tip).
    let thickness = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() - gear.backlash;
    let involute = |angle: f64| angle.tan() - angle;
    let half_angle = |radius: f64| thickness / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
    let tip_angle = half_angle(r_a);
    let tip_offset = polar_angle(tip) - tip_angle;
    if tip_angle * r_a <= 1e-6 * m || tip_offset.abs() > 1e-9 {
        // Where the flanks meet: half_angle falls as the radius grows.
        let (mut lo, mut hi) = (form_radius.max(r_b), r_a);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if half_angle(mid) > 0.0 { lo = mid } else { hi = mid }
        }
        return Err(refuse(
            "pointed_tip",
            format!(
                "The teeth come to a point at d = {:.4}, inside the tip circle (d = {:.4}); reduce the addendum or the profile shift, or add teeth.",
                2.0 * lo,
                2.0 * r_a
            ),
        ));
    }
    if tip_angle >= half_pitch {
        return Err(refuse("teeth_overlap", "The tooth tips overlap their neighbours.".into()));
    }
    // Fillet samples must stay inside the half space (else neighbouring gaps cross).
    for step in 0..=64 {
        let point = rack.fillet(psi_join * step as f64 / 64.0);
        let angle = polar_angle(point);
        if angle <= 0.0 || angle > half_pitch + 1e-12 {
            return Err(refuse("teeth_overlap", "The tooth gaps cross: the root form of one gap cuts the next tooth.".into()));
        }
    }

    let flank_fit = fit_planar(&|x| rack.flank(x), x_join, x_tip, tolerance)?; // J -> tip
    let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; // root -> J
    let root_angle = rack.centre[1] / r;
    let land = 2.0 * half_pitch - 2.0 * root_angle;

    // Tooth 0, counter-clockwise: V (root -> J_R), R (J_R -> tip), K, L (tip -> J), W (J -> root), G.
    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![
        ("V", mirrored(&fillet_fit)),
        ("R", mirrored(&flank_fit)),
        ("K", arc(r_a, -tip_angle, tip_angle)?),
        ("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
        ("W", fillet_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
    ];
    if land > 1e-9 {
        tooth.push(("G", arc(r_f, root_angle, 2.0 * half_pitch - root_angle)?));
    }

    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = TAU * index as f64 / z;
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    // Share every junction exactly: each curve ends on the next one's first point.
    snap_junctions(&mut curves);

    let thickness_angle = |radius: f64| polar_angle(rack.flank(rack.flank_x_at_radius(radius)));
    let data = GearData {
        pitch_diameter: 2.0 * r,
        base_diameter: 2.0 * r_b,
        tip_diameter: 2.0 * r_a,
        root_diameter: 2.0 * r_f,
        form_diameter: 2.0 * form_radius,
        tooth_thickness: 2.0 * r * thickness_angle(r.max(r_b)),
        tip_thickness: 2.0 * r_a * tip_angle,
        undercut,
        min_shift_without_undercut: min_shift,
    };
    Ok(GearSection { curves, data })
}

/// A spur gear solid: the section extruded along +z by the face width. The face
/// names (suffixes, in the solid's face order) are the section curves' roles,
/// then `F` (the z = 0 face) and `B` (the z = width face).
pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = spur_section(gear)?;
    let solid = extrude_section(&section, gear.face_width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// Extrude a counter-clockwise gear section along +z.
pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
    extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
}

/// A straight-toothed rack: the basic rack profile of `teeth` teeth along +x
/// from x = 0, the pitch line on y = 0, teeth pointing +y, extruded along +z.
/// Each end stops in the middle of a tooth space.
#[derive(Clone, Debug)]
pub struct Rack {
    pub module: f64,
    pub teeth: usize,
    pub pressure_angle: f64,
    pub addendum: f64,
    pub dedendum: f64,
    /// Root fillet radius coefficient (× module).
    pub root_fillet: f64,
    /// Circumferential backlash taken off the tooth thickness on the pitch line.
    pub backlash: f64,
    pub face_width: f64,
    /// Distance from the pitch line down to the rack's back face.
    pub height: f64,
    /// Helix angle of a helical rack (0: straight teeth); the module, pressure
    /// angle and coefficients are then those of the normal section. Positive
    /// leans the teeth one way (right hand), negative the other.
    pub helix_angle: f64,
}

impl Default for Rack {
    fn default() -> Self {
        Self {
            module: 2.0,
            teeth: 10,
            pressure_angle: 20f64.to_radians(),
            addendum: 1.0,
            dedendum: 1.25,
            root_fillet: 0.38,
            backlash: 0.0,
            face_width: 10.0,
            height: 6.0,
            helix_angle: 0.0,
        }
    }
}

fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
    crate::make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)).map_err(|error| refuse("gear_line", error))
}

fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
    make_arc(Vec3::new(centre[0], centre[1], 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
        .map_err(|error| refuse("gear_arc", error))
}

/// The section of a straight rack (exact: lines and arcs), counter-clockwise.
/// Roles: `G<k>` the root land before tooth k (`G<teeth>` the last one),
/// `W<k>`/`V<k>` the root fillets left/right of tooth k, `L<k>`/`R<k>` its
/// left (low x) and right flanks, `K<k>` its tip, `BASE` the back face, `E0`
/// and `E1` the ends at x = 0 and x = length.
pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
    rack_section_checked(rack, 35.0)
}

fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
    let m = rack.module;
    let positive = |value: f64, what: &str| {
        if value.is_finite() && value > 0.0 {
            Ok(())
        } else {
            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
        }
    };
    positive(m, "module")?;
    positive(rack.face_width, "face width")?;
    positive(rack.addendum, "addendum coefficient")?;
    positive(rack.dedendum, "dedendum coefficient")?;
    if rack.teeth < 1 {
        return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
    }
    let degrees = rack.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
    }
    if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    let alpha = rack.pressure_angle;
    let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
    if rack.height <= hf + 1e-9 * m {
        return Err(refuse(
            "rack_too_thin",
            format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
        ));
    }
    let p = PI * m;
    let w = p / 4.0 - rack.backlash / 2.0; // half the tooth thickness on the pitch line
    let tip_half = w - ha * alpha.tan();
    if tip_half <= 1e-6 * m {
        return Err(refuse(
            "pointed_tip",
            "The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
        ));
    }
    let rho = rack.root_fillet * m;
    // Right-hand fillet of the tooth centred on x = 0: centre, flank tangent point, root tangent x.
    let y_p = -hf + rho - rho * alpha.sin();
    let flank_x = |y: f64| w - y * alpha.tan();
    let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
    let root_half = centre[0]; // the root tangent point's x (right of the tooth centre)
    if y_p >= ha - 1e-9 * m {
        return Err(refuse(
            "root_fillet_too_large",
            format!(
                "The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
                rack.root_fillet
            ),
        ));
    }
    if root_half > p / 2.0 + 1e-9 * m {
        let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
        return Err(refuse(
            "root_fillet_too_large",
            format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
        ));
    }
    let length = p * rack.teeth as f64;
    let mut curves: Vec<SectionCurve> = Vec::new();
    let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
    let base = -rack.height;
    push(line([0.0, base], [length, base])?, "BASE", 0);
    push(line([length, base], [length, -hf])?, "E1", 0);
    // Teeth from the right end leftwards (counter-clockwise along the top).
    let mut x_prev_root = length; // where the current root land starts (right end)
    for k in (0..rack.teeth).rev() {
        let c = (k as f64 + 0.5) * p;
        let right_root = [c + root_half, -hf];
        if x_prev_root - right_root[0] > 1e-9 * m {
            push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
        }
        // Right fillet: from the root tangent (angle 270°) back to the flank tangent (180° + alpha).
        let right_centre = [c + centre[0], centre[1]];
        let right_flank_low = [c + flank_x(y_p), y_p];
        if rho > 0.0 {
            push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
        }
        let right_tip = [c + tip_half, ha];
        let left_tip = [c - tip_half, ha];
        let left_flank_low = [c - flank_x(y_p), y_p];
        push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
        push(line(right_tip, left_tip)?, "K", k);
        let left_root = [c - root_half, -hf];
        push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
        if rho > 0.0 {
            let left_centre = [c - centre[0], centre[1]];
            push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
        }
        x_prev_root = left_root[0];
    }
    if x_prev_root > 1e-9 * m {
        push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
    }
    push(line([0.0, -hf], [0.0, base])?, "E0", 0);
    // Share every junction exactly.
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: f64::INFINITY,
        tooth_thickness: 2.0 * w,
        tip_thickness: 2.0 * tip_half,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A rack solid: the section extruded along +z by the face width; names as
/// [`rack_section`], then `F` (z = 0) and `B` (z = width).
pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let beta = rack.helix_angle;
    if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
        return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
    }
    // A helical rack's transverse section (the plane z = const) is the rack of
    // the transverse module and pressure angle; the teeth run along (tan beta, 0, 1).
    let degrees = rack.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    if beta == 0.0 {
        // Straight teeth: the rack exactly as given (no transverse conversion).
        let section = rack_section(rack)?;
        let solid = extrude_section(&section, rack.face_width)?;
        let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
        names.push("F".into());
        names.push("B".into());
        return Ok((solid, names, section.data));
    }
    // A helical rack's teeth are straight prisms along (tan beta, 0, 1). Its
    // normal section (across the teeth) is the basic rack; the transverse
    // section (z = const) is that section stretched along the rack by
    // 1 / cos beta, exactly: lines stay lines, the root rounds become ellipses
    // (still rational quadratic arcs).
    let c = beta.cos();
    let mut section = rack_section(rack)?;
    for piece in &mut section.curves {
        for point in &mut piece.curve.control_points {
            point.x /= c;
        }
    }
    // The recorded thicknesses are read along the rack (transverse), as the section is.
    section.data.tooth_thickness /= c;
    section.data.tip_thickness /= c;
    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
    let direction = Vec3::new(beta.tan(), 0.0, 1.0);
    let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
    let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

fn rack_suffix(piece: &SectionCurve) -> String {
    match piece.role {
        "BASE" | "E0" | "E1" => piece.role.to_string(),
        _ => piece.suffix(),
    }
}

/// Share every junction of a closed loop exactly: each curve ends on the next one's first point.
fn snap_junctions(curves: &mut [SectionCurve]) {
    let count = curves.len();
    for index in 0..count {
        let start = curves[(index + 1) % count].curve.control_points[0];
        let curve = &mut curves[index].curve;
        let last = curve.control_points.len() - 1;
        let w = curve.control_points[last].w;
        curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: start.z / start.w * w, w };
    }
}

/// An internal (ring) gear: involute tooth spaces cut into the inside of a
/// ring. Lengths in model units, angles in radians, coefficients × module.
#[derive(Clone, Debug)]
pub struct RingGear {
    pub module: f64,
    pub teeth: usize,
    pub pressure_angle: f64,
    /// Profile shift: the cutter moved outward by x · module (tip and root
    /// circles grow by x · module, the spaces widen by 2 x m tan alpha).
    pub profile_shift: f64,
    pub addendum: f64,
    pub dedendum: f64,
    /// Radius of the root fillet (× module): an exact arc tangent to the
    /// flank and the root circle.
    pub root_fillet: f64,
    /// Circumferential backlash added to each tooth space on the reference circle.
    pub backlash: f64,
    pub face_width: f64,
    /// Radial wall beyond the root circle.
    pub rim: f64,
}

impl Default for RingGear {
    fn default() -> Self {
        Self {
            module: 2.0,
            teeth: 60,
            pressure_angle: 20f64.to_radians(),
            profile_shift: 0.0,
            addendum: 1.0,
            dedendum: 1.25,
            root_fillet: 0.38,
            backlash: 0.0,
            face_width: 10.0,
            rim: 6.0,
        }
    }
}

/// The inner (toothed) loop of a ring gear, counter-clockwise about +z, and its data.
/// Roles per tooth space k: `R<k>` flank on its clockwise side, `V<k>` its
/// fillet, `G<k>` the root land, `W<k>`, `L<k>`, then `K<k>` the tip land of
/// the ring tooth after the space.
pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
    ring_section_checked(gear, 35.0)
}

fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    let positive = |value: f64, what: &str| {
        if value.is_finite() && value > 0.0 {
            Ok(())
        } else {
            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
        }
    };
    positive(m, "module")?;
    positive(gear.face_width, "face width")?;
    positive(gear.addendum, "addendum coefficient")?;
    positive(gear.dedendum, "dedendum coefficient")?;
    positive(gear.rim, "rim thickness")?;
    if gear.teeth < 6 {
        return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
    }
    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    let z = gear.teeth as f64;
    let alpha = gear.pressure_angle;
    let r = m * z / 2.0;
    let r_b = r * alpha.cos();
    let r_a = r - (gear.addendum - gear.profile_shift) * m; // inner (tip) circle
    let r_f = r + (gear.dedendum + gear.profile_shift) * m; // outer (root) circle
    let rho = gear.root_fillet * m;
    let half_pitch = PI / z;
    let tolerance = GEAR_FIT_TOLERANCE * m;
    if r_a <= r_b + 1e-9 * m {
        return Err(refuse(
            "tip_inside_base",
            format!(
                "An internal gear's tip circle (d = {:.4}) must lie outside its base circle (d = {:.4}); raise the tooth count, lower the pressure angle or the addendum.",
                2.0 * r_a,
                2.0 * r_b
            ),
        ));
    }
    // Half the SPACE angle at a radius: the space is shaped as an external tooth.
    let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
    let involute = |angle: f64| angle.tan() - angle;
    let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
    let flank = |radius: f64| {
        let angle = half_space(radius);
        [radius * angle.cos(), radius * angle.sin()]
    };
    if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
        return Err(refuse(
            "pointed_tip",
            "The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
        ));
    }
    // The spaces narrow outward: one that closes before the root circle has
    // crossed flanks (read unwrapped, from the closed form).
    if half_space(r_f) <= 1e-6 * m / r_f {
        let (mut lo, mut hi) = (r_a, r_f);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
        }
        return Err(refuse(
            "teeth_overlap",
            format!(
                "The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
                2.0 * lo,
                2.0 * r_f
            ),
        ));
    }
    // The fillet: a circle of radius rho tangent to the flank (left side of
    // space 0, at T) and inside the root circle. Its centre is T moved by rho
    // along the flank's normal into the space; solve |centre| = r_f - rho for T.
    let normal_into_space = |radius: f64| {
        let h = 1e-6 * m;
        let (a, b) = (flank(radius - h), flank(radius + h));
        let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
        let length = tx.hypot(ty);
        // The space lies at smaller angles than its left flank: the normal turned clockwise from the outward tangent.
        [ty / length, -tx / length]
    };
    let centre_at = |radius: f64| {
        let point = flank(radius);
        let n = normal_into_space(radius);
        [point[0] + rho * n[0], point[1] + rho * n[1]]
    };
    let (join_radius, centre) = if rho == 0.0 {
        (r_f, flank(r_f))
    } else {
        let target = r_f - rho;
        let (mut lo, mut hi) = (r_a, r_f);
        if radius_of(centre_at(lo)) > target {
            return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
        }
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
        }
        let radius = 0.5 * (lo + hi);
        (radius, centre_at(radius))
    };
    let root_angle = polar_angle(centre);
    if rho > 0.0 && root_angle <= 1e-9 {
        return Err(refuse(
            "root_fillet_too_large",
            "The root fillet is larger than fits the tooth space; lower it.".into(),
        ));
    }
    let tip_angle = half_space(r_a);
    // Left flank of space 0 from its root end (join) in to the tip circle.
    let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; // tip -> join
    let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
    // Clockwise side (negative angles), outward: mirrored left flank (tip -> join), fillet, land, fillet, flank.
    space.push(("R", mirrored(&flank_fit)));
    if rho > 0.0 {
        // The left fillet runs counter-clockwise about its centre from the root
        // tangent point (straight out from the centre) round to the flank join.
        let join = flank(join_radius);
        let from = root_angle;
        let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
        while to <= from {
            to += TAU;
        }
        let left = centred_arc(centre, rho, from, to)?; // root -> join
        space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
        space.push(("G", arc(r_f, -root_angle, root_angle)?));
        space.push(("W", left));
    } else {
        space.push(("G", arc(r_f, -root_angle, root_angle)?));
    }
    space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
    space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
    let mut curves = Vec::with_capacity(space.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = TAU * index as f64 / z;
        for (role, curve) in &space {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: 2.0 * r,
        base_diameter: 2.0 * r_b,
        tip_diameter: 2.0 * r_a,
        root_diameter: 2.0 * r_f,
        form_diameter: 2.0 * join_radius,
        tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
        tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
        undercut: false,
        min_shift_without_undercut: 0.0,
    };
    Ok(GearSection { curves, data })
}

/// A ring gear solid: a cylinder of radius root + rim with the toothed loop
/// cut through it. Its faces carry their role names (`R3`, `K0`, …, `OD` the
/// outside, `F` at z = 0, `B` at z = width) in `face.name`.
pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
    let section = ring_section(gear)?;
    let outer = section.data.root_diameter / 2.0 + gear.rim;
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), axis, outer, gear.face_width)
        .map_err(|error| refuse("gear_blank", error))?;
    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
        face.name = Some(name.into());
    }
    // The tool runs past both faces so no face of it lies on the blank's.
    let reach = gear.face_width * 0.1 + gear.module;
    let shifted: Vec<SectionCurve> = section
        .curves
        .iter()
        .map(|piece| SectionCurve { curve: translated(&piece.curve, -reach), role: piece.role, tooth: piece.tooth })
        .collect();
    let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, gear.face_width + 2.0 * reach)?;
    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
        face.name = Some(piece.suffix());
    }
    let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
    Ok((ring, section.data))
}

/// A helical (or double helical) ring gear: `gear` in the normal section,
/// its transverse section screwed through the blank. Names as [`ring_solid`].
pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
    let beta = helix_angle;
    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
    }
    let normal = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
    }
    let c = beta.cos();
    let transverse = RingGear {
        module: gear.module / c,
        pressure_angle: (gear.pressure_angle.tan() / c).atan(),
        profile_shift: gear.profile_shift * c,
        addendum: gear.addendum * c,
        dedendum: gear.dedendum * c,
        root_fillet: gear.root_fillet * c,
        ..gear.clone()
    };
    let section = ring_section_checked(&transverse, 60.0)?;
    let r = transverse.module * transverse.teeth as f64 / 2.0;
    let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
    let rate = sign * beta.tan() / r; // turn per unit height
    let outer = section.data.root_diameter / 2.0 + gear.rim;
    let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), outer, gear.face_width)
        .map_err(|error| refuse("gear_blank", error))?;
    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
        face.name = Some(name.into());
    }
    // The tool runs past both faces, turned so that it reads the nominal section at z = 0.
    let reach = gear.face_width * 0.1 + transverse.module;
    let height = gear.face_width + 2.0 * reach;
    let start: Vec<SectionCurve> = section
        .curves
        .iter()
        .map(|piece| SectionCurve { curve: rotated(&piece.curve, -rate * reach), role: piece.role, tooth: piece.tooth })
        .collect();
    let twist = if herringbone { Twist::Herringbone { turn: rate * height } } else { Twist::Helical { turn: rate * height } };
    let tool = twisted_prism(&GearSection { curves: start.clone(), data: section.data.clone() }, height, twist, GEAR_FIT_TOLERANCE * transverse.module)?;
    let shift = crate::AffineTransform::new([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -reach, 0.0, 0.0, 0.0, 1.0])
        .map_err(|e| refuse("gear_transform", e))?;
    let mut tool = crate::transform_brep(&tool, shift, false).map_err(|e| refuse("gear_transform", e))?;
    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&start) {
        face.name = Some(piece.suffix());
    }
    let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
    Ok((ring, section.data))
}

fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
    let points = curve.control_points.iter().map(|p| Vec4 { x: p.x, y: p.y, z: p.z + p.w * dz, w: p.w }).collect();
    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
}

/// Which ISO 606 tooth form a sprocket is cut to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SprocketForm {
    /// Smallest seating radius, largest flank radius, largest seating angle.
    Minimum,
    /// Largest seating radius, smallest flank radius, smallest seating angle.
    Maximum,
    /// The mean of the two.
    Mean,
}

/// A roller-chain sprocket (ISO 606 tooth form; ANSI chains are its A series).
#[derive(Clone, Debug)]
pub struct Sprocket {
    pub pitch: f64,
    pub roller_diameter: f64,
    pub teeth: usize,
    pub form: SprocketForm,
    /// Tooth width across the sprocket (the extrusion).
    pub width: f64,
}

/// The section of a roller-chain sprocket, counter-clockwise; every curve is a
/// circular arc. Tooth k is centred on angle 2 pi k / z (tooth 0 on +x); gap k
/// follows it. Roles: `A<k>` the flank into gap k, `S<k>` its roller seating,
/// `C<k>` the flank out of it, `K<k>` the tip land of the tooth after gap k
/// (absent when the flanks meet below the tip circle).
pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
    let p = sprocket.pitch;
    let d1 = sprocket.roller_diameter;
    if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
        return Err(refuse(
            "gear_input",
            format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
        ));
    }
    if sprocket.teeth < 6 || sprocket.teeth > 300 {
        return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
    }
    let z = sprocket.teeth as f64;
    let tau = TAU / z;
    let d = p / (PI / z).sin();
    // ISO 606 tooth form limits.
    let ri_min = 0.505 * d1;
    let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
    let re_min = 0.008 * d1 * (z * z + 180.0);
    let re_max = 0.12 * d1 * (z + 2.0);
    let a_min = (120.0 - 90.0 / z).to_radians();
    let a_max = (140.0 - 90.0 / z).to_radians();
    let da_min = d + p * (1.0 - 1.6 / z) - d1;
    let da_max = d + 1.25 * p - d1;
    let (ri, re, alpha, da) = match sprocket.form {
        SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
        SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
        SprocketForm::Mean => (0.5 * (ri_min + ri_max), 0.5 * (re_min + re_max), 0.5 * (a_min + a_max), 0.5 * (da_min + da_max)),
    };
    let ra = da / 2.0;
    // Gap 0 centred on angle tau / 2 is built centred on +x, then turned.
    let c = [d / 2.0, 0.0];
    let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; // roller centre -> upper seating end
    let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
    let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; // the upper flank's centre
    // The upper flank: circle (f, re) from t_up outward. The tooth after the gap
    // is centred on the line at angle tau / 2 (built frame).
    let half = tau / 2.0;
    let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
    // Walk the flank circle from t_up in the sense that moves away from the axis.
    let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
    let step = 1e-4;
    let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
    // Find where the flank reaches the tip circle or the tooth centre line, whichever first.
    let reach = |angle: f64| {
        let q = on_flank(angle);
        (radius_of(q) >= ra, polar_angle(q) >= half)
    };
    let (mut lo, mut hi) = (0.0, PI / 2.0);
    if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
        return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
    }
    for _ in 0..200 {
        let mid = 0.5 * (lo + hi);
        let (tip, centre) = reach(a_t + sense * mid);
        if tip || centre { hi = mid } else { lo = mid }
    }
    let a_end = a_t + sense * hi;
    let end = on_flank(a_end);
    let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
    let (a_end, end) = if pointed {
        // Land exactly on the tooth centre line.
        let (mut lo, mut hi) = (0.0, hi);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
        }
        let a = a_t + sense * hi;
        (a, on_flank(a))
    } else {
        (a_end, end)
    };
    let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
        if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
    };
    let upper = flank_arc(a_t, a_end)?; // t_up -> end
    let seat = centred_arc(c, ri, PI - alpha / 2.0, PI + alpha / 2.0)?.reversed().map_err(|e| refuse("gear_arc", e))?; // t_down -> t_up
    let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; // end' -> t_down
    let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
    let tip_angle = polar_angle(end);
    if !pointed {
        gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
    }
    let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
    for index in 0..sprocket.teeth {
        let angle = tau * index as f64 + half;
        for (role, curve) in &gap {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: d,
        tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
        root_diameter: d - 2.0 * ri,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A sprocket solid: the section extruded along +z by the width; names as
/// [`sprocket_section`], then `F` and `B`.
pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = sprocket_section(sprocket)?;
    let solid = extrude_section(&section, sprocket.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// The turn of a twisted prism's section along its height: `theta(t)` at
/// `t = z / width` in [0, 1], with an optional crease at `t = 1/2` (a
/// herringbone's apex).
#[derive(Clone, Copy, Debug)]
pub enum Twist {
    /// theta = turn · t (a helical gear: a screw motion).
    Helical { turn: f64 },
    /// theta = turn · (1/2 − |t − 1/2|): out by `turn / 2` to the middle and back.
    Herringbone { turn: f64 },
}

impl Twist {
    fn angle(&self, t: f64) -> f64 {
        match *self {
            Twist::Helical { turn } => turn * t,
            Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
        }
    }

    fn rate(&self, t: f64, after_crease: bool) -> f64 {
        match *self {
            Twist::Helical { turn } => turn,
            Twist::Herringbone { turn } => {
                if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
            }
        }
    }

    fn total_turn(&self) -> f64 {
        match *self {
            Twist::Helical { turn } => turn.abs(),
            Twist::Herringbone { turn } => turn.abs(),
        }
    }
}

/// The axial basis of a twisted prism: cubic Hermite spans in t carrying
/// (cos theta, sin theta, t), with doubled interior knots (C1) and a tripled
/// knot at a crease. Returns (knots, per control point (cos, sin, t)).
fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
    let crease = matches!(twist, Twist::Herringbone { .. });
    // Hermite cubic error of cos/sin over a span of turn d: about reach · d^4 / 384.
    let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
    let needed = twist.total_turn() / per;
    if !(needed <= 4096.0) {
        return Err(refuse(
            "twist_too_long",
            format!(
                "The teeth turn {:.3} times round the axis over the face width; shorten the face width or lower the helix angle (at most {:.1} turns at this size).",
                twist.total_turn() / TAU,
                4096.0 * per / TAU
            ),
        ));
    }
    let mut spans = (needed.ceil() as usize).max(1);
    if crease && spans % 2 == 1 {
        spans += 1;
    }
    let value = |t: f64| {
        let a = twist.angle(t);
        [a.cos(), a.sin(), t]
    };
    let slope = |t: f64, after: bool| {
        let a = twist.angle(t);
        let r = twist.rate(t, after);
        [-a.sin() * r, a.cos() * r, 1.0]
    };
    let mut knots = vec![0.0; 4];
    let mut points = vec![value(0.0)];
    for index in 0..spans {
        let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
        let h = (t1 - t0) / 3.0;
        let (p0, p1) = (value(t0), value(t1));
        let (d0, d1) = (slope(t0, true), slope(t1, false));
        points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
        points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
        let last = index + 1 == spans;
        let at_crease = crease && 2 * (index + 1) == spans;
        if last {
            points.push(p1);
        } else if at_crease {
            points.push(p1);
            knots.extend([t1, t1, t1]);
        } else {
            knots.extend([t1, t1]);
        }
    }
    knots.extend([1.0; 4]);
    Ok((knots, points))
}

/// Carry a section curve along the twist: the curve turned by theta and lifted


/// A counter-clockwise section (z = 0) carried up to z = width while turning
/// by `twist`: side faces in section order, then the face at z = 0, then the
/// face at z = width (exactly the section turned by the end angle).
pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
    if !(width > 0.0) {
        return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
    }
    let reach = section
        .curves
        .iter()
        .flat_map(|c| c.curve.control_points.iter())
        .map(|p| (p.x / p.w).hypot(p.y / p.w))
        .fold(0.0, f64::max);
    let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
    let rows = |p: Vec4| -> Vec<Vec4> {
        basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect()
    };
    prism_by_rows(section, 3, &knots_v, &rows)
}

/// A planar counter-clockwise section (in a plane z = const) carried along
/// v in [0, 1] by `rows`, which maps each homogeneous control point to the
/// control points of its v-curve (degree `degree_v` on `knots_v`); the last
/// row must again be planar at a constant z (the top cap). Side faces in
/// section order, then the face at v = 0, then the face at v = 1.
pub fn prism_by_rows(section: &GearSection, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
    let count = curves.len();
    let top_of = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
        let points = curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect();
        NurbsCurve::new(curve.degree, curve.knots.clone(), points).map_err(|e| refuse("gear_curve", e))
    };
    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
    let unit = |p: Vec4| Vec4 { x: p.x / p.w, y: p.y / p.w, z: p.z / p.w, w: 1.0 };
    let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
    let mut vertices = Vec::with_capacity(2 * count);
    for (index, start) in starts.iter().enumerate() {
        vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
    }
    for (index, start) in starts.iter().enumerate() {
        vertices.push(VertexRecord { id: (count + index) as u64 + 1, point: point_of(*rows(unit(*start)).last().expect("a row")) });
    }
    let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
    let mut edges = Vec::with_capacity(3 * count);
    let mut tops = Vec::with_capacity(count);
    for (index, curve) in curves.iter().enumerate() {
        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let next = (index + 1) % count;
        let top = top_of(curve)?;
        let axial = NurbsCurve::new(degree_v, knots_v.to_vec(), rows(unit(starts[index]))).map_err(|e| refuse("gear_edge", e))?;
        edges.push(EdgeRecord { id: edge_id(0, index), curve: curve.clone(), t0: start, t1: end, start_vertex_id: index as u64 + 1, end_vertex_id: next as u64 + 1, degenerate: false, name: None });
        edges.push(EdgeRecord { id: edge_id(1, index), curve: top.clone(), t0: start, t1: end, start_vertex_id: (count + index) as u64 + 1, end_vertex_id: (count + next) as u64 + 1, degenerate: false, name: None });
        edges.push(EdgeRecord { id: edge_id(2, index), curve: axial, t0: 0.0, t1: 1.0, start_vertex_id: index as u64 + 1, end_vertex_id: (count + index) as u64 + 1, degenerate: false, name: None });
        tops.push(top);
    }
    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
    let mut next_id = 10 + 3 * count as u64 + 1000;
    let mut faces = Vec::with_capacity(count + 2);
    for (index, curve) in curves.iter().enumerate() {
        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let next = (index + 1) % count;
        let coedges = vec![
            CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
            CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
            CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
            CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
        ];
        next_id += 4;
        let surface_rows: Vec<Vec<Vec4>> = curve.control_points.iter().map(|p| rows(*p)).collect();
        let surface = NurbsSurface::new(curve.degree, degree_v, curve.knots.clone(), knots_v.to_vec(), surface_rows).map_err(|e| refuse("gear_surface", e))?;
        faces.push(FaceRecord { id: next_id + 1, surface, same_sense: true, loops: vec![LoopRecord { id: next_id, coedges }], name: None });
        next_id += 2;
    }
    let reach = curves.iter().chain(tops.iter()).flat_map(|c| c.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
    let pad = reach * 1.1 + 1.0;
    let x_axis = Vec3::new(1.0, 0.0, 0.0);
    let y_axis = Vec3::new(0.0, 1.0, 0.0);
    let z0 = vertices[0].point.z;
    let z1 = vertices[count].point.z;
    let bottom_origin = Vec3::new(-pad, -pad, z0);
    let mut bottom = Vec::with_capacity(count);
    for index in (0..count).rev() {
        bottom.push(CoedgeRecord {
            id: next_id,
            edge_id: edge_id(0, index),
            forward: false,
            pcurve: curve_to_plane_parameters(&curves[index], bottom_origin, x_axis, y_axis).and_then(|c| c.reversed()).map_err(|e| refuse("gear_pcurve", e))?,
        });
        next_id += 1;
    }
    faces.push(FaceRecord {
        id: next_id + 1,
        surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
        same_sense: false,
        loops: vec![LoopRecord { id: next_id, coedges: bottom }],
        name: None,
    });
    next_id += 2;
    let top_origin = Vec3::new(-pad, -pad, z1);
    let mut top = Vec::with_capacity(count);
    for (index, curve) in tops.iter().enumerate() {
        top.push(CoedgeRecord {
            id: next_id,
            edge_id: edge_id(1, index),
            forward: true,
            pcurve: curve_to_plane_parameters(curve, top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
        });
        next_id += 1;
    }
    faces.push(FaceRecord {
        id: next_id + 1,
        surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
        same_sense: true,
        loops: vec![LoopRecord { id: next_id, coedges: top }],
        name: None,
    });
    next_id += 2;
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id: next_id + 1,
        vertices,
        edges,
        shells: vec![ShellRecord { id: next_id, faces }],
        genus: 0,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if issues.is_empty() {
        Ok(solid)
    } else {
        Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("gear prism is not valid: {issues:?}")))
    }
}

/// Hand of a helical gear's teeth.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hand {
    Right,
    Left,
}

/// A helical (or, with `herringbone`, double helical) external gear given by
/// its normal-section values; `spur` carries them (module = normal module,
/// pressure angle = normal pressure angle, coefficients × normal module).
#[derive(Clone, Debug)]
pub struct HelicalGear {
    pub spur: SpurGear,
    pub helix_angle: f64,
    pub hand: Hand,
    pub herringbone: bool,
}

/// The transverse spur gear a helical gear's every section is (turned).
pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
    let beta = gear.helix_angle;
    // The pressure angle limits apply to the normal section (the cutter's).
    let normal = gear.spur.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
    }
    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
    }
    let n = &gear.spur;
    let c = beta.cos();
    Ok(SpurGear {
        module: n.module / c,
        teeth: n.teeth,
        pressure_angle: (n.pressure_angle.tan() / c).atan(),
        profile_shift: n.profile_shift * c,
        addendum: n.addendum * c,
        dedendum: n.dedendum * c,
        // The cutter's tip radius in the transverse section is taken as the
        // normal one (the true section of the round is a slightly longer ellipse).
        root_fillet: n.root_fillet * c,
        backlash: n.backlash,
        face_width: n.face_width,
    })
}

/// A helical or herringbone gear solid; names as [`spur_solid`].
pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let transverse = helical_transverse(gear)?;
    let section = transverse_section(&transverse)?;
    let r = transverse.module * transverse.teeth as f64 / 2.0;
    let width = transverse.face_width;
    let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
    let twist = if gear.herringbone {
        // Each half advances by its own half width.
        Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
    } else {
        Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
    };
    let solid = twisted_prism(&section, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A straight-sided spline (ISO 14 form: `teeth` keys of width `key_width`
/// between the minor diameter `minor` and the major diameter `major`).
#[derive(Clone, Debug)]
pub struct StraightSpline {
    pub teeth: usize,
    pub minor: f64,
    pub major: f64,
    pub key_width: f64,
    pub length: f64,
}

fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
    let StraightSpline { teeth, minor, major, key_width, length } = *spline;
    if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
        return Err(refuse(
            "gear_input",
            format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
        ));
    }
    if teeth < 2 || teeth > 100 {
        return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
    }
    // The keys must not meet on the minor circle.
    let half_root = (key_width / minor).asin();
    if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
        return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
    }
    Ok(())
}

/// The section of a straight-sided spline shaft, counter-clockwise; exact
/// lines and arcs. Key k is centred on angle 2 pi k / N. Roles: `R<k>`/`L<k>`
/// its flanks, `K<k>` its top on the major circle, `G<k>` the root land after it.
pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
    check_straight_spline(spline)?;
    let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
    let n = spline.teeth as f64;
    let foot = [(rr * rr - h * h).sqrt(), h];
    let top = [(ra * ra - h * h).sqrt(), h];
    let top_angle = (h / ra).asin();
    let foot_angle = (h / rr).asin();
    let key: Vec<(&'static str, NurbsCurve)> = vec![
        ("R", line([foot[0], -h], [top[0], -h])?),
        ("K", arc(ra, -top_angle, top_angle)?),
        ("L", line(top, foot)?),
        ("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
    ];
    let mut curves = Vec::with_capacity(4 * spline.teeth);
    for index in 0..spline.teeth {
        let angle = TAU * index as f64 / n;
        for (role, curve) in &key {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
}

/// A spline shaft: the section extruded along +z by the length; names as the
/// section's roles, then `F` and `B`.
pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = straight_spline_section(spline)?;
    let solid = extrude_section(&section, spline.length)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// Cut a counter-clockwise section through a cylinder of `outside` diameter
/// and `length`: a hub. The section's faces keep their role names, the
/// cylinder's are `OD`, `F` and `B` (all in `face.name`).
pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
    // The section's true outer radius, read off the curves (a rational arc's
    // middle control point lies outside the arc).
    let mut reach: f64 = 0.0;
    for piece in &section.curves {
        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
        for i in 0..=32 {
            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
            reach = reach.max(p.x.hypot(p.y));
        }
    }
    if !(outside / 2.0 > reach + 1e-9) {
        return Err(refuse(
            "hub_too_small",
            format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
        ));
    }
    let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), outside / 2.0, length)
        .map_err(|error| refuse("gear_blank", error))?;
    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
        face.name = Some(name.into());
    }
    let extra = 0.1 * length + 0.1 * reach;
    let shifted: Vec<SectionCurve> = section
        .curves
        .iter()
        .map(|piece| SectionCurve { curve: translated(&piece.curve, -extra), role: piece.role, tooth: piece.tooth })
        .collect();
    let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, length + 2.0 * extra)?;
    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
        face.name = Some(piece.suffix());
    }
    crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)
}

/// A spline hub: the shaft's section (nominal size) cut through a cylinder.
pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
    let section = straight_spline_section(spline)?;
    let hub = hub_from_section(&section, outside, spline.length)?;
    Ok((hub, section.data))
}

/// A timing-belt pulley with straight-sided grooves (ISO 5294 Table 2 form;
/// the metric trapezoidal profiles the same way): every curve a line or an arc.
#[derive(Clone, Debug)]
pub struct TimingPulley {
    /// Belt pitch.
    pub pitch: f64,
    pub teeth: usize,
    /// Pitch line differential 2a: outside diameter = pitch z / pi - 2a.
    pub pld: f64,
    /// Groove bottom width bw.
    pub bottom_width: f64,
    /// Groove depth hg (from the outside diameter).
    pub depth: f64,
    /// Groove side angle to the radial direction, each side (half of 2 beta).
    pub side_angle: f64,
    /// Bottom (root) corner radius rb.
    pub bottom_radius: f64,
    /// Top (tip) corner radius rt.
    pub top_radius: f64,
    pub width: f64,
}

/// An arc about `centre` from `from` to `to` (both on it), counter-clockwise
/// when `ccw`, else clockwise.
fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
    let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
    let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
    let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
    if ccw {
        let mut end = a1;
        while end <= a0 {
            end += TAU;
        }
        centred_arc(centre, radius, a0, end)
    } else {
        let mut start = a1;
        while start <= a0 - TAU {
            start += TAU;
        }
        while start >= a0 {
            start -= TAU;
        }
        centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
    }
}

/// The pulley section, counter-clockwise. Groove k is centred on angle
/// 2 pi (k + 1/2) / z (tooth k on angle 2 pi k / z). Roles per groove k, in
/// order: `Q<k>` the top corner arc into it, `A<k>` its first side, `U<k>`
/// the bottom corner arc, `S<k>` the bottom, `D<k>` the other bottom corner
/// arc, `C<k>` the other side, `P<k>` the top corner arc out of it, `K<k>`
/// the land of the next tooth on the outside diameter.
pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
    let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
    if !(pitch > 0.0 && pld >= 0.0 && bottom_width > 0.0 && depth > 0.0 && width > 0.0 && bottom_radius >= 0.0 && top_radius >= 0.0) {
        return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
    }
    if !(0.0..60f64.to_radians()).contains(&side_angle) {
        return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
    }
    if teeth < 6 || teeth > 400 {
        return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
    }
    let z = teeth as f64;
    let ro = pitch * z / PI / 2.0 - pld / 2.0;
    let x_bottom = ro - depth;
    if !(x_bottom > 0.0) {
        return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
    }
    let tau = TAU / z;
    let (s, c) = side_angle.sin_cos();
    let side = [c, s]; // outward along the upper side
    let normal = [-s, c]; // from the upper side into the material
    let corner = [x_bottom, bottom_width / 2.0];
    // The upper side meets the outside circle at |corner + t side| = ro.
    let b = corner[0] * side[0] + corner[1] * side[1];
    let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
    let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
    // Bottom corner fillet: between the bottom (direction +y) and the side; the
    // path turns right there (clockwise arc). Interior turn angle phi = 90° - beta.
    let turn = PI / 2.0 - side_angle;
    let reach_b = bottom_radius * (turn / 2.0).tan();
    let t1 = [corner[0], corner[1] - reach_b];
    let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
    let centre_b = [t1[0] + bottom_radius, t1[1]];
    // Top corner fillet: tangent to the side (offset into the material) and
    // inside the outside circle (centre at ro - rt).
    let rt = top_radius;
    let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
    let bb = base[0] * side[0] + base[1] * side[1];
    let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
    if disc < 0.0 {
        return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
    }
    let t_c = -bb + disc.sqrt();
    let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
    let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
    let scale = ro / (centre_t[0].hypot(centre_t[1]));
    let t4 = [centre_t[0] * scale, centre_t[1] * scale];
    let land_start = polar_angle(t4);
    if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
        return Err(refuse(
            "groove_too_wide",
            format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
        ));
    }
    let _ = top;
    // The upper half of groove 0, outward: bottom half line, D, C, P.
    let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
    if bottom_radius > 0.0 {
        upper.push(("D", arc_through(centre_b, t1, t2, false)?));
    }
    upper.push(("C", line(t2, t3)?));
    if rt > 0.0 {
        upper.push(("P", arc_through(centre_t, t3, t4, true)?));
    }
    let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
    let lower_roles = |role: &'static str| match role {
        "D" => "U",
        "C" => "A",
        _ => "Q",
    };
    for (role, curve) in upper.iter().rev() {
        groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
    }
    groove.push(("S", line([t1[0], -t1[1]], t1)?));
    groove.extend(upper.into_iter());
    groove.push(("K", arc(ro, land_start, tau - land_start)?));
    let mut curves = Vec::with_capacity(groove.len() * teeth);
    for index in 0..teeth {
        let angle = tau * index as f64 + tau / 2.0;
        for (role, curve) in &groove {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
    Ok(GearSection { curves, data })
}

/// A pulley solid: the section extruded along +z by the width; names as the
/// section's roles, then `F` and `B`.
pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = timing_pulley_section(pulley)?;
    let solid = extrude_section(&section, pulley.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A ratchet wheel: `teeth` teeth on `outside` diameter, `depth` deep. A saw
/// tooth has a locking face (leaning `lean` back from radial, so a pawl is drawn
/// in under load) and a straight back; a symmetric tooth leans both faces
/// equally (for a reversible pawl). Teeth lock against counter-clockwise turning
/// when `clockwise_locks` is false.
#[derive(Clone, Debug)]
pub struct Ratchet {
    pub teeth: usize,
    pub outside: f64,
    pub depth: f64,
    pub lean: f64,
    pub symmetric: bool,
    pub clockwise_locks: bool,
    pub width: f64,
}

/// The ratchet section, counter-clockwise; straight lines only. Roles per
/// tooth k (tip k on angle 2 pi k / z): `LK<k>` the locking face below its
/// tip, `BK<k>` the back running up to it.
pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
    let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
    if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
        return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
    }
    if teeth < 3 || teeth > 360 {
        return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
    }
    if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
        return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
    }
    let z = teeth as f64;
    let tau = TAU / z;
    let ra = outside / 2.0;
    let rf = ra - depth;
    // Tooth 0's tip on +x. The locking face runs from the tip down to the root
    // at a polar angle `foot` ahead of the tip (counter-clockwise), leaning back.
    // A radial face has foot = 0; leaning back by `lean` moves the root point
    // forward along the face's direction: solve |tip + t d| = rf.
    let tip = [ra, 0.0];
    let face_angle = PI + lean; // pointing inward, tilted to +y by `lean`
    let d = [face_angle.cos(), face_angle.sin()];
    let b = tip[0] * d[0] + tip[1] * d[1];
    let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
    let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
    let foot = polar_angle(root);
    let (lock, back) = if symmetric {
        // Both faces meet at the root halfway between tips, each leaning equally.
        let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
        let lock = line(tip, mid)?;
        let next = [ra * tau.cos(), ra * tau.sin()];
        (lock, line(mid, next)?)
    } else {
        if foot >= tau - 1e-9 {
            return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
        }
        let next = [ra * tau.cos(), ra * tau.sin()];
        (line(tip, root)?, line(root, next)?)
    };
    // Counter-clockwise traversal from tip k: locking face down, back up to tip k + 1.
    let mut curves = Vec::with_capacity(2 * teeth);
    for index in 0..teeth {
        let angle = tau * index as f64;
        curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
        curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
    }
    if clockwise_locks {
        // The mirror image locks the other way; mirror, then restore the
        // counter-clockwise order.
        let mut mirrored_curves: Vec<SectionCurve> = curves
            .iter()
            .map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
            .collect();
        mirrored_curves.reverse();
        curves = mirrored_curves;
    }
    snap_junctions(&mut curves);
    Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
}

/// A ratchet solid: the section extruded along +z; names as the section's roles, then `F` and `B`.
pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = ratchet_section(ratchet)?;
    let solid = extrude_section(&section, ratchet.width)?;
    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// An external Geneva wheel of `slots` slots for a driver at `centre_distance`
/// whose pin of `pin_diameter` runs on the crank radius a sin(pi / n); the
/// wheel's radius is a cos(pi / n) (the pin enters the slot tangentially). The
/// rim between slots is cut by the concave locking arc of radius
/// `lock_radius + clearance / 2` about the driver's centre.
#[derive(Clone, Debug)]
pub struct GenevaWheel {
    pub slots: usize,
    pub centre_distance: f64,
    pub pin_diameter: f64,
    pub clearance: f64,
    /// The driver's locking disc radius; 0 = crank radius − pin diameter.
    pub lock_radius: f64,
    pub width: f64,
}

/// Derived Geneva sizes: (crank radius, wheel radius, slot inner centre radius, locking disc radius).
pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
    let n = wheel.slots as f64;
    let a = wheel.centre_distance;
    let crank = a * (PI / n).sin();
    let radius = a * (PI / n).cos();
    let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
    (crank, radius, a - crank, lock)
}

/// The Geneva wheel section, counter-clockwise; lines and arcs. Slot k on
/// angle 2 pi k / n. Roles: `SL<k>`/`SU<k>` its sides, `SE<k>` its end arc,
/// `RA<k>`/`RB<k>` the rim arcs either side of the locking arc `LA<k>` that
/// follows slot k.
pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
    let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
    if !(3..=12).contains(&slots) {
        return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
    }
    if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
        return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
    }
    let n = slots as f64;
    let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
    let half = (dp + c) / 2.0; // half the slot width
    let rl = lock + c / 2.0;
    if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
        return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
    }
    // Adjacent slots must not meet: their ends (and sides) stay apart only
    // while the end centres are more than a slot width apart.
    if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
        return Err(refuse(
            "gear_input",
            format!("Adjacent slots meet near the hub: {slots} slots {:.4} wide need a larger centre distance than {a}, or a smaller pin.", 2.0 * half),
        ));
    }
    let x_top = (rw * rw - half * half).sqrt();
    let p1 = [x_top, half];
    let beta = PI / n;
    let centre = [a * beta.cos(), a * beta.sin()];
    // Rim circle (O, rw) meets the locking circle (centre, rl).
    let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
    let h2 = rw * rw - along * along;
    if h2 <= 0.0 {
        return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
    }
    let h = h2.sqrt();
    let e = [beta.cos(), beta.sin()];
    let perp = [-beta.sin(), beta.cos()];
    let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
    let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
    let a1 = polar_angle(p1);
    if polar_angle(q1) <= a1 + 1e-9 {
        return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
    }
    let tau = TAU / n;
    let slot: Vec<(&'static str, NurbsCurve)> = vec![
        ("SL", line([x_top, -half], [end_centre, -half])?),
        ("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
        ("SU", line([end_centre, half], p1)?),
        ("RA", arc(rw, a1, polar_angle(q1))?),
        ("LA", arc_through(centre, q1, q2, false)?),
        ("RB", arc(rw, polar_angle(q2), tau - a1)?),
    ];
    let mut curves = Vec::with_capacity(6 * slots);
    for index in 0..slots {
        let angle = tau * index as f64;
        for (role, curve) in &slot {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let _ = crank;
    Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
}

/// A Geneva wheel solid: the section extruded along +z; names as the
/// section's roles, then `F` and `B`.
pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = geneva_section(wheel)?;
    let solid = extrude_section(&section, wheel.width)?;
    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A cylindrical worm with an Archimedean (ZA) thread: straight flanks in the
/// axial section at the axial pressure angle. Lengths in model units.
#[derive(Clone, Debug)]
pub struct Worm {
    pub axial_module: f64,
    pub starts: usize,
    /// Reference (pitch) diameter d1 = q × axial module.
    pub reference_diameter: f64,
    pub pressure_angle: f64,
    pub addendum: f64,
    pub dedendum: f64,
    pub length: f64,
    pub hand: Hand,
}

impl Worm {
    /// The lead: starts × axial pitch.
    pub fn lead(&self) -> f64 {
        self.starts as f64 * PI * self.axial_module
    }

    /// The axial thread thickness at a radius (ZA: straight axial flanks).
    pub fn axial_thickness(&self, radius: f64) -> f64 {
        PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
    }
}

/// The worm's transverse section (z = 0), counter-clockwise: per start j (its
/// thread centred on angle 2 pi j / n) `R<j>` the flank on its clockwise side,
/// `K<j>` the thread's tip, `L<j>` the other flank, `G<j>` the root after it.
/// The flanks are Archimedean spirals (fitted), tip and root exact arcs.
pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
    let m = worm.axial_module;
    if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
        return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
    }
    if worm.starts < 1 || worm.starts > 8 {
        return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
    }
    let degrees = worm.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    let r1 = worm.reference_diameter / 2.0;
    let ra = r1 + worm.addendum * m;
    let rf = r1 - worm.dedendum * m;
    if !(rf > 0.0) {
        return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
    }
    let lead = worm.lead();
    let gamma = (lead / (PI * worm.reference_diameter)).atan();
    if gamma.to_degrees() > 45.0 {
        return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
    }
    if worm.axial_thickness(ra) <= 1e-6 * m {
        return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
    }
    let n = worm.starts as f64;
    let pitch = PI * m;
    if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
        return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
    }
    // Half the angular width of a thread at radius r in the transverse plane.
    let half = |r: f64| PI * worm.axial_thickness(r) / lead;
    let flank = |r: f64| {
        let t = half(r);
        [r * t.cos(), r * t.sin()]
    };
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; // root -> tip on the +angle side
    let tau = TAU / n;
    let thread: Vec<(&'static str, NurbsCurve)> = vec![
        ("R", mirrored(&upper)),
        ("K", arc(ra, -half(ra), half(ra))?),
        ("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
        ("G", arc(rf, half(rf), tau - half(rf))?),
    ];
    let mut curves = Vec::with_capacity(4 * worm.starts);
    for index in 0..worm.starts {
        let angle = tau * index as f64;
        for (role, curve) in &thread {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
    Ok(GearSection { curves, data })
}

/// A worm solid: the transverse section screwed along +z by the length (one
/// lead per turn); names as the section's roles, then `F` and `B`.
pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = worm_section(worm)?;
    let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
    let turn = sign * TAU * worm.length / worm.lead();
    let solid = twisted_prism(&section, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A cycloidal-drive disc: `pins` housing pins of diameter `pin_diameter` on a
/// circle of `pin_circle_diameter`, the disc running at `eccentricity`; the disc
/// has pins − 1 lobes. Its profile is the equidistant (by the pin radius plus
/// half the clearance) of the epitrochoid the pin centres trace relative to it.
#[derive(Clone, Debug)]
pub struct CycloidalDisc {
    pub pins: usize,
    pub pin_circle_diameter: f64,
    pub pin_diameter: f64,
    pub eccentricity: f64,
    /// Running clearance (diametral): the profile stands clearance / 2 further off the pins.
    pub clearance: f64,
    pub width: f64,
}

impl CycloidalDisc {
    /// The epitrochoid of the pin centres relative to the disc, and its derivative.
    fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
        let r = self.pin_circle_diameter / 2.0;
        let e = self.eccentricity;
        let n = self.pins as f64;
        (
            [r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
            [-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
        )
    }

    /// The disc profile point at parameter t: the trochoid moved by the offset
    /// along its normal towards the disc's centre.
    pub fn profile(&self, t: f64) -> [f64; 2] {
        let (q, d) = self.trochoid(t);
        let length = d[0].hypot(d[1]);
        let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
        // The trochoid runs clockwise (y = -r sin t ...); its right-hand normal points inward.
        let n = [d[1] / length, -d[0] / length];
        [q[0] + offset * n[0], q[1] + offset * n[1]]
    }
}

/// The disc's section, counter-clockwise: one fitted piece per lobe, `LB<k>`.
pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
    let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
    if !(4..=200).contains(&pins) {
        return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
    }
    if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
        return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
    }
    let n = pins as f64;
    let r = dc / 2.0;
    // The trochoid loops back on itself once e >= r / n.
    if e >= r / n * (1.0 - 1e-9) {
        return Err(refuse(
            "gear_input",
            format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
        ));
    }
    // The offset must stay under the trochoid's smallest radius of curvature (else the lobes cusp).
    let offset = dp / 2.0 + clearance / 2.0;
    // An inward offset can cusp only where the (clockwise) curve turns
    // clockwise, its centre of curvature inside. Radius of curvature there,
    // from the closed-form first and second derivatives.
    let (rr, ee) = (dc / 2.0, e);
    let radius = |t: f64| -> f64 {
        let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
        let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
        let cross = d[0] * dd[1] - d[1] * dd[0];
        let speed = d[0].hypot(d[1]);
        if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
    };
    // The curve repeats every 2 pi / (n - 1): sample one period densely, then
    // refine every local minimum by golden-section search.
    let period = TAU / (n - 1.0);
    let samples = 2000;
    let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
    let mut least = f64::INFINITY;
    for i in 0..=samples {
        let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
        let next = values[if i == samples { 1 } else { i + 1 }];
        if values[i] <= previous && values[i] <= next && values[i].is_finite() {
            let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
            for _ in 0..100 {
                let a = lo + (hi - lo) * 0.381966;
                let b = hi - (hi - lo) * 0.381966;
                if radius(a) < radius(b) { hi = b } else { lo = a }
            }
            least = least.min(radius(0.5 * (lo + hi)));
        }
    }
    if offset >= least * (1.0 - 1e-6) {
        return Err(refuse(
            "undercut",
            format!("The pins ({dp}) are too large for this eccentricity and pin circle: the lobes would cusp (the pin radius plus half the clearance must be under {least:.4})."),
        ));
    }
    let lobes = pins - 1;
    let step = TAU / lobes as f64;
    let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
    // The trochoid runs clockwise in t: walk t downwards for a counter-clockwise section.
    let mut curves = Vec::with_capacity(lobes);
    for k in 0..lobes {
        let (a, b) = (step * k as f64, step * (k + 1) as f64);
        let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
        curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
    }
    snap_junctions(&mut curves);
    Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
}

/// A cycloidal disc solid: the section extruded along +z; names `LB<k>`, `F`, `B`.
pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = cycloidal_disc_section(disc)?;
    let solid = extrude_section(&section, disc.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// The pin ring of a cycloidal drive: a ring of `outside` diameter whose bore
/// is the pin circle, with `pins` pins of `pin_diameter` centred on it (half
/// standing into the bore). Exact arcs. Faces: `P<k>` the pins' exposed halves,
/// `G<k>` the bore between pins, `OD`, `F`, `B`.
pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
    if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
        return Err(refuse("gear_input", "The pin ring needs 4 to 200 pins, a pin circle larger than the pins and a positive width.".into()));
    }
    let r = pin_circle_diameter / 2.0;
    let rp = pin_diameter / 2.0;
    let n = pins as f64;
    let tau = TAU / n;
    // Where a pin's circle crosses the bore circle (radius r): half-angle delta about the origin.
    let delta = 2.0 * (rp / (2.0 * r)).asin();
    if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
        return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
    }
    let centre = [r, 0.0];
    let a = [r * (-delta).cos(), r * (-delta).sin()];
    let b = [r * delta.cos(), r * delta.sin()];
    // The pin bulges into the bore: its arc from a to b passes through (r - rp, 0).
    let cw = arc_through(centre, a, b, false)?;
    let pin_arc = {
        let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
        let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
        if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
    };
    let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
    let mut curves = Vec::with_capacity(2 * pins);
    for k in 0..pins {
        for (role, curve) in &space {
            curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
        }
    }
    snap_junctions(&mut curves);
    let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
    let ring = hub_from_section(&section, outside, width)?;
    Ok((ring, section.data))
}

/// A cycloidal (clock-style) gear: teeth whose addenda are epicycloids rolled
/// by a circle of `generating_radius` on the pitch circle and whose dedenda are
/// radial lines (the hypocycloid of a circle of half the mate's pitch radius).
#[derive(Clone, Debug)]
pub struct CycloidalGear {
    pub module: f64,
    pub teeth: usize,
    /// Radius of the rolling circle (usually half the mating gear's pitch radius).
    pub generating_radius: f64,
    /// Tooth thickness on the pitch circle as a fraction of the circular pitch.
    pub tooth_fraction: f64,
    /// Addendum limit × module (the tip is pointed if the flanks meet first).
    pub addendum: f64,
    /// Dedendum × module.
    pub dedendum: f64,
    pub width: f64,
}

/// The cycloidal gear's section, counter-clockwise. Per tooth k: `R<k>`/`L<k>`
/// the radial dedendum flanks, `ER<k>`/`EL<k>` the epicycloidal addenda, `K<k>`
/// the tip land (absent when pointed), `G<k>` the root land.
pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
        return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
    }
    if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
        return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
    }
    if gear.teeth < 6 || gear.teeth > 1000 {
        return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
    }
    let z = gear.teeth as f64;
    let r = m * z / 2.0;
    let rho = gear.generating_radius;
    let rf = r - gear.dedendum * m;
    if !(rf > 0.0) {
        return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
    }
    let tau = TAU / z;
    let psi = PI * gear.tooth_fraction / z; // half the tooth angle on the pitch circle
    // The right flank's epicycloid, from the pitch circle at angle -psi.
    let k = (r + rho) / rho;
    let epi = |phi: f64| {
        let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
        rotate(p, -psi)
    };
    let ra = r + gear.addendum * m;
    // Run phi up until the curve reaches the tip circle or the tooth centre line (angle 0).
    let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
    let mut hi = 1e-3;
    while !reach(hi) {
        hi *= 1.5;
        if hi > PI {
            return Err(refuse("gear_input", "The addendum curve does not close.".into()));
        }
    }
    let mut lo = 0.0;
    for _ in 0..200 {
        let mid = 0.5 * (lo + hi);
        if reach(mid) { hi = mid } else { lo = mid }
    }
    let end = epi(hi);
    // Pointed when the flank reaches the tooth centre line no later than the
    // tip circle (a tip land narrower than 1e-9 counts as pointed).
    let pointed = polar_angle(end) >= -1e-9;
    let phi_end = if pointed {
        let (mut lo, mut hi) = (0.0, hi);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
        }
        hi
    } else {
        hi
    };
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; // pitch -> tip, right side
    let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
    let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
    let tip_angle = -polar_angle(epi(phi_end));
    if !pointed {
        tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
    }
    tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
    tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
    tooth.push(("G", arc(rf, psi, tau - psi)?));
    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = tau * index as f64;
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: 2.0 * r,
        tip_diameter: 2.0 * radius_of(epi(phi_end)),
        root_diameter: 2.0 * rf,
        tooth_thickness: 2.0 * psi * r,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A cycloidal gear solid; names as the section's roles, then `F` and `B`.
pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = cycloidal_gear_section(gear)?;
    let solid = extrude_section(&section, gear.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A straight bevel gear with spherical-involute teeth (the true conjugate
/// form; not Tredgold's back-cone approximation). Module at the heel, shaft
/// angle 90°, pitch cone angle atan(z / z_mate). Apex at the origin, axis +z,
/// the teeth between cone distances R − face width and R; back and front
/// faces are the back and front cones (perpendicular to the pitch cone).
#[derive(Clone, Debug)]
pub struct BevelGear {
    pub module: f64,
    pub teeth: usize,
    pub mate_teeth: usize,
    pub pressure_angle: f64,
    pub addendum: f64,
    pub dedendum: f64,
    pub face_width: f64,
    pub backlash: f64,
}

/// Derived bevel sizes: (pitch cone angle, cone distance, base cone angle).
pub fn bevel_cones(gear: &BevelGear) -> (f64, f64, f64) {
    let delta = (gear.teeth as f64).atan2(gear.mate_teeth as f64);
    let cone = gear.module * gear.teeth as f64 / (2.0 * delta.sin());
    let base = (delta.sin() * gear.pressure_angle.cos()).asin();
    (delta, cone, base)
}

/// A point of the spherical involute of the base cone (half angle `base`) on
/// the sphere of radius `r`, unwrapped by `phi` from the base circle at azimuth 0.
fn spherical_involute(r: f64, base: f64, phi: f64) -> [f64; 3] {
    let (s, c) = base.sin_cos();
    let t = phi * s;
    [
        r * (t.cos() * s * phi.cos() + t.sin() * phi.sin()),
        r * (t.cos() * s * phi.sin() - t.sin() * phi.cos()),
        r * t.cos() * c,
    ]
}

/// The polar angle from the axis (the cone angle) of a point.
fn cone_angle(p: [f64; 3]) -> f64 {
    p[0].hypot(p[1]).atan2(p[2])
}

/// Central projection from the apex onto the plane z = h.
fn project(p: [f64; 3], h: f64) -> [f64; 2] {
    [p[0] * h / p[2], p[1] * h / p[2]]
}

/// The bevel gear section: the spherical tooth outline on the sphere through
/// the heel, centrally projected onto the plane z = h (so every surface the
/// apex sees edge-on — tooth flanks, root and tip cones — becomes a planar
/// curve; the cones' circles project to exact arcs). Counter-clockwise; roles
/// as the spur gear's: `V/R/K/L/W/G` with `V/W` the radial (meridian) root
/// extension below the base cone when the root lies under it.
pub fn bevel_section(gear: &BevelGear, h: f64) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.backlash >= 0.0) {
        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
    }
    if gear.teeth < 6 || gear.mate_teeth < 6 {
        return Err(refuse("gear_input", "A bevel pair needs at least 6 teeth on each gear.".into()));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    let (delta, r, base) = bevel_cones(gear);
    if gear.face_width > r / 3.0 + 1e-9 {
        return Err(refuse(
            "face_too_wide",
            format!("The face width ({}) is over a third of the cone distance ({:.4}): the teeth would be too small at the toe.", gear.face_width, r),
        ));
    }
    let z = gear.teeth as f64;
    let tip = delta + gear.addendum * m / r;
    let root = delta - gear.dedendum * m / r;
    if !(root > 0.0) {
        return Err(refuse("root_below_centre", "The root cone passes the axis: fewer dedendum or more teeth.".into()));
    }
    // The unwrap angle where the involute reaches a cone angle theta: cos(phi sin b) cos b = cos theta.
    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
    // Position the left flank: half the tooth thickness (arc on the pitch circle of radius r sin delta) at the pitch cone.
    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
    let p_pitch = spherical_involute(r, base, phi_at(delta));
    // The involute (unwrapping counter-clockwise) leans to positive azimuth as it rises: the left flank
    // is it mirrored, turned so its pitch point sits at +half.
    let shift = half + azimuth(p_pitch);
    let left = |phi: f64| {
        let p = spherical_involute(r, base, phi);
        let q = [p[0], -p[1], p[2]];
        let (s, c) = shift.sin_cos();
        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
    };
    let tip_phi = phi_at(tip);
    if azimuth(left(tip_phi)) <= 1e-6 * m / r {
        return Err(refuse("pointed_tip", "The teeth come to a point below the tip cone: reduce the addendum.".into()));
    }
    // At the base cone the involute leaves with zero speed (a cusp in phi):
    // when the root lies under it, the flank starts a little above (2% of the
    // unwrap) and the radial root extension runs up to that point.
    let extend = !(root > base); // the root lies on or under the base cone: a radial extension
    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let flank = fit_planar(&|phi| project(left(phi), h), start_phi, tip_phi, tolerance)?; // root side -> tip
    let tau = TAU / z;
    let base_point = project(left(start_phi), h);
    let root_r = h * root.tan();
    let tip_r = h * tip.tan();
    let foot_angle = base_point[1].atan2(base_point[0]);
    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
    let tip_angle = {
        let p = project(left(tip_phi), h);
        p[1].atan2(p[0])
    };
    // Right side (mirror), going up: [V radial] + R; tip K; then L down + [W radial]; G root land.
    let radial_foot = [root_r * foot_angle.cos(), root_r * foot_angle.sin()];
    if extend {
        tooth.push(("V", line([radial_foot[0], -radial_foot[1]], [base_point[0], -base_point[1]])?));
    }
    tooth.push(("R", mirrored(&flank)));
    tooth.push(("K", arc(tip_r, -tip_angle, tip_angle)?));
    tooth.push(("L", flank.reversed().map_err(|e| refuse("gear_fit", e))?));
    if extend {
        tooth.push(("W", line(base_point, radial_foot)?));
    }
    if foot_angle >= tau / 2.0 - 1e-9 {
        return Err(refuse("teeth_overlap", "The tooth roots meet: fewer teeth or a smaller pressure angle.".into()));
    }
    tooth.push(("G", arc(root_r, foot_angle, tau - foot_angle)?));
    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = tau * index as f64;
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    // Lift the section into the plane z = h.
    for piece in &mut curves {
        for p in &mut piece.curve.control_points {
            p.z = p.w * h;
        }
    }
    snap_junctions(&mut curves);
    // Diameters at the heel: where each cone meets the back cone (perpendicular
    // to the pitch cone at cone distance r).
    let heel = |angle: f64| 2.0 * r * angle.sin() / (angle - delta).cos();
    let data = GearData {
        pitch_diameter: 2.0 * r * delta.sin(),
        tip_diameter: heel(tip),
        root_diameter: heel(root),
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A straight bevel gear solid: the section's cone (every curve carried to
/// and from the apex by scaling, so the flanks are exactly the cones over the
/// spherical involutes) cut to the back and front cones. Faces carry their
/// roles in `face.name` (`R3`, `K0`, …, `BACK`, `FRONT`).
pub fn bevel_solid(gear: &BevelGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
    let (delta, r, _) = bevel_cones(gear);
    let rho = r - gear.face_width;
    let m = gear.module;
    let tip = delta + gear.addendum * m / r;
    let h = r * delta.cos();
    let mut section = bevel_section(gear, h)?;
    // The cone of the section, from below the lowest blank point inside it to above the back cone's apex.
    let z_lo = 0.5 * rho * tip.cos() / (tip - delta).cos();
    let z_hi = 1.05 * r / delta.cos();
    let (s_lo, s_hi) = (z_lo / h, z_hi / h);
    for piece in &mut section.curves {
        for p in &mut piece.curve.control_points {
            p.x *= s_lo;
            p.y *= s_lo;
            p.z *= s_lo;
        }
    }
    let grow = s_hi / s_lo;
    let rows = |p: Vec4| vec![p, Vec4 { x: p.x * grow, y: p.y * grow, z: p.z * grow, w: p.w }];
    let mut cone = prism_by_rows(&section, 1, &[0.0, 0.0, 1.0, 1.0], &rows)?;
    let count = section.curves.len();
    for (index, face) in cone.shells[0].faces.iter_mut().enumerate() {
        face.name = Some(if index < count { section.curves[index].suffix() } else { "CAP".into() });
    }
    // The blank: between the front and back cones, out past the tip.
    let r_out = r * tip.sin() * 1.2 + m;
    let (sd, cd) = delta.sin_cos();
    let back_apex = [0.0, r / cd];
    let front_apex = [0.0, rho / cd];
    let out = |along: f64| {
        // From the pitch point at cone distance `along`, outwards on the line perpendicular to the pitch cone.
        let t = (r_out - along * sd) / cd;
        [along * sd + t * cd, along * cd - t * sd]
    };
    let (f2, b2) = (out(rho), out(r));
    let at = |q: [f64; 2]| Vec3::new(q[0], 0.0, q[1]);
    let line3 = |a: [f64; 2], b: [f64; 2]| crate::make_line(at(a), at(b)).map_err(|e| refuse("gear_blank", e));
    let revolve = |profile: Vec<NurbsCurve>, names: &[&str]| -> Result<BrepSolid, KernelRefusal> {
        let names: Vec<Option<String>> = names.iter().map(|n| Some(n.to_string())).collect();
        crate::revolve_profile_brep_named(&profile, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), TAU, &names, &[])
            .map_err(|e| refuse("gear_blank", e))
    };
    // Below the back cone: a cone of material under it, out past the tip and down below the cone's foot.
    // Below everything the back cone bounds: under the cone prism's foot and the back cone's outer point.
    let low = (z_lo * 0.5).min(b2[1]) - m;
    let back = revolve(
        vec![line3(back_apex, b2)?, line3(b2, [b2[0], low])?, line3([b2[0], low], [0.0, low])?, line3([0.0, low], back_apex)?],
        &["BACK", "BX1", "BX2", "BX3"],
    )?;
    // Above the front cone.
    let high = z_hi * 1.1;
    let front = revolve(
        vec![line3(front_apex, [0.0, high])?, line3([0.0, high], [f2[0], high])?, line3([f2[0], high], f2)?, line3(f2, front_apex)?],
        &["FX1", "FX2", "FX3", "FRONT"],
    )?;
    let cut = crate::boolean_operation_nary(&[cone, back], crate::BooleanOperation::Intersect)?;
    let gear_solid = crate::boolean_operation_nary(&[cut, front], crate::BooleanOperation::Intersect)?;
    Ok((gear_solid, section.data))
}

/// An elliptical gear: the pitch curve is an ellipse turning about one of its
/// foci, and the teeth are generated by rolling the standard basic rack round
/// it without slip (the rack's pitch line tangent to the ellipse, the contact
/// normal through the touching point), as a spur gear is generated round its
/// pitch circle. Two identical elliptical gears with an odd tooth count mesh
/// at a centre distance of the major axis (see [`elliptical_sizes`]).
///
/// The ellipse is sized so its perimeter is exactly `teeth` circular pitches
/// (π · module), so the teeth close. Tooth 0 is centred on the near vertex
/// (on +x, closest to the pivot).
#[derive(Clone, Debug)]
pub struct EllipticalGear {
    pub module: f64,
    pub teeth: usize,
    /// Eccentricity of the pitch ellipse (0 is a spur gear turning about its centre).
    pub eccentricity: f64,
    pub pressure_angle: f64,
    /// Addendum coefficient × module, measured normal to the pitch curve.
    pub addendum: f64,
    /// Dedendum coefficient × module, normal to the pitch curve.
    pub dedendum: f64,
    /// Tip radius of the generating rack × module.
    pub root_fillet: f64,
    /// Arc length added to each tooth space along the pitch curve.
    pub backlash: f64,
    pub face_width: f64,
}

/// The pitch ellipse about its focus, by arc length.
struct PitchEllipse {
    /// Semi-latus rectum: r(θ) = p / (1 + e cos θ) about the focus.
    latus: f64,
    e: f64,
    /// Cumulative arc length at θ = 2π i / SEGMENTS.
    table: Vec<f64>,
}

impl PitchEllipse {
    const SEGMENTS: usize = 1024;

    fn new(latus: f64, e: f64) -> Self {
        let mut curve = Self { latus, e, table: Vec::with_capacity(Self::SEGMENTS + 1) };
        // Five-point Gauss-Legendre per segment.
        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
        let step = TAU / Self::SEGMENTS as f64;
        let mut total = 0.0;
        curve.table.push(0.0);
        for i in 0..Self::SEGMENTS {
            let mid = (i as f64 + 0.5) * step;
            let sum: f64 = nodes.iter().zip(&weights).map(|(x, w)| w * curve.speed(mid + 0.5 * step * x)).sum();
            total += 0.5 * step * sum;
            curve.table.push(total);
        }
        curve
    }

    fn length(&self) -> f64 {
        self.table[Self::SEGMENTS]
    }

    /// Point, first and second derivatives in θ.
    fn derivatives(&self, theta: f64) -> ([f64; 2], [f64; 2], [f64; 2]) {
        let (s, c) = theta.sin_cos();
        let d = 1.0 + self.e * c;
        let d1 = -self.e * s;
        let d2 = -self.e * c;
        let r = self.latus / d;
        let r1 = -self.latus * d1 / (d * d);
        let r2 = -self.latus * (d2 * d - 2.0 * d1 * d1) / (d * d * d);
        (
            [r * c, r * s],
            [r1 * c - r * s, r1 * s + r * c],
            [r2 * c - 2.0 * r1 * s - r * c, r2 * s + 2.0 * r1 * c - r * s],
        )
    }

    fn speed(&self, theta: f64) -> f64 {
        let (_, d1, _) = self.derivatives(theta);
        d1[0].hypot(d1[1])
    }

    /// The polar angle at arc length `s` (any real; the curve is periodic).
    fn theta_at(&self, s: f64) -> f64 {
        let length = self.length();
        let turns = (s / length).floor();
        let local = s - turns * length;
        let index = self.table.partition_point(|&value| value <= local).clamp(1, Self::SEGMENTS) - 1;
        let step = TAU / Self::SEGMENTS as f64;
        let (lo, hi) = (index as f64 * step, (index + 1) as f64 * step);
        let span = self.table[index + 1] - self.table[index];
        let mut theta = lo + step * (local - self.table[index]) / span;
        // Newton on the segment's arc length, measured from its start by Gauss-Legendre.
        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
        for _ in 0..8 {
            let half = 0.5 * (theta - lo);
            let arc: f64 = half * nodes.iter().zip(&weights).map(|(x, w)| w * self.speed(lo + half * (1.0 + x))).sum::<f64>();
            let error = self.table[index] + arc - local;
            theta = (theta - error / self.speed(theta)).clamp(lo, hi);
            if error.abs() < 1e-15 * length {
                break;
            }
        }
        theta + turns * TAU
    }

    /// Point, unit tangent (counter-clockwise), outward unit normal and signed curvature at arc length `s`.
    fn frame(&self, s: f64) -> ([f64; 2], [f64; 2], [f64; 2], f64) {
        let (p, d1, d2) = self.derivatives(self.theta_at(s));
        let speed = d1[0].hypot(d1[1]);
        let t = [d1[0] / speed, d1[1] / speed];
        let curvature = (d1[0] * d2[1] - d1[1] * d2[0]) / speed.powi(3);
        (p, t, [t[1], -t[0]], curvature)
    }
}

/// The derived sizes of an elliptical gear: (semi-major axis, eccentricity,
/// perimeter, centre distance to an identical mate = 2 × semi-major axis).
pub fn elliptical_sizes(gear: &EllipticalGear) -> (f64, f64, f64, f64) {
    let e = gear.eccentricity;
    let unit = PitchEllipse::new(1.0 - e * e, e); // semi-major axis 1
    let a = PI * gear.module * gear.teeth as f64 / unit.length();
    (a, e, PI * gear.module * gear.teeth as f64, 2.0 * a)
}

/// The rack, pitch line on y = 0 with +y away from the gear, rolled to arc
/// length `s`: rack point (x, y) lies at P(s) + (x − s) T(s) + y N(s).
struct RollingRack<'a> {
    pitch: &'a PitchEllipse,
}

impl RollingRack<'_> {
    /// The gear point generated by the rack point `q` with normal direction `n`
    /// (either sense): the normal through q meets the pitch line at the rolling position.
    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
        let s = q[0] - q[1] * n[0] / n[1];
        self.place(q, s)
    }

    fn place(&self, q: [f64; 2], s: f64) -> [f64; 2] {
        let (p, t, n, _) = self.pitch.frame(s);
        let u = q[0] - s;
        [p[0] + u * t[0] + q[1] * n[0], p[1] + u * t[1] + q[1] * n[1]]
    }

    /// The arc length of the foot of the normal from `g` to the pitch curve
    /// (starting near `guess`) and the signed distance along the outward normal.
    fn foot(&self, g: [f64; 2], guess: f64) -> (f64, f64) {
        let mut sigma = guess;
        for _ in 0..40 {
            let (p, t, n, curvature) = self.pitch.frame(sigma);
            let v = [g[0] - p[0], g[1] - p[1]];
            let along = v[0] * t[0] + v[1] * t[1];
            let distance = v[0] * n[0] + v[1] * n[1];
            let step = along / (1.0 + curvature * distance);
            sigma += step;
            if step.abs() < 1e-15 * self.pitch.length() {
                break;
            }
        }
        let (p, _, n, _) = self.pitch.frame(sigma);
        (sigma, (g[0] - p[0]) * n[0] + (g[1] - p[1]) * n[1])
    }
}

/// The elliptical gear section, counter-clockwise about the pivot (the focus,
/// at the origin). Roles per tooth k, as the spur gear's: `V<k>` root fillet,
/// `R<k>` flank rising to `K<k>` the tip land (normal offset of the pitch
/// curve), `L<k>` the falling flank, `W<k>` root fillet, `G<k>` the root land
/// (inward offset) of the space after tooth k.
pub fn elliptical_section(gear: &EllipticalGear) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0) {
        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
    }
    if !(gear.root_fillet >= 0.0 && gear.backlash >= 0.0) {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    if !(0.0..=0.8).contains(&gear.eccentricity) {
        return Err(refuse("gear_input", format!("The eccentricity must be from 0 to 0.8 (it is {}).", gear.eccentricity)));
    }
    if gear.teeth < 8 || gear.teeth > 1000 {
        return Err(refuse("gear_input", format!("An elliptical gear needs from 8 to 1000 teeth (it has {}).", gear.teeth)));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    let (a, e, perimeter, _) = elliptical_sizes(gear);
    let pitch_curve = PitchEllipse::new(a * (1.0 - e * e), e);
    let rack = RollingRack { pitch: &pitch_curve };
    let z = gear.teeth as f64;
    let p = perimeter / z;
    let alpha = gear.pressure_angle;
    let (sin_a, cos_a, tan_a) = (alpha.sin(), alpha.cos(), alpha.tan());
    let h_a = gear.addendum * m;
    let h_f = gear.dedendum * m;
    let rho = gear.root_fillet * m;
    let tolerance = GEAR_FIT_TOLERANCE * m;
    // The sharpest point of the ellipse is its major vertex: radius b²/a.
    let min_radius = a * (1.0 - e * e);
    if h_f >= min_radius {
        return Err(refuse(
            "undercut",
            format!("The root would fold at the ellipse's ends (radius of curvature {min_radius:.4} there): add teeth or lower the eccentricity."),
        ));
    }
    // Cutter tooth centred on x = 0 (it cuts the space there): half width at height y is w0 + y tan α.
    let w0 = p / 4.0 + gear.backlash / 2.0;
    let centre_y = -h_f + rho;
    let centre_x = -w0 - (centre_y - rho * sin_a) * tan_a + rho * cos_a; // low-side fillet centre
    if centre_x >= 0.0 {
        return Err(refuse("root_fillet_too_large", "The root fillet is larger than fits the tooth space; lower it.".into()));
    }
    let y_join = centre_y - rho * sin_a;
    let low_flank = |c: f64, y: f64| rack.envelope([c - w0 - y * tan_a, y], [cos_a, sin_a]);
    let high_flank = |c: f64, y: f64| rack.envelope([c + w0 + y * tan_a, y], [-cos_a, sin_a]);
    // ψ ∈ [0, 1]: from the flank tangency (0) to the tip line (1).
    let fillet_normal = |t: f64| {
        let psi = -PI + alpha + t * (PI / 2.0 - alpha);
        [psi.cos(), psi.sin()]
    };
    let low_fillet = |c: f64, t: f64| {
        let n = fillet_normal(t);
        if rho == 0.0 {
            return rack.envelope([c + centre_x, centre_y], n);
        }
        rack.envelope([c + centre_x + rho * n[0], centre_y + rho * n[1]], n)
    };
    let high_fillet = |c: f64, t: f64| {
        let n = fillet_normal(t);
        if rho == 0.0 {
            return rack.envelope([c - centre_x, centre_y], [-n[0], n[1]]);
        }
        rack.envelope([c - centre_x - rho * n[0], centre_y + rho * n[1]], [-n[0], n[1]])
    };
    let root = |x: f64| rack.place([x, -h_f], x);
    let tip = |sigma: f64| {
        let (q, _, n, _) = pitch_curve.frame(sigma);
        [q[0] + h_a * n[0], q[1] + h_a * n[1]]
    };
    // The generated flank is regular while sin²α + y κ > 0 down to its foot (it cusps
    // where the rack flank passes the point of interference); κ is largest, 1 / min_radius,
    // at the major vertices.
    if sin_a * sin_a + y_join / min_radius <= 1e-9 {
        return Err(refuse(
            "undercut",
            format!(
                "The teeth would be undercut where the ellipse is sharpest (radius of curvature {min_radius:.4}): add teeth, lower the eccentricity or raise the pressure angle."
            ),
        ));
    }
    // The flank height where a generated flank reaches the tip offset (offset distance h_a).
    let top_of = |flank: &dyn Fn(f64) -> [f64; 2], guess: f64| -> Result<(f64, f64), KernelRefusal> {
        let offset = |y: f64| rack.foot(flank(y), guess).1 - h_a;
        let (mut lo, mut hi) = (y_join, h_a + 2.0 * m);
        if !(offset(lo) < 0.0 && offset(hi) > 0.0) {
            return Err(refuse("gear_fit", "The generated flank does not reach the tip curve.".into()));
        }
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if offset(mid) < 0.0 { lo = mid } else { hi = mid }
        }
        let y = 0.5 * (lo + hi);
        Ok((y, rack.foot(flank(y), guess).0))
    };
    let mut curves = Vec::with_capacity(6 * gear.teeth);
    let reversed = |curve: NurbsCurve| curve.reversed().map_err(|error| refuse("gear_fit", error));
    for k in 0..gear.teeth {
        let before = (k as f64 - 0.5) * p; // the space before tooth k
        let after = (k as f64 + 0.5) * p;
        let rising = |y: f64| high_flank(before, y);
        let falling = |y: f64| low_flank(after, y);
        let (y_rise, sigma_rise) = top_of(&rising, k as f64 * p - w0)?;
        let (y_fall, sigma_fall) = top_of(&falling, k as f64 * p + w0)?;
        if sigma_fall - sigma_rise <= 1e-6 * m {
            return Err(refuse("pointed_tip", "The teeth come to a point below the tip curve: reduce the addendum or the backlash.".into()));
        }
        curves.push(SectionCurve { curve: reversed(fit_planar(&|t| high_fillet(before, t), 0.0, 1.0, tolerance)?)?, role: "V", tooth: k });
        curves.push(SectionCurve { curve: fit_planar(&rising, y_join, y_rise, tolerance)?, role: "R", tooth: k });
        curves.push(SectionCurve { curve: fit_planar(&tip, sigma_rise, sigma_fall, tolerance)?, role: "K", tooth: k });
        curves.push(SectionCurve { curve: reversed(fit_planar(&falling, y_join, y_fall, tolerance)?)?, role: "L", tooth: k });
        curves.push(SectionCurve { curve: fit_planar(&|t| low_fillet(after, t), 0.0, 1.0, tolerance)?, role: "W", tooth: k });
        if centre_x < -1e-9 * m {
            curves.push(SectionCurve { curve: fit_planar(&root, after + centre_x, after - centre_x, tolerance)?, role: "G", tooth: k });
        }
    }
    snap_junctions(&mut curves);
    let samples = 4096;
    let (mut tip_max, mut root_min) = (0.0_f64, f64::INFINITY);
    for i in 0..samples {
        let s = perimeter * i as f64 / samples as f64;
        tip_max = tip_max.max(radius_of(tip(s)));
        root_min = root_min.min(radius_of(rack.place([s, -h_f], s)));
    }
    let data = GearData {
        pitch_diameter: perimeter / PI,
        tip_diameter: 2.0 * tip_max,
        root_diameter: 2.0 * root_min,
        tooth_thickness: p / 2.0 - gear.backlash,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// An elliptical gear solid: the section extruded along +z by the face width;
/// names as the section's roles, then `F` and `B`.
pub fn elliptical_solid(gear: &EllipticalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = elliptical_section(gear)?;
    let solid = extrude_section(&section, gear.face_width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// The parameter breaks (normalised to [0, 1]) at which [`fit_planar`] would
/// split `f` on `[a, b]` to fit it within `tolerance`.
fn adaptive_breaks(f: &dyn Fn(f64) -> [f64; 2], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
    let mut breaks = vec![0.0];
    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
    while let Some((t0, t1, depth)) = pending.pop() {
        if hermite_span_error(f, t0, t1) > tolerance {
            if depth >= 16 {
                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
            }
            let mid = 0.5 * (t0 + t1);
            pending.push((mid, t1, depth + 1));
            pending.push((t0, mid, depth + 1));
        } else {
            breaks.push(t1);
        }
    }
    Ok(breaks)
}

/// The cubic Hermite span of `f` on `[t0, t1]` (numeric end derivatives) as Bézier points.
fn hermite_span(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> [[f64; 2]; 4] {
    let derivative = |t: f64| {
        let h = 1e-6;
        let (p, q) = (f(t + h), f(t - h));
        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
    };
    let (p0, p1) = (f(t0), f(t1));
    let (d0, d1) = (derivative(t0), derivative(t1));
    let k = (t1 - t0) / 3.0;
    [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
}

fn hermite_span_error(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> f64 {
    let c = hermite_span(f, t0, t1);
    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
        .iter()
        .map(|&u| {
            let exact = f(t0 + (t1 - t0) * u);
            let v = 1.0 - u;
            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
            let x = w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0];
            let y = w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1];
            (exact[0] - x).hypot(exact[1] - y)
        })
        .fold(0.0, f64::max)
}

/// `f` on [0, 1] as C1 cubic Hermite spans at the given breaks (as
/// [`fit_planar`] lays them out), and its worst error over the spans.
fn fit_on_breaks(f: &dyn Fn(f64) -> [f64; 2], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
    let mut knots = vec![0.0; 4];
    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
    let mut worst = 0.0_f64;
    let spans = breaks.len() - 1;
    for index in 0..spans {
        let (t0, t1) = (breaks[index], breaks[index + 1]);
        let c = hermite_span(f, t0, t1);
        worst = worst.max(hermite_span_error(f, t0, t1));
        if index == 0 {
            points.push(to_point(c[0]));
        }
        points.push(to_point(c[1]));
        points.push(to_point(c[2]));
        if index + 1 < spans {
            knots.extend([t1, t1]);
        } else {
            points.push(to_point(c[3]));
        }
    }
    knots.extend([1.0; 4]);
    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
}

/// A throated (single-enveloping) worm wheel: the teeth are cut as a hob of
/// the mating ZA worm cuts them, the worm's thread swept by the generating
/// motion (the worm turning, the wheel turning with it at the gear ratio).
/// In every plane across the face width the worm's thread section moves as a
/// rack and the wheel section is its envelope; the flanks, tips (the throat,
/// a torus about the worm's axis) and roots are skinned through those
/// sections. Front face on z = 0, back face on z = face width; the worm's
/// axis runs along +y at x = centre distance, z = face width / 2.
#[derive(Clone, Debug)]
pub struct WormWheel {
    /// The mating worm (its length is not used).
    pub worm: Worm,
    pub teeth: usize,
    /// Wheel addendum × module, in the mid-plane (the throat).
    pub addendum: f64,
    /// Wheel dedendum × module, in the mid-plane: the hob's tip (the worm's tip plus the clearance).
    pub dedendum: f64,
    pub face_width: f64,
    /// Axial backlash: the hob's thread is that much thicker than the worm's.
    pub backlash: f64,
}

/// The worm wheel's sizes: (pitch radius, centre distance, throat radius in the mid-plane, outside radius at the faces).
pub fn worm_wheel_sizes(wheel: &WormWheel) -> (f64, f64, f64, f64) {
    let m = wheel.worm.axial_module;
    let r2 = m * wheel.teeth as f64 / 2.0;
    let a = r2 + wheel.worm.reference_diameter / 2.0;
    let throat = r2 + wheel.addendum * m;
    let tube = a - throat;
    let half = wheel.face_width / 2.0;
    (r2, a, throat, a - (tube * tube - half * half).max(0.0).sqrt())
}

/// One plane z = c (from the mid-plane) of the wheel: the hob section as a rack.
struct WheelPlane<'a> {
    wheel: &'a WormWheel,
    c: f64,
    r2: f64,
    a: f64,
    /// The hob's tip radius about the worm axis.
    rho_tip: f64,
    /// The wheel's tip (throat) radius in this plane.
    r_tip: f64,
    /// Flank parameters (radius about the worm axis) where each flank reaches the tip: [- side, + side].
    rho_clip: [f64; 2],
}

impl<'a> WheelPlane<'a> {
    fn new(wheel: &'a WormWheel, c: f64) -> Result<Self, KernelRefusal> {
        let m = wheel.worm.axial_module;
        let (r2, a, throat, _) = worm_wheel_sizes(wheel);
        let rho_tip = a - (r2 - wheel.dedendum * m);
        let tube = a - throat;
        let r_tip = a - (tube * tube - c * c).sqrt();
        let mut plane = Self { wheel, c, r2, a, rho_tip, r_tip, rho_clip: [0.0; 2] };
        for (index, side) in [-1.0, 1.0].into_iter().enumerate() {
            // The generated flank falls from above the tip to the root. A hob point with rho under the throat's
            // tube radius sits beyond the throat (x = a - sqrt(rho^2 - c^2) > r_tip), and so does its envelope.
            let (mut lo, mut hi) = (0.5 * (c.abs() + tube), rho_tip);
            if !(radius_of(plane.flank(side, lo)) > r_tip && radius_of(plane.flank(side, hi)) < r_tip) {
                return Err(refuse("gear_fit", "A worm wheel flank does not reach its throat.".into()));
            }
            for _ in 0..200 {
                let mid = 0.5 * (lo + hi);
                if radius_of(plane.flank(side, mid)) > r_tip { lo = mid } else { hi = mid }
            }
            plane.rho_clip[index] = 0.5 * (lo + hi);
        }
        Ok(plane)
    }

    /// The hob flank point (radial x from the wheel axis, y along the worm axis) at radius `rho`
    /// about the worm axis, on the `side` (±1) of the thread centred on y = 0.
    fn hob(&self, side: f64, rho: f64) -> [f64; 2] {
        let worm = &self.wheel.worm;
        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
        let thickness = worm.axial_thickness(rho) + self.wheel.backlash;
        let angle = (self.c / rho).clamp(-1.0, 1.0).asin();
        [self.a - (rho * rho - self.c * self.c).max(0.0).sqrt(), side * thickness / 2.0 + hand * worm.lead() * angle / TAU]
    }

    fn hob_normal(&self, side: f64, rho: f64) -> [f64; 2] {
        // d/drho of hob(): x = a - sqrt(rho^2 - c^2), y = side t(rho) / 2 + hand L asin(c / rho) / 2 pi (exact:
        // a difference quotient's rounding noise is magnified by the fits' own derivative steps).
        let worm = &self.wheel.worm;
        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
        let root = (rho * rho - self.c * self.c).max(1e-300).sqrt();
        let t = [-rho / root, -side * worm.pressure_angle.tan() - hand * worm.lead() * self.c / (TAU * rho * root)];
        let length = t[0].hypot(t[1]);
        // Outward of the thread: +y on the + side.
        let n = [-t[1] / length, t[0] / length];
        if n[1] * side >= 0.0 { n } else { [-n[0], -n[1]] }
    }

    /// The wheel point generated by the hob point `q` with normal `n` (rolling at the pitch radius).
    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
        let s = (q[0] - self.r2) * n[1] / n[0] - q[1];
        rotate([q[0], q[1] + s], -s / self.r2)
    }

    fn flank(&self, side: f64, rho: f64) -> [f64; 2] {
        self.envelope(self.hob(side, rho), self.hob_normal(side, rho))
    }

    /// The root fillet the hob's sharp tip corner traces, `t` from the flank (0) to the tip land (1).
    fn fillet(&self, side: f64, t: f64) -> [f64; 2] {
        let n = self.hob_normal(side, self.rho_tip);
        let from = n[1].atan2(n[0]);
        let psi = from + t * (side * PI - from);
        self.envelope(self.hob(side, self.rho_tip), [psi.cos(), psi.sin()])
    }

    /// The six pieces of tooth 0 on normalised parameters, in section order V, R, K, L, W, G.
    fn piece(&self, role: usize, t: f64) -> [f64; 2] {
        let tau = TAU / self.wheel.teeth as f64;
        let half = tau / 2.0;
        let turn = |p: [f64; 2], angle: f64| rotate(p, angle);
        let root_r = self.a - (self.rho_tip * self.rho_tip - self.c * self.c).sqrt();
        match role {
            0 => turn(self.fillet(1.0, 1.0 - t), -half),
            1 => turn(self.flank(1.0, self.rho_tip + t * (self.rho_clip[1] - self.rho_tip)), -half),
            2 => {
                let from = polar_angle(self.flank(1.0, self.rho_clip[1]));
                let to = tau + polar_angle(self.flank(-1.0, self.rho_clip[0]));
                let angle = from + t * (to - from) - half;
                [self.r_tip * angle.cos(), self.r_tip * angle.sin()]
            }
            3 => turn(self.flank(-1.0, self.rho_clip[0] + t * (self.rho_tip - self.rho_clip[0])), half),
            4 => turn(self.fillet(-1.0, t), half),
            _ => {
                // The root land of the space after the tooth (the base space turned by tau, then by -half).
                let from = polar_angle(self.fillet(-1.0, 1.0));
                let to = polar_angle(self.fillet(1.0, 1.0));
                let angle = from + t * (to - from) + half;
                [root_r * angle.cos(), root_r * angle.sin()]
            }
        }
    }

    /// Refuse a plane whose teeth are pointed, whose roots meet, or whose flanks are undercut.
    fn check(&self) -> Result<(), KernelRefusal> {
        let m = self.wheel.worm.axial_module;
        let tau = TAU / self.wheel.teeth as f64;
        let tip_span = tau + polar_angle(self.flank(-1.0, self.rho_clip[0])) - polar_angle(self.flank(1.0, self.rho_clip[1]));
        if tip_span * self.r_tip <= 1e-6 * m {
            return Err(refuse("pointed_tip", format!("The wheel teeth come to a point below the throat {:.4} from the mid-plane: lower the addendum or the face width.", self.c)));
        }
        let root_span = polar_angle(self.fillet(1.0, 1.0)) - polar_angle(self.fillet(-1.0, 1.0));
        if root_span <= 1e-9 {
            return Err(refuse("teeth_overlap", "The worm thread is wider than the wheel's tooth space at the root: lower the dedendum.".into()));
        }
        // Each flank must fall steadily from its tip to its root, and the corner's trace must not cross it.
        for side in [-1.0, 1.0] {
            let index = if side < 0.0 { 0 } else { 1 };
            let flank: Vec<[f64; 2]> = (0..=96).map(|i| self.flank(side, self.rho_clip[index] + (self.rho_tip - self.rho_clip[index]) * i as f64 / 96.0)).collect();
            let fillet: Vec<[f64; 2]> = (0..=48).map(|i| self.fillet(side, i as f64 / 48.0)).collect();
            let falling = flank.windows(2).all(|pair| radius_of(pair[1]) < radius_of(pair[0]));
            let crosses = flank[..flank.len() - 2].windows(2).any(|f| fillet[1..].windows(2).any(|g| segments_cross(f[0], f[1], g[0], g[1])));
            if !falling || crosses {
                return Err(refuse(
                    "undercut",
                    format!("The worm undercuts the wheel teeth {:.4} from the mid-plane: add wheel teeth, narrow the face width or raise the pressure angle.", self.c),
                ));
            }
        }
        Ok(())
    }
}

fn segments_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
    let cross = |o: [f64; 2], p: [f64; 2], q: [f64; 2]| (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]);
    let (d1, d2) = (cross(c, d, a), cross(c, d, b));
    let (d3, d4) = (cross(a, b, c), cross(a, b, d));
    d1 * d2 < 0.0 && d3 * d4 < 0.0
}

const WHEEL_ROLES: [&str; 6] = ["V", "R", "K", "L", "W", "G"];

/// Tooth 0's six curves in the plane `c`, fitted on the shared breaks, at height z.
fn wheel_tooth(plane: &WheelPlane, breaks: &[Vec<f64>], z: f64) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
    let mut curves = Vec::with_capacity(6);
    let mut worst = 0.0_f64;
    for (role, role_breaks) in breaks.iter().enumerate() {
        let (mut curve, error) = fit_on_breaks(&|t| plane.piece(role, t), role_breaks)?;
        worst = worst.max(error);
        for p in &mut curve.control_points {
            p.z = z * p.w;
        }
        curves.push(curve);
    }
    Ok((curves, worst))
}

/// The full section (every tooth) from tooth 0's curves, junctions shared.
fn wheel_section(tooth: &[NurbsCurve], teeth: usize) -> Vec<SectionCurve> {
    let tau = TAU / teeth as f64;
    let mut curves = Vec::with_capacity(6 * teeth);
    for index in 0..teeth {
        for (role, curve) in tooth.iter().enumerate() {
            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: WHEEL_ROLES[role], tooth: index });
        }
    }
    snap_junctions(&mut curves);
    curves
}

/// A throated worm wheel solid and its data; face names as the spur gear's
/// per tooth (`V/R/K/L/W/G<n>`, the `K` faces making the throat), then `F` (z = 0) and `B`.
pub fn worm_wheel_solid(wheel: &WormWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let worm = &wheel.worm;
    let m = worm.axial_module;
    worm_section(worm)?; // the worm's own checks
    if wheel.teeth < 12 || wheel.teeth > 400 {
        return Err(refuse("gear_input", format!("A worm wheel needs from 12 to 400 teeth (it has {}).", wheel.teeth)));
    }
    if !(wheel.addendum > 0.0 && wheel.dedendum > 0.0 && wheel.face_width > 0.0 && wheel.backlash >= 0.0) {
        return Err(refuse("gear_input", "The wheel's addendum, dedendum and face width must be positive, the backlash not negative.".into()));
    }
    let (r2, a, throat, _) = worm_wheel_sizes(wheel);
    let tube = a - throat;
    let limit = 0.9 * tube;
    if wheel.face_width / 2.0 > limit {
        return Err(refuse(
            "face_too_wide",
            format!("The face width ({}) must stay inside the throat: at most {:.4} for this worm.", wheel.face_width, 2.0 * limit),
        ));
    }
    // The hob's thread at the wheel's tip (in the mid-plane) must leave a tooth in the axial pitch. Checked
    // here, before any polar angle: a thread a whole pitch wider wraps round to the same teeth.
    if worm.axial_thickness(tube) + wheel.backlash >= PI * m - 1e-6 * m {
        return Err(refuse("pointed_tip", format!("The backlash ({}) leaves no wheel tooth: the hob's thread fills the whole axial pitch at the throat.", wheel.backlash)));
    }
    if worm.axial_thickness(a - (r2 - wheel.dedendum * m)) + wheel.backlash <= 1e-6 * m {
        return Err(refuse("pointed_tip", "The hob's thread (the worm's, grown to the wheel's root) comes to a point: lower the wheel dedendum.".into()));
    }
    let half = wheel.face_width / 2.0;
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let skin_tolerance = 1e-5 * m;
    // Shared breaks per role from the mid-plane and both faces.
    let probe: Vec<WheelPlane> = [-half, 0.0, half].iter().map(|&c| WheelPlane::new(wheel, c)).collect::<Result<_, _>>()?;
    for plane in &probe {
        plane.check()?;
    }
    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(6);
    for role in 0..6 {
        let mut all: Vec<f64> = Vec::new();
        for plane in &probe {
            all.extend(adaptive_breaks(&|t| plane.piece(role, t), tolerance)?);
        }
        all.sort_by(f64::total_cmp);
        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
        breaks.push(all);
    }
    // Planes across the face; each plane's control points carried along v by
    // cubic Hermite spans (derivatives from planes a step either side).
    let mut planes = 8usize;
    loop {
        let step = wheel.face_width / planes as f64;
        let delta = 1e-3 * step;
        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1); // tooth 0 per plane
        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
        let mut refit = false;
        for j in 0..=planes {
            let c = -half + step * j as f64;
            let plane = WheelPlane::new(wheel, c)?;
            plane.check()?;
            let (tooth, worst) = wheel_tooth(&plane, &breaks, c + half)?;
            if worst > tolerance {
                refit = true;
                break;
            }
            let lo = wheel_tooth(&WheelPlane::new(wheel, c - delta)?, &breaks, 0.0)?.0;
            let hi = wheel_tooth(&WheelPlane::new(wheel, c + delta)?, &breaks, 0.0)?.0;
            let slope: Vec<Vec<[f64; 2]>> = lo
                .iter()
                .zip(&hi)
                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
                .collect();
            rows.push(tooth);
            slopes.push(slope);
        }
        if refit {
            // A plane the shared breaks fit too loosely: halve every span and start over.
            for role_breaks in &mut breaks {
                let mut finer = Vec::with_capacity(2 * role_breaks.len());
                for pair in role_breaks.windows(2) {
                    finer.push(pair[0]);
                    finer.push(0.5 * (pair[0] + pair[1]));
                }
                finer.push(1.0);
                *role_breaks = finer;
            }
            continue;
        }
        // Check the skin halfway between planes against the exact plane there.
        let mut worst = 0.0_f64;
        for j in 0..planes {
            let c = -half + step * (j as f64 + 0.5);
            let exact = wheel_tooth(&WheelPlane::new(wheel, c)?, &breaks, 0.0)?.0;
            for role in 0..6 {
                for (k, p) in exact[role].control_points.iter().enumerate() {
                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
                    worst = worst.max((x - p.x).hypot(y - p.y));
                }
            }
        }
        if worst > skin_tolerance {
            if planes >= 256 {
                return Err(refuse("gear_fit", format!("The worm wheel's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
            }
            planes *= 2;
            continue;
        }
        // Rows along v for every control point of the full bottom section, keyed by its bits.
        let sections: Vec<Vec<SectionCurve>> = rows.iter().map(|tooth| wheel_section(tooth, wheel.teeth)).collect();
        let tau = TAU / wheel.teeth as f64;
        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
        let h = 1.0 / planes as f64;
        for (index, piece) in sections[0].iter().enumerate() {
            let (role, tooth) = (index % 6, index / 6);
            let (s, cs) = (tau * tooth as f64).sin_cos();
            for (k, p) in piece.curve.control_points.iter().enumerate() {
                let mut row = Vec::with_capacity(3 * planes + 1);
                for j in 0..=planes {
                    let q = sections[j][index].curve.control_points[k];
                    let d = slopes[j][role][k];
                    // The slope in v (per unit v: face width per unit c), turned with the tooth.
                    let dv = [wheel.face_width * (cs * d[0] - s * d[1]), wheel.face_width * (s * d[0] + cs * d[1]), wheel.face_width];
                    let point = Vec3::new(q.x, q.y, q.z);
                    if j > 0 {
                        row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
                    }
                    if j == 0 || j == planes {
                        row.push(Vec4::from_point(point, 1.0));
                    }
                    if j < planes {
                        row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
                    }
                }
                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
            }
        }
        let mut knots_v = vec![0.0; 4];
        for j in 1..planes {
            let v = j as f64 * h;
            knots_v.extend([v, v]);
        }
        knots_v.extend([1.0; 4]);
        let section = GearSection { curves: sections[0].clone(), data: GearData::default() };
        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
            table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
        })?;
        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
        names.push("F".into());
        names.push("B".into());
        let data = GearData {
            pitch_diameter: 2.0 * r2,
            tip_diameter: 2.0 * throat,
            root_diameter: 2.0 * (r2 - wheel.dedendum * m),
            tip_thickness: 0.0,
            ..GearData::default()
        };
        return Ok((solid, names, data));
    }
}