BREP_construction 0.25.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
//! 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: 0.0, 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
/// by t · width, as a surface (u along the curve, v = t).
fn twisted_surface(curve: &NurbsCurve, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsSurface, KernelRefusal> {
    let rows = curve
        .control_points
        .iter()
        .map(|p| {
            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()
        })
        .collect();
    NurbsSurface::new(curve.degree, 3, curve.knots.clone(), knots_v.to_vec(), rows).map_err(|e| refuse("gear_surface", e))
}

/// The axial edge through a section point.
fn twisted_edge(point: Vec4, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsCurve, KernelRefusal> {
    let (x, y) = (point.x / point.w, point.y / point.w);
    let points = basis
        .iter()
        .map(|[c, s, t]| Vec4 { x: c * x - s * y, y: s * x + c * y, z: t * width, w: 1.0 })
        .collect();
    NurbsCurve::new(3, knots_v.to_vec(), points).map_err(|e| refuse("gear_edge", e))
}

/// 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> {
    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
    if !(width > 0.0) {
        return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
    }
    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
    let count = curves.len();
    let reach = curves
        .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 (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
    let end_angle = twist.angle(1.0);
    let lift = |curve: &NurbsCurve| -> NurbsCurve {
        let mut top = rotated(curve, end_angle);
        for point in &mut top.control_points {
            point.z += point.w * width;
        }
        top
    };
    let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
    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) });
    }
    let (se, ce) = end_angle.sin_cos();
    for (index, start) in starts.iter().enumerate() {
        let p = point_of(*start);
        vertices.push(VertexRecord {
            id: (count + index) as u64 + 1,
            point: Vec3::new(ce * p.x - se * p.y, se * p.x + ce * p.y, width),
        });
    }
    // Ids: edges from 10, coedges/loops/faces past every edge id.
    let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
    let mut edges = Vec::with_capacity(3 * 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;
        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: lift(curve), 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: twisted_edge(starts[index], width, &knots_v, &basis)?, 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 });
    }
    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;
        faces.push(FaceRecord {
            id: next_id + 1,
            surface: twisted_surface(curve, width, &knots_v, &basis)?,
            same_sense: true,
            loops: vec![LoopRecord { id: next_id, coedges }],
            name: None,
        });
        next_id += 2;
    }
    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 bottom_origin = Vec3::new(-pad, -pad, 0.0);
    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, width);
    let mut top = Vec::with_capacity(count);
    for (index, curve) in curves.iter().enumerate() {
        top.push(CoedgeRecord {
            id: next_id,
            edge_id: edge_id(1, index),
            forward: true,
            pcurve: curve_to_plane_parameters(&lift(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!("twisted 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))
}