BREP_direct_edit 0.28.0

Rust B-rep CAD kernel (next.BREP.io): direct editing of B-rep faces: move, rotate, offset, draft, delete and refit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
//! Move Face by RE-CUTTING — the second road, for a motion whose answer is a
//! different topology rather than the same topology re-solved.
//!
//! # Why a second road at all
//!
//! `face_move.rs` and `face_move_carrier.rs` both MOVE A CARRIER and re-solve
//! the boundary that is already there. Where the motion leaves the body with
//! the same faces meeting the same faces, that is the whole answer, and where
//! it leaves two of them crossing, `healing/accept.rs` splits the pair along
//! their exact section and drops the overshoot. Between them they cover every
//! Transform Face the capability matrix records as building.
//!
//! They do not cover a motion whose result needs a face to STOP EXISTING.
//! The 2026-09-22 inbox document is the first report of one: a rectangular
//! through-slot cut into a block, with the slot's CEILING and one of its SIDE
//! WALLS dragged together, the ceiling carried 90 mm — clean out of the top of
//! the part. The right body is the slot re-cut as an open channel, which has
//! the ceiling gone, both side walls re-trimmed against two different outer
//! faces, and the slot's mouth loops on the two end faces merged into those
//! faces' outer loops. Measured against the boolean that cuts the same channel
//! directly: **10F 24E 16V**, where the direct edit leaves 11F.
//!
//! The pairwise crossing repair cannot reach that body, and the reason is
//! structural rather than a threshold. It splits ONE pair of crossing faces
//! along their carriers' section and drops pieces, closed over the faces the
//! imprint cut. Here the two crossings (`Box_PZ | P.CU6_NX` and `Box_PX |
//! P.CU6_PX`) BOUND EACH OTHER — the strip of the top face that has to go is
//! bounded by both sections at once — and the face that has to go whole, the
//! ceiling, is crossed by nothing at all, so no imprint ever cuts it.
//!
//! # The construction
//!
//! A planar face of a solid states a constraint on where the material is:
//! everything inside lies on one side of its carrier. Moving that face moves
//! the constraint, and the material that changes hands is the SLAB the carrier
//! sweeps, bounded sideways by the faces that bound the moved face today. So:
//!
//! 1. Each moved face must carry a PLANE, and its trim must be loops of
//!    straight edges (`trim_polygon`): the outer trim, and on a translation
//!    any number of ISLANDS — holes through the face or bosses standing on
//!    it, whose walls stay put and decide what the tool does inside them
//!    (the island block of `recut_moved_planes_rigid`). `delta` is how far the face moves
//!    along its own outward normal `n̂` — `translation · n̂` for a
//!    translation; a face whose `delta` is zero only slides inside its own
//!    carrier, moves no material at all, and contributes no tool.
//! 2. The trim is cut into convex CELLS (`convex_cells`): along its own
//!    reflex corners — each cut extends the edge arriving at the corner across
//!    the face to the boundary, so the new edge still lies on that edge's own
//!    neighbour carrier — and, for a turn, along the HINGE the old and new
//!    carriers meet in, wherever it crosses a cell. Every cell then lies on
//!    one side of every plane that bounds it and moves one way.
//! 3. The TOOL for a cell is the slab (for a turn, the wedge) between the
//!    face's old and new carrier, intersected with one half-space per cell
//!    edge — the neighbour's carrier across that edge, or the plane through
//!    the hinge — and clipped to a box around the body big enough to hold the
//!    motion.
//! 4. Which SIDE of each bound the tool lies on is read from a PROBE POINT
//!    rather than classified: the cell's centroid, displaced half way along
//!    the cell's own normal motion, lies inside the slab (or wedge) by
//!    construction, and the tool is on the side of every bound that contains
//!    it. That one rule covers a cell moving INTO the body and a cell moving
//!    OUT of it without a convexity branch.
//! 5. Which POSITION of a neighbour that is itself in the selection bounds
//!    the tool — where it was, or where the motion leaves it — is set algebra
//!    on the feature the two faces bound together. For a boss `P = ∩ Mⱼ` (the
//!    material half-spaces) the material added is `P' − P = ∪ᵢ (P' ∩ ¬Mᵢ)`,
//!    bounded by the neighbours where the motion LEAVES them, and the material
//!    removed is `P − P' = ∪ᵢ (P ∩ ¬M'ᵢ)`, bounded where they WERE; for a
//!    cavity `C = ∩ ¬Mⱼ` the two swap. Read locally per (cell, neighbour): the
//!    neighbour's MOVED plane iff the cell's seat is on the neighbour's
//!    material side exactly when the cell moves out; its HOME plane otherwise.
//!    (Always-moved, the rule until 2026-09-30, is the growth half of this; a
//!    slot wall swinging out below a ceiling lifted clean out of the part would
//!    have been filled up to that ceiling, a fin above the part.)
//! 6. `delta < 0` — a cell moving against the face's outward normal — takes
//!    material away, `delta > 0` adds it. The removing cells are unioned into
//!    one tool and SUBTRACTED, the adding cells into another and UNIONED, in
//!    that order. In the set algebra above the two tools are disjoint (what
//!    a face removes lies inside the body's old bounds, what it adds outside
//!    them), and on every fixture measured the order made no difference; a
//!    selection that does both is what a turn across the hinge IS, and is no
//!    longer refused.
//!
//! The cells of a direction are unioned before the body is cut, because two
//! tools that share a carrier — the two arms of an L, or the reported
//! document's two faces, which share both `x` and `z` planes — leave coplanar
//! residue when they are subtracted one at a time.
//!
//! Two guards read every cell against its own bounds, so a decomposition that
//! left something for a tool to miss refuses by name rather than cutting some
//! of the material: `cell_is_its_bounds` (class `reflex_trim`; the pre-cell
//! road's convex-core failure, measured at 3600 for a through-L of 3250) and
//! `one_way_only` (the other wedge of a turned cell has volume inside the
//! cell's bounds). Neither fires on a cell the cut produced; both fire the
//! moment the cut is stubbed out.
//!
//! # A turn, too
//!
//! Transform Face's motion is rotate-then-translate, and a plane moved rigidly
//! is still a plane, so `recut_moved_planes_rigid` takes the whole motion: the
//! new carrier is the old one carried by it, the tool is the WEDGE between the
//! two (inside one, outside the other — the slab's own two half-spaces, no
//! longer parallel), `delta` is how far a cell's seat travels along `n̂` to
//! reach the new carrier, and the probe sits half way there. A turn whose
//! hinge crosses the face carries one side into the body and the other out;
//! the hinge split gives each side its own cell and its own tool. A pure
//! translation keeps this road's original SLAB arithmetic (`offset.max(offset
//! + delta)`), so a convex face's slab is the same set of planes it was. The
//! 2026-09-22 report that needed the turn is the slot document with its wall
//! also turned 16.9°
//! (`tests/suites/inbox_20260922_turned_slot_wall_transform_face.rs`); the
//! same document turned 10° about a line ACROSS the wall is the case the
//! hinge split closed on 2026-09-30.
//!
//! # What it is not
//!
//! It is not a repair: nothing about the self-intersecting body the direct
//! edit built is read. It is the same edit performed the other way round, from
//! the ORIGINAL body and the motion, which is why it can return a body with a
//! different face count. `transform_face` reaches it only after `accept_sound`
//! has refused, so no motion that builds today changes by a bit. Of the motions
//! `move_faces` / `rotate_faces` themselves refuse, only one reaches it: a turned
//! face TANGENT to a fillet beside it (`ruling_edge`). The fillet has no
//! half-space, so the tool is bounded past it by the planar faces around it
//! (`tangent_surround`). On the side that moves in, the plane cuts the fillet in
//! a new ruling. On the side that moves out, it may miss the fillet altogether,
//! and the fillet is then filled in, the tilted face meeting the wall beyond it.
//! `reblend_lost_fillets` rounds that edge again at the fillet's radius, or
//! under its radius law where the radius varies along it.
//!
//! Names are RE-STAMPED rather than collected, because the boolean mints its
//! own faces: a result face whose carrier is an original face's carrier (at its
//! moved position, for a moved face) takes that face's name, a carrier that
//! arrives as two faces takes `name_1` for the second as the breakout already
//! does, and a face whose carrier left the body keeps no name because it is no
//! longer there.

use super::*;
use crate::offset_retrim::plane_of_surface;
use crate::topology::ShellRecord;
use crate::{
    boolean_operation, make_plane, BooleanOperation, BooleanOptions,

};
use crate::curve::parameter_line;
use crate::{KernelRefusal, KernelStage, OrRefuse};

const OP: &str = "move_faces(re-cut)";

/// A closed half-space `n̂·x ≤ offset`, with `n̂` a unit vector.
#[derive(Clone, Copy, Debug)]
pub(super) struct HalfSpace {
    pub(super) normal: Vec3,
    pub(super) offset: f64,
}


/// Re-cut a solid for a pure TRANSLATION of planar faces.
///
/// `solid` is the body BEFORE the edit and `moved` its face ids; the result is
/// the body the same selection and translation define, built as a boolean
/// rather than as a carrier re-solve. See the module header for the
/// construction and for every refusal.
///
/// A re-solve looks only at the faces the selection borders, so a result that
/// meets a face it does not border can close incidence-clean on a body that
/// passes through itself. [`crate::accept_sound`] is the floor on the way out
/// of this entry, as it is for [`crate::move_faces`]: it repairs where the
/// crossing can be proved and refuses by name where it cannot.
/// [`recut_moved_planes_unchecked`] is the re-solve alone, for a caller that runs its own
/// acceptance on the result.
pub fn recut_moved_planes(
    solid: &BrepSolid,
    moved: &[u64],
    translation: Vec3,
) -> Result<BrepSolid, KernelRefusal> {
    crate::accept_sound(recut_moved_planes_unchecked(solid, moved, translation)?, "recutMovedPlanes")
}

/// [`recut_moved_planes`] without its soundness floor: returned as soon as its incidences
/// validate. The result can pass through itself; the caller owes it an
/// acceptance scan ([`crate::accept_sound`]) before it is used as a body.
pub fn recut_moved_planes_unchecked(
    solid: &BrepSolid,
    moved: &[u64],
    translation: Vec3,
) -> Result<BrepSolid, KernelRefusal> {
    recut_moved_planes_rigid(solid, moved, None, translation)
}

/// The rigid motion a re-cut carries its selection by: an optional rotation
/// (`p ↦ a + R·(p − a)`, the affine `rotate_faces` applies) FOLLOWED by a
/// translation — Transform Face's rotate-then-translate, in its own order.
struct Motion {
    rotation: Option<AffineTransform>,
    translation: Vec3,
}

impl Motion {
    fn point(&self, point: Vec3) -> Vec3 {
        match &self.rotation {
            None => point.add(self.translation),
            Some(rotation) => rotation.point(point).add(self.translation),
        }
    }

    /// The oriented plane `n̂·x = offset`, carried. A pure translation keeps
    /// the exact arithmetic the translation-only road always used —
    /// `offset + t·n̂`.
    fn plane(&self, normal: Vec3, offset: f64) -> (Vec3, f64) {
        match &self.rotation {
            None => (normal, offset + self.translation.dot(normal)),
            Some(rotation) => {
                let turned = super::face_rotate::rotate_direction(rotation, normal);
                (turned, turned.dot(self.point(normal.scale(offset))))
            }
        }
    }
}

/// Re-cut a solid for a RIGID motion of planar faces: `rotation`, when given as
/// `(axis point, unit axis, angle in radians)`, is applied first and
/// `translation` after it — Transform Face's rotate-then-translate.
///
/// A plane moved rigidly is still a plane, so everything the translation road
/// does carries over with one generalisation: the old and the new carrier need
/// no longer be parallel, and the material that changes hands is the WEDGE
/// between them rather than a slab. That wedge is the same two half-spaces —
/// inside the old carrier and outside the new one (material taken away), or
/// the other way round (material added) — so `convex_solid` builds it as it
/// built the slab.
///
/// The tool for one face is built per CELL of its trim rather than once for
/// the face (`convex_cells`): the trim is cut into convex pieces along its own
/// reflex edges, and a turned face is cut along the HINGE its two carriers
/// meet in, so a cell lies on one side of every plane that bounds it and moves
/// one way only. Each cell's tool is the slab or wedge intersected with one
/// half-space per cell edge, the cells that take material away are unioned
/// into one tool and subtracted, and the cells that add material are unioned
/// into another and added. Two guards read every cell against its own bounds
/// (`cell_is_its_bounds`, `one_way_only`), so a decomposition that left a cell
/// reflex or straddling the hinge refuses by name rather than cutting some of
/// the material.
pub fn recut_moved_planes_rigid(
    solid: &BrepSolid,
    moved: &[u64],
    rotation: Option<(Vec3, Vec3, f64)>,
    translation: Vec3,
) -> Result<BrepSolid, KernelRefusal> {
    let scale = solid_model_scale(solid);
    let tolerance = (scale * 1e-7).max(1e-9);
    let moved_set: HashSet<u64> = moved.iter().copied().collect();
    if moved_set.is_empty() {
        return Err(KernelRefusal::input(
            KernelStage::Collect,
            "selection",
            format!("{OP}: no face was selected"),
        ));
    }
    let motion = Motion {
        rotation: match rotation {
            None => None,
            Some((point, axis, angle)) => {
                let axis = axis.normalized().map_err(|_| {
                    KernelRefusal::input(
                        KernelStage::Collect,
                        "rotation_axis",
                        format!("{OP}: the rotation axis has zero length"),
                    )
                })?;
                Some(
                    super::face_rotate::rotation_about(point, axis, angle)
                        .or_input(KernelStage::Collect, "rotation")?,
                )
            }
        },
        translation,
    };

    // Every moved face's carrier, as an outward-pointing plane. A curved
    // carrier is refused here and not approximated: the slab this road sweeps
    // is a PLANE's slab and nothing else.
    let mut carriers: Vec<(u64, Vec3, f64)> = Vec::new();
    for &id in &moved_set {
        let face = face_by_id(solid, id)?;
        let plane = plane_of_surface(&face.surface, tolerance.max(1e-9) * 10.0, OP).map_err(
            |error| {
                KernelRefusal::unsupported(
                    KernelStage::Classify,
                    "curved_carrier",
                    format!(
                        "{error} — this road sweeps a PLANE's slab, so face {id}{} cannot take it",
                        named(face)
                    ),
                )
            },
        )?;
        let normal = if face.same_sense {
            plane.normal
        } else {
            plane.normal.scale(-1.0)
        };
        carriers.push((id, normal, normal.dot(plane.origin)));
    }
    // Deterministic order: the tools are unioned in this order.
    carriers.sort_by_key(|entry| entry.0);

    // The clip box: the body's own bounds, grown by the motion and a margin,
    // so a tool is a bounded polytope whatever its half-spaces leave open. A
    // turn carries corners further than its translation alone says, so the
    // bounds then also take every vertex where the motion leaves it.
    let bounds = solid_bounds(solid)?;
    let bounds = if motion.rotation.is_none() {
        bounds
    } else {
        solid.vertices.iter().fold(bounds, |(low, high), vertex| {
            let point = motion.point(vertex.point);
            (
                Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z)),
                Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z)),
            )
        })
    };
    let margin = translation.length() + scale.max(1.0);
    let clip = box_half_spaces(bounds, margin);

    let motion_floor = (scale * 1e-9).max(1e-12);
    let edge_band = (scale * 1e-7).max(1e-9);
    let mut removing: Vec<BrepSolid> = Vec::new();
    let mut adding: Vec<BrepSolid> = Vec::new();
    let unite = |mut tools: Vec<BrepSolid>| -> Result<Option<BrepSolid>, KernelRefusal> {
        if tools.is_empty() {
            return Ok(None);
        }
        let mut tool = tools.remove(0);
        for next in tools {
            // The boolean's own class rides through: a degeneracy inside the
            // union is still a degeneracy at this road's boundary.
            tool = boolean_operation(&tool, &next, BooleanOperation::Union, &BooleanOptions::default())
                .map_err(|error| {
                    error.with_message(|message| {
                        format!("{OP}: the tools could not be unioned into one — {message}")
                    })
                })?;
        }
        Ok(Some(tool))
    };
    // A direction's tool less the islands it must leave alone.
    let less_islands = |tool: Option<BrepSolid>, keep: Vec<BrepSolid>| -> Result<Option<BrepSolid>, KernelRefusal> {
        match (tool, unite(keep)?) {
            (Some(tool), Some(keep)) => {
                boolean_operation(&tool, &keep, BooleanOperation::Subtract, &BooleanOptions::default())
                    .map(Some)
                    .map_err(|error| {
                        error.with_message(|message| {
                            format!("{OP}: the islands could not be taken out of the tool — {message}")
                        })
                    })
            }
            (tool, _) => Ok(tool),
        }
    };

    for &(id, normal, offset) in &carriers {
        let face = face_by_id(solid, id)?;
        // This face's own tools start here; its islands are taken out of
        // THEM alone, so one face's island never cancels another face's tool.
        let (removing_from, adding_from) = (removing.len(), adding.len());
        let mut keep_removing: Vec<BrepSolid> = Vec::new();
        let mut keep_adding: Vec<BrepSolid> = Vec::new();
        let (moved_normal, moved_offset) = motion.plane(normal, offset);
        let facing = moved_normal.dot(normal);
        if motion.rotation.is_some() && facing <= 1e-6 {
            return Err(KernelRefusal::ill_posed(
                KernelStage::Classify,
                "turned_past_right_angle",
                format!(
                    "{OP}: the motion turns face {id}{} through a right angle or more, so its \
                     new carrier does not face the way the old one did and there is no wedge \
                     between them for a tool to fill; refusing",
                    named(face)
                ),
            ));
        }
        let unturned = moved_normal.sub(normal).length() <= 1e-12;
        // A pure translation reads the SAME delta everywhere on the face, in
        // the arithmetic the translation-only road always used.
        let translation_delta = translation.dot(normal);
        if motion.rotation.is_none() && translation_delta.abs() <= motion_floor {
            // Slides inside its own carrier: no material moves, no tool.
            continue;
        }

        // Every face that bounds this one, with its outward plane at HOME and
        // where the motion LEAVES it (the same plane for an unmoved face).
        let mut neighbour_planes: HashMap<u64, ((Vec3, f64), (Vec3, f64))> = HashMap::default();
        // A turned face's TANGENT curved neighbours (see `tangent_surround`).
        let mut tangent_bands: HashSet<u64> = HashSet::default();
        let polygon = trim_polygon(solid, face, normal, edge_band)?;
        if !polygon.islands.is_empty() && motion.rotation.is_some() && !turned_islands_enabled() {
            return Err(KernelRefusal::unsupported(
                KernelStage::Classify,
                "island_trim",
                format!(
                    "{OP}: face {id}{} has {} loops and the motion turns it, so its island's walls \
                     would have to be cut along the hinge as well; this road carries an island only \
                     on a translation, refusing rather than filling the island",
                    named(face),
                    face.loops.len()
                ),
            ));
        }
        for source in &polygon.sources {
            let &EdgeSource::Neighbour(neighbour) = source else { continue };
            if neighbour_planes.contains_key(&neighbour) || tangent_bands.contains(&neighbour) {
                continue;
            }
            let other = face_by_id(solid, neighbour)?;
            if motion.rotation.is_some()
                && !moved_set.contains(&neighbour)
                && plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP).is_err()
                && band_is_tangent_along_shared_edges(face, other, normal)
            {
                tangent_bands.insert(neighbour);
                continue;
            }
            let plane = plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP)
                .map_err(|error| {
                    KernelRefusal::unsupported(
                        KernelStage::Classify,
                        "curved_neighbour",
                        format!(
                            "{error} — face {id}{} is bounded by face {neighbour}{}, and this road \
                             needs every bounding carrier as a half-space",
                            named(face),
                            named(other)
                        ),
                    )
                })?;
            let outward = if other.same_sense {
                plane.normal
            } else {
                plane.normal.scale(-1.0)
            };
            let home = (outward, outward.dot(plane.origin));
            let left = if moved_set.contains(&neighbour) {
                motion.plane(home.0, home.1)
            } else {
                home
            };
            neighbour_planes.insert(neighbour, (home, left));
        }

        // The hinge: the line the old and the new carrier meet in, in the
        // face's own 2-D frame — only a TURN has one.
        let hinge = if unturned {
            None
        } else {
            polygon.frame.hinge(normal, offset, moved_normal, moved_offset)
        };
        let cells = convex_cells(&polygon, hinge, edge_band, scale).map_err(|error| {
            KernelRefusal::internal(
                KernelStage::Classify,
                "cell_split",
                format!("{OP}: face {id}{}'s trim could not be cut into convex cells — {error}", named(face)),
            )
        })?;

        let surround = if tangent_bands.is_empty() {
            None
        } else {
            Some(tangent_surround(solid, face, normal, offset, &tangent_bands, &moved_set, tolerance)?)
        };

        for cell in &cells {
            let seat = polygon.frame.lift(cell.centroid());
            // How far this cell travels along the face's own normal to reach
            // the new carrier: `t·n̂` for a translation, the same everywhere;
            // for a turn, read at the cell's own seat, which is on one side of
            // the hinge by construction.
            let delta = if motion.rotation.is_none() {
                translation_delta
            } else {
                (moved_offset - moved_normal.dot(seat)) / facing
            };
            if delta.abs() <= motion_floor {
                if unturned {
                    continue;
                }
                return Err(KernelRefusal::ill_posed(
                    KernelStage::Classify,
                    "turned_through_trim",
                    format!(
                        "{OP}: the motion turns face {id}{} about a line through its own trim, and a \
                         cell of the trim still sits on that line after the hinge split, so which way \
                         it moves is not decided by the geometry; refusing rather than choosing",
                        named(face)
                    ),
                ));
            }
            let adds = delta > 0.0;

            // The two carriers the cell moves between. The tool is inside one
            // and outside the other: inside the OLD and outside the NEW when
            // the cell moves in (material leaves), the other way round when it
            // moves out.
            let (inner, outer) = if adds {
                ((moved_normal, moved_offset), (normal, offset))
            } else {
                ((normal, offset), (moved_normal, moved_offset))
            };
            let wedge = |inner: (Vec3, f64), outer: (Vec3, f64)| {
                [
                    HalfSpace { normal: inner.0, offset: inner.1 },
                    HalfSpace { normal: outer.0.scale(-1.0), offset: -outer.1 },
                ]
            };
            // A growing cell beside a tangent band also fills what the band
            // rounded off, so its inner wall starts behind the band.
            let touches_band = cell.sources.iter().any(|source| {
                matches!(source, EdgeSource::Neighbour(neighbour) if tangent_bands.contains(neighbour))
            });
            let (inner, outer) = match (&surround, adds && touches_band) {
                (Some(surround), true) => (inner, (outer.0, outer.1 - surround.inner_wall_depth)),
                _ => (inner, outer),
            };
            let mut spaces = clip.clone();
            if let (Some(surround), true) = (&surround, touches_band) {
                for plane in &surround.planes {
                    push_unique(
                        &mut spaces,
                        HalfSpace { normal: plane.0, offset: plane.1 },
                        tolerance,
                    );
                }
            }
            if motion.rotation.is_none() {
                // The slab the carrier sweeps, in the arithmetic this road has
                // always used for it.
                spaces.push(HalfSpace {
                    normal,
                    offset: offset.max(offset + delta),
                });
                spaces.push(HalfSpace {
                    normal: normal.scale(-1.0),
                    offset: -offset.min(offset + delta),
                });
            } else {
                spaces.extend(wedge(inner, outer));
            }

            // A point inside the cell, carried half way along the face's own
            // normal to where its new carrier is: inside the slab (or wedge) by
            // construction, and on the tool's side of every plane that bounds it.
            let probe = seat.add(normal.scale(delta * 0.5));

            // The bounds as they stand TODAY, kept beside the ones the tool
            // uses so the cell can be read against them (`cell_is_its_bounds`).
            let mut at_home: Vec<HalfSpace> = Vec::new();
            // The bounds alone, for the other wedge (`one_way_only`).
            let mut sides: Vec<HalfSpace> = Vec::new();

            for (edge, source) in cell.sources.iter().enumerate() {
                // A tangent band has no half-space: `surround.planes` bound the
                // tool past it. For the cell's own read of its bounds, the edge
                // stands for itself.
                if matches!(source, EdgeSource::Neighbour(neighbour) if tangent_bands.contains(neighbour)) {
                    let plane = polygon.frame.edge_plane(cell, edge);
                    let home_sign = if plane.0.dot(seat) - plane.1 > 0.0 { -1.0 } else { 1.0 };
                    push_unique(
                        &mut at_home,
                        HalfSpace { normal: plane.0.scale(home_sign), offset: plane.1 * home_sign },
                        tolerance,
                    );
                    continue;
                }
                let (home, bound) = match source {
                    EdgeSource::Neighbour(neighbour) => {
                        let &(home, left) = neighbour_planes
                            .get(neighbour)
                            .expect("every neighbour's plane was read above");
                        // Which position of a MOVED neighbour bounds the tool is
                        // decided by set algebra on the feature the two faces
                        // bound together. For a convex edge (the cell is on the
                        // neighbour's MATERIAL side — a boss's top against its
                        // wall) material added is `P' − P`, bounded by the
                        // neighbours where the motion leaves them, and material
                        // removed is `P − P'`, bounded where they were. For a
                        // concave edge (the cell is on the neighbour's EMPTY
                        // side — a slot's ceiling against its wall) it is the
                        // other way round: the cavity that grows is bounded by
                        // its new walls, the cavity that shrinks by its old ones.
                        // So: the neighbour's MOVED plane iff the cell sits on
                        // its material side exactly when the cell moves out.
                        let material_side = home.0.dot(seat) - home.1 < 0.0;
                        let bound = if material_side == adds { left } else { home };
                        (home, bound)
                    }
                    EdgeSource::Hinge => {
                        let plane = polygon.frame.edge_plane(cell, edge);
                        (plane, plane)
                    }
                };
                let reach = bound.0.dot(probe) - bound.1;
                if reach.abs() <= tolerance {
                    return Err(KernelRefusal::ill_posed(
                        KernelStage::Classify,
                        "probe_on_carrier",
                        format!(
                            "{OP}: the probe point for face {id} lies ON the carrier of one of its \
                             bounds ({reach:.3e} from it), so which side of that carrier the tool \
                             is on is not decided by the geometry; refusing rather than choosing"
                        ),
                    ));
                }
                let sign = if reach > 0.0 { -1.0 } else { 1.0 };
                let bound = HalfSpace {
                    normal: bound.0.scale(sign),
                    offset: bound.1 * sign,
                };
                // HOME is oriented by the SEAT, which lies in the face's plane
                // and strictly inside the cell: the side the trim is on.
                let home_sign = if home.0.dot(seat) - home.1 > 0.0 { -1.0 } else { 1.0 };
                push_unique(&mut spaces, bound, tolerance);
                push_unique(&mut sides, bound, tolerance);
                push_unique(
                    &mut at_home,
                    HalfSpace {
                        normal: home.0.scale(home_sign),
                        offset: home.1 * home_sign,
                    },
                    tolerance,
                );
            }
            cell_is_its_bounds(face, cell, &polygon.frame, &at_home, scale)?;
            if motion.rotation.is_some() {
                let (home_inner, home_outer) = if adds {
                    ((moved_normal, moved_offset), (normal, offset))
                } else {
                    ((normal, offset), (moved_normal, moved_offset))
                };
                one_way_only(id, &clip, &sides, wedge(home_outer, home_inner), tolerance, || named(face))?;
            }

            let tool = convex_solid(&spaces, probe, tolerance).map_err(|error| {
                KernelRefusal::internal(
                    KernelStage::Fragment,
                    "tool_polytope",
                    format!("{OP}: the tool for face {id} could not be built — {error}"),
                )
            })?;
            if adds {
                adding.push(tool);
            } else {
                removing.push(tool);
            }
        }

        // ISLANDS. The cells above cover the
        // outer trim WHOLE, the islands' feet included, and what that does
        // inside an island is decided by the island's own walls, which carry
        // on to meet the moved face exactly as they met it at home:
        //   * a HOLE (the walls' material outside the island): material
        //     taken away under it is empty already, or is the bottom of a
        //     blind hole the face's new position passes, which goes with the
        //     floor; material ADDED over it must leave the hole open;
        //   * a BOSS (the walls' material inside): material added under its
        //     foot is the boss already; material taken away there must stay,
        //     since the boss's walls run on down to the moved face.
        // So an island is KEPT out of the tool exactly when its inside is
        // material and the tool removes, or empty and the tool adds: a prism
        // over each convex cell of the island, the slab bounded by the
        // island's walls, which is subtracted from that direction's tool.
        //
        // A TURN (`BREP_RECUT_TURNED_ISLANDS`): the island is cut along the
        // same hinge as the trim, so each of its cells lies on one side of it
        // and moves one way, read at the cell's own seat exactly as the trim's
        // cells are; the cell kept out is the WEDGE between the old and the new
        // carrier on that side, bounded by the island's walls and, where the
        // hinge split it, by the plane through the hinge. The walls stay where
        // they are and run on to meet the turned face, so the same rule
        // decides: kept out exactly when the inside is material and the cell
        // removes, or empty and the cell adds.
        for island in &polygon.islands {
            // Hole or boss, read once off the island's OWN boundary (the
            // cells below also carry the carriers their convex split ran
            // along, which are not walls): the polygon is wound
            // counter-clockwise about the face's outward normal, so the
            // island's inside is to the LEFT of each edge, and a wall whose
            // outward normal points that way has its material outside — a
            // hole.
            let mut inside_is_material: Option<bool> = None;
            let corners = island.points.len();
            for (edge, source) in island.sources.iter().enumerate() {
                let &EdgeSource::Neighbour(wall) = source else { continue };
                let other = face_by_id(solid, wall)?;
                if moved_set.contains(&wall) {
                    return Err(KernelRefusal::unsupported(
                        KernelStage::Classify,
                        "island_trim",
                        format!(
                            "{OP}: face {id}{} has an island whose wall, face {wall}{}, moves with it; \
                             this road carries an island only past walls that stay, refusing",
                            named(face),
                            named(other)
                        ),
                    ));
                }
                let plane = plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP).map_err(|error| {
                    KernelRefusal::unsupported(
                        KernelStage::Classify,
                        "curved_neighbour",
                        format!(
                            "{error} — face {id}{} has an island walled by face {wall}{}, and this road \
                             needs every bounding carrier as a half-space",
                            named(face),
                            named(other)
                        ),
                    )
                })?;
                let outward = if other.same_sense { plane.normal } else { plane.normal.scale(-1.0) };
                if outward.dot(normal).abs() > 1e-9 {
                    return Err(KernelRefusal::unsupported(
                        KernelStage::Classify,
                        "island_trim",
                        format!(
                            "{OP}: an island wall of face {id}{}, face {wall}{}, leans against the face's \
                             normal, so the island's section moves sideways as the face moves and this \
                             road's straight prism does not follow it; refusing",
                            named(face),
                            named(other)
                        ),
                    ));
                }
                let along = polygon
                    .frame
                    .lift(island.points[(edge + 1) % corners])
                    .sub(polygon.frame.lift(island.points[edge]));
                let left = normal.cross(along);
                let lean = outward.dot(left) / left.length().max(1e-300);
                if lean.abs() <= 1e-9 {
                    return Err(KernelRefusal::ill_posed(
                        KernelStage::Classify,
                        "island_trim",
                        format!(
                            "{OP}: an island wall of face {id}{}, face {wall}{}, lies in the face's own \
                             plane, so which side of it the island is on is not decided; refusing",
                            named(face),
                            named(other)
                        ),
                    ));
                }
                let material = lean < 0.0;
                if inside_is_material.is_some_and(|known| known != material) {
                    return Err(KernelRefusal::ill_posed(
                        KernelStage::Classify,
                        "island_trim",
                        format!(
                            "{OP}: an island of face {id}{} is walled partly by material and partly \
                             by empty space, so whether the moved face carries it as a hole or as a \
                             boss is not decided by the geometry; refusing",
                            named(face)
                        ),
                    ));
                }
                inside_is_material = Some(material);
            }
            let Some(material) = inside_is_material else { continue };
            if motion.rotation.is_none() && material == (translation_delta > 0.0) {
                // Inside is what the tool makes it anyway.
                continue;
            }
            let cells = convex_cells(island, hinge, edge_band, scale).map_err(|error| {
                KernelRefusal::internal(
                    KernelStage::Classify,
                    "cell_split",
                    format!("{OP}: an island of face {id}{} could not be cut into convex cells — {error}", named(face)),
                )
            })?;
            if motion.rotation.is_some() && hinge.is_some() && !cells.is_empty() {
                // The hinge split drops a piece thinner than the band, which
                // would leave that sliver of the island to the other side's
                // tool: refuse rather than fill a corner of a hole (or cut a
                // corner off a post).
                let unsplit = convex_cells(island, None, edge_band, scale).map_err(|error| {
                    KernelRefusal::internal(
                        KernelStage::Classify,
                        "cell_split",
                        format!("{OP}: an island of face {id}{} could not be cut into convex cells — {error}", named(face)),
                    )
                })?;
                let area = |cells: &[Cell]| cells.iter().map(|cell| cell.signed_area().abs()).sum::<f64>();
                let (whole, kept) = (area(&unsplit), area(&cells));
                // Relative: a dropped piece and the island both scale with the
                // model, and the sums agree to roundoff (~1e-15 of the area).
                if (whole - kept).abs() > 1e-12 * whole {
                    return Err(KernelRefusal::ill_posed(
                        KernelStage::Classify,
                        "island_trim",
                        format!(
                            "{OP}: the hinge of the turn of face {id}{} cuts a piece off one of its islands \
                             thinner than this road's band ({:.3e} of {:.3e}), so that piece would move \
                             with the wrong side; refusing rather than dropping it",
                            named(face),
                            whole - kept,
                            whole
                        ),
                    ));
                }
            }
            if cells.is_empty() {
                return Err(KernelRefusal::ill_posed(
                    KernelStage::Classify,
                    "island_trim",
                    format!(
                        "{OP}: an island of face {id}{} is thinner than this road's band, so it has no \
                         cell to keep out of the tool and would vanish; refusing rather than \
                         dropping it",
                        named(face)
                    ),
                ));
            }
            for cell in &cells {
                let seat = polygon.frame.lift(cell.centroid());
                let delta = if motion.rotation.is_none() {
                    translation_delta
                } else {
                    (moved_offset - moved_normal.dot(seat)) / facing
                };
                if delta.abs() <= motion_floor {
                    return Err(KernelRefusal::ill_posed(
                        KernelStage::Classify,
                        "turned_through_trim",
                        format!(
                            "{OP}: the motion turns face {id}{} about a line through one of its islands, \
                             and a cell of that island still sits on the line after the hinge split, so \
                             which way it moves is not decided by the geometry; refusing rather than \
                             choosing",
                            named(face)
                        ),
                    ));
                }
                let adds = delta > 0.0;
                if material == adds {
                    // Inside is what this side's tool makes it anyway.
                    continue;
                }
                let mut spaces = clip.clone();
                if motion.rotation.is_none() {
                    spaces.push(HalfSpace { normal, offset: offset.max(offset + delta) });
                    spaces.push(HalfSpace { normal: normal.scale(-1.0), offset: -offset.min(offset + delta) });
                } else {
                    // The wedge on this cell's side of the hinge: inside the
                    // old carrier and outside the new one where the cell moves
                    // in, the other way round where it moves out.
                    let (inner, outer) = if adds {
                        ((moved_normal, moved_offset), (normal, offset))
                    } else {
                        ((normal, offset), (moved_normal, moved_offset))
                    };
                    spaces.push(HalfSpace { normal: inner.0, offset: inner.1 });
                    spaces.push(HalfSpace { normal: outer.0.scale(-1.0), offset: -outer.1 });
                }
                // Every carrier the cell's edges lie on — the island's walls,
                // the ones its convex split ran along and, on a turn, the plane
                // through the hinge — read from the seat, which a convex cell
                // has on one side of each.
                for (edge, source) in cell.sources.iter().enumerate() {
                    let wall = match *source {
                        EdgeSource::Neighbour(wall) => wall,
                        EdgeSource::Hinge => {
                            let plane = polygon.frame.edge_plane(cell, edge);
                            let sign = if plane.0.dot(seat) - plane.1 > 0.0 { -1.0 } else { 1.0 };
                            push_unique(
                                &mut spaces,
                                HalfSpace { normal: plane.0.scale(sign), offset: plane.1 * sign },
                                tolerance,
                            );
                            continue;
                        }
                    };
                    let other = face_by_id(solid, wall)?;
                    let plane = plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP)
                        .map_err(|error| {
                            KernelRefusal::unsupported(KernelStage::Classify, "curved_neighbour", error)
                        })?;
                    let outward = if other.same_sense { plane.normal } else { plane.normal.scale(-1.0) };
                    let reach = outward.dot(seat) - outward.dot(plane.origin);
                    if reach.abs() <= tolerance {
                        return Err(KernelRefusal::ill_posed(
                            KernelStage::Classify,
                            "probe_on_carrier",
                            format!(
                                "{OP}: a cell of an island of face {id} has its seat ON the carrier of \
                                 its wall {wall} ({reach:.3e} from it); refusing rather than choosing"
                            ),
                        ));
                    }
                    let sign = if reach > 0.0 { -1.0 } else { 1.0 };
                    push_unique(
                        &mut spaces,
                        HalfSpace { normal: outward.scale(sign), offset: outward.dot(plane.origin) * sign },
                        tolerance,
                    );
                }
                let probe = seat.add(normal.scale(delta * 0.5));
                let prism = convex_solid(&spaces, probe, tolerance).map_err(|error| {
                    KernelRefusal::internal(
                        KernelStage::Fragment,
                        "tool_polytope",
                        format!("{OP}: the island tool for face {id} could not be built — {error}"),
                    )
                })?;
                if adds {
                    keep_adding.push(prism);
                } else {
                    keep_removing.push(prism);
                }
            }
        }
        // This face's tools, less its own islands.
        if !keep_removing.is_empty() {
            let own = removing.split_off(removing_from);
            removing.extend(less_islands(unite(own)?, keep_removing)?);
        }
        if !keep_adding.is_empty() {
            let own = adding.split_off(adding_from);
            adding.extend(less_islands(unite(own)?, keep_adding)?);
        }
    }
    if removing.is_empty() && adding.is_empty() {
        return Err(KernelRefusal::input(
            KernelStage::Classify,
            "in_plane_motion",
            format!(
                "{OP}: every selected face slides inside its own carrier (the motion has no \
                 component along any of their normals), so there is no material for a re-cut to \
                 move"
            ),
        ));
    }

    // One tool per direction, then one cut per direction. Two tools that share
    // a carrier leave coplanar residue when they are applied one at a time,
    // so the cells of a direction are unioned before the body is touched. The
    // two directions' tools are disjoint by construction — what a face removes
    // lies inside the body's old bounds and what it adds lies outside them —
    // so the order of the two cuts is not a choice of answer; the subtract
    // runs first so the added material meets a body already at its new bounds.
    let mut cut = solid.clone();
    if let Some(tool) = unite(removing)? {
        cut = boolean_operation(&cut, &tool, BooleanOperation::Subtract, &BooleanOptions::default())
            .map_err(|error| {
                error.with_message(|message| format!("{OP}: the re-cut's subtract refused — {message}"))
            })?;
    }
    if let Some(tool) = unite(adding)? {
        cut = boolean_operation(&cut, &tool, BooleanOperation::Union, &BooleanOptions::default())
            .map_err(|error| {
                error.with_message(|message| format!("{OP}: the re-cut's union refused — {message}"))
            })?;
    }
    // A boss whose floor is carried out through the far side of the body is
    // left standing on nothing: the cut answers with a separate piece. That
    // is not an edit of this body, so it is refused by name.
    // Outer pieces, not shells: a cavity the cut opens up takes a shell away
    // as a post cut loose adds one. A shell bounds material where its signed
    // volume is positive.
    let pieces = |body: &BrepSolid| -> Result<usize, KernelRefusal> {
        let mut count = 0;
        for shell in &body.shells {
            let volume = crate::mass_properties::shell_signed_volume(shell)
                .map_err(|error| KernelRefusal::internal(KernelStage::Validate, "shell_volume", format!("{OP}: {error}")))?;
            if volume > 0.0 {
                count += 1;
            }
        }
        Ok(count)
    };
    let (before, after) = (pieces(solid)?, pieces(&cut)?);
    if after == 0 {
        return Err(KernelRefusal::ill_posed(
            KernelStage::Classify,
            "solid_vanishes",
            format!("{OP}: the motion takes away all of the body's material; refusing rather than returning nothing"),
        ));
    }
    if after > before {
        return Err(KernelRefusal::ill_posed(
            KernelStage::Classify,
            "island_cut_loose",
            format!(
                "{OP}: the motion carries the selection past the far side of the body and leaves \
                 {after} piece(s) where there was {before}: an island standing on the moved face is \
                 cut loose; refusing rather than returning a body in pieces"
            ),
        ));
    }
    Ok(restamp(cut, solid, &moved_set, &motion, tolerance))
}

/// Put back the fillets a re-cut filled in.
///
/// Where a turned plane misses a tangent fillet, the re-cut leaves the turned
/// face meeting the wall beyond it at a sharp edge. That edge is rounded again
/// at the fillet's radius and under its name, so the face re-meets its fillet.
/// A fillet that cannot be re-made stays filled in; the returned notes name
/// each one, with the reason, so the loss is never silent.
pub fn reblend_lost_fillets(original: &BrepSolid, moved: &[u64], mut body: BrepSolid) -> (BrepSolid, Vec<String>) {
    let tolerance = (solid_model_scale(original) * 1e-6).max(1e-9);
    let moved_set: HashSet<u64> = moved.iter().copied().collect();
    let faces: HashMap<u64, &FaceRecord> =
        original.shells.iter().flat_map(|shell| &shell.faces).map(|face| (face.id, face)).collect();
    let mut owners: HashMap<u64, Vec<u64>> = HashMap::default();
    for face in faces.values() {
        for coedge in face.loops.iter().flat_map(|wire| &wire.coedges) {
            owners.entry(coedge.edge_id).or_default().push(face.id);
        }
    }
    let across = |face: &FaceRecord| -> Vec<u64> {
        let mut found: Vec<u64> = face
            .loops
            .iter()
            .flat_map(|wire| &wire.coedges)
            .flat_map(|coedge| owners.get(&coedge.edge_id).into_iter().flatten().copied())
            .filter(|id| *id != face.id)
            .collect();
        found.sort_unstable();
        found.dedup();
        found
    };
    let mut notes = Vec::new();
    let mut ordered = moved.to_vec();
    ordered.sort_unstable();
    for id in ordered {
        let Some(&face) = faces.get(&id) else { continue };
        let Ok(plane) = plane_of_surface(&face.surface, tolerance * 10.0, OP) else { continue };
        for band_id in across(face) {
            let band = faces[&band_id];
            let Some(band_name) = band.name.clone() else { continue };
            if moved_set.contains(&band_id)
                || plane_of_surface(&band.surface, tolerance * 10.0, OP).is_ok()
                || !band_is_tangent_along_shared_edges(face, band, plane.normal)
                || body.shells.iter().flat_map(|shell| &shell.faces).any(|f| f.name.as_deref() == Some(&band_name))
            {
                continue;
            }
            // A constant radius is rolled again as it was. Any other band is
            // read as a rolling-ball fillet under a radius law and re-made
            // under that law (`blend_rebuild.rs`); one that reads as neither
            // is still a fillet this edit filled in, so it is named.
            let radius = super::face_move::ruled_revolution_carrier(&band.surface)
                .filter(|(_, rho0, rho1, _)| (rho0 - rho1).abs() <= tolerance)
                .map(|(_, rho0, _, _)| rho0);
            let (remade, radius_label) = match radius {
                Some(rho0) => (
                    across(band)
                        .into_iter()
                        .filter(|wall| *wall != id)
                        .find_map(|wall| {
                            let wall = faces[&wall];
                            let wall_plane = plane_of_surface(&wall.surface, tolerance * 10.0, OP).ok()?;
                            band_is_tangent_along_shared_edges(wall, band, wall_plane.normal).then_some(wall)
                        })
                        .ok_or_else(|| "the wall beyond it could not be read".to_string())
                        .and_then(|wall| sharp_edge_between(&body, face, wall))
                        .and_then(|edge| {
                            let rebuilt =
                                crate::fillet_edge(&body, edge, rho0, Some(&band_name)).map_err(|e| e.to_string())?;
                            let issues = rebuilt.validate();
                            if !issues.is_empty() {
                                return Err(format!("the new fillet is invalid: {issues:?}"));
                            }
                            // Checked one by one, so a fillet the acceptance would
                            // refuse costs that fillet and not the whole edit.
                            crate::accept_sound(rebuilt, "transformFace").map_err(|e| e.to_string())
                        }),
                    format!(" (radius {rho0})"),
                ),
                None => (
                    super::blend_rebuild::read_band_law(original, band_id)
                        .map_err(|reason| {
                            format!(
                                "it is neither a constant-radius fillet nor a rolling-ball fillet under a \
                                 radius law: {reason}"
                            )
                        })
                        .and_then(|law| super::blend_rebuild::remake_band(&body, &law, false, "transformFace")),
                    String::new(),
                ),
            };
            match remade {
                Ok(rebuilt) => {
                    body = rebuilt;
                    // A blend that ran round the old fillet has nothing to run
                    // round until it too is re-made; that is not built.
                    for beside in across(band) {
                        let beside = faces[&beside];
                        let Some(beside_name) = beside.name.as_deref() else { continue };
                        if !moved_set.contains(&beside.id)
                            && plane_of_surface(&beside.surface, tolerance * 10.0, OP).is_err()
                            && !body.shells.iter().flat_map(|shell| &shell.faces).any(|f| f.name.as_deref() == Some(beside_name))
                        {
                            notes.push(format!(
                                "transformFace: blend `{beside_name}`, which ran round fillet \
                                 `{band_name}`, was not re-made: the fillet was rebuilt at its radius \
                                 and the faces either side of that blend now meet over it"
                            ));
                        }
                    }
                }
                Err(reason) => notes.push(format!(
                    "transformFace: fillet `{band_name}`{radius_label} was lost: the moved face no \
                     longer reaches it, so it was filled in, and it could not be re-made ({reason})"
                )),
            }
        }
    }
    (body, notes)
}

/// The one edge of `body` between the faces named as `first` and `second`.
fn sharp_edge_between(body: &BrepSolid, first: &FaceRecord, second: &FaceRecord) -> Result<u64, String> {
    let edges_of = |face: &FaceRecord| -> Result<HashSet<u64>, String> {
        let name = face.name.as_deref().ok_or_else(|| format!("face {} has no name to find it by", face.id))?;
        Ok(body
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter(|f| f.name.as_deref() == Some(name))
            .flat_map(|f| f.loops.iter().flat_map(|wire| &wire.coedges).map(|coedge| coedge.edge_id))
            .collect())
    };
    let (a, b) = (edges_of(first)?, edges_of(second)?);
    let mut shared = a.intersection(&b).copied();
    match (shared.next(), shared.next()) {
        (Some(edge), None) => Ok(edge),
        _ => Err("no single sharp edge joins the turned face to the wall beyond it".to_string()),
    }
}

/// What bounds a turned face's wedge past the tangent band (a fillet) beside it.
struct TangentSurround {
    /// Outward planes `n̂·x ≤ o` of the planar faces reached across curved faces.
    planes: Vec<(Vec3, f64)>,
    /// How far behind the face a growing tool's inner wall must start.
    inner_wall_depth: f64,
}

/// Is `band` tangent to the planar `face` along the edges they share?
fn band_is_tangent_along_shared_edges(
    face: &FaceRecord,
    band: &FaceRecord,
    normal: Vec3,
) -> bool {
    let own: HashSet<u64> =
        face.loops.iter().flat_map(|wire| &wire.coedges).map(|coedge| coedge.edge_id).collect();
    let mut shared = 0usize;
    for coedge in band.loops.iter().flat_map(|wire| &wire.coedges) {
        if !own.contains(&coedge.edge_id) {
            continue;
        }
        let Ok([q0, q1]) = coedge.pcurve.domain() else {
            return false;
        };
        let Ok(uv) = coedge.pcurve.evaluate(0.5 * (q0 + q1)) else {
            return false;
        };
        let Ok(band_normal) = band.surface.normal(uv.x, uv.y) else {
            return false;
        };
        if band_normal.cross(normal).length() > 1e-4 {
            return false;
        }
        shared += 1;
    }
    shared > 0
}

/// The planar faces that close the region around a turned face's tangent bands:
/// every planar face reached from the bands through curved faces only.
///
/// A plane missing a fillet leaves no ruling to re-meet, so the growing side's
/// answer is the fillet filled in and the tilted face meeting the wall beyond
/// it. Those walls bound the tool, which is sound only where the material is
/// convex: every plane must hold every vertex of the region, or the tool could
/// fill a pocket the part really has.
fn tangent_surround(
    solid: &BrepSolid,
    face: &FaceRecord,
    normal: Vec3,
    offset: f64,
    bands: &HashSet<u64>,
    moved: &HashSet<u64>,
    tolerance: f64,
) -> Result<TangentSurround, KernelRefusal> {
    let mut owners: HashMap<u64, Vec<u64>> = HashMap::default();
    for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
        for coedge in other.loops.iter().flat_map(|wire| &wire.coedges) {
            owners.entry(coedge.edge_id).or_default().push(other.id);
        }
    }
    let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
    let points: HashMap<u64, Vec3> =
        solid.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
    let plane_band = tolerance.max(1e-9) * 10.0;

    let mut curved: HashSet<u64> = bands.clone();
    let mut planar: HashSet<u64> = HashSet::default();
    let mut stack: Vec<u64> = bands.iter().copied().collect();
    while let Some(id) = stack.pop() {
        let current = face_by_id(solid, id)?;
        for coedge in current.loops.iter().flat_map(|wire| &wire.coedges) {
            for &next in owners.get(&coedge.edge_id).into_iter().flatten() {
                if next == id || next == face.id || curved.contains(&next) || planar.contains(&next) {
                    continue;
                }
                if moved.contains(&next) {
                    return Err(KernelRefusal::unsupported(
                        KernelStage::Classify,
                        "curved_neighbour",
                        format!(
                            "{OP}: face {next} is also selected and borders the fillet beside face \
                             {}, so what bounds the tool past that fillet is itself moving; refusing",
                            face.id
                        ),
                    ));
                }
                let other = face_by_id(solid, next)?;
                if plane_of_surface(&other.surface, plane_band, OP).is_ok() {
                    planar.insert(next);
                } else {
                    curved.insert(next);
                    stack.push(next);
                }
            }
        }
    }

    let vertices_of = |id: u64| -> Result<Vec<Vec3>, KernelRefusal> {
        let mut found = Vec::new();
        for coedge in face_by_id(solid, id)?.loops.iter().flat_map(|wire| &wire.coedges) {
            if let Some(edge) = edges.get(&coedge.edge_id) {
                found.extend(points.get(&edge.start_vertex_id).copied());
                found.extend(points.get(&edge.end_vertex_id).copied());
            }
        }
        Ok(found)
    };
    let mut region: Vec<Vec3> = Vec::new();
    let mut depth = 0.0f64;
    for &id in &curved {
        for point in vertices_of(id)? {
            depth = depth.max(offset - normal.dot(point));
            region.push(point);
        }
    }
    let mut ordered: Vec<u64> = planar.iter().copied().collect();
    ordered.sort_unstable();
    for &id in &ordered {
        region.extend(vertices_of(id)?);
    }

    let mut planes = Vec::new();
    for &id in &ordered {
        let other = face_by_id(solid, id)?;
        let plane = plane_of_surface(&other.surface, plane_band, OP)
            .map_err(|error| KernelRefusal::unsupported(KernelStage::Classify, "curved_neighbour", error.to_string()))?;
        let outward = if other.same_sense { plane.normal } else { plane.normal.scale(-1.0) };
        let outward_offset = outward.dot(plane.origin);
        if let Some(point) = region.iter().find(|point| outward.dot(**point) - outward_offset > plane_band) {
            return Err(KernelRefusal::unsupported(
                KernelStage::Classify,
                "curved_neighbour",
                format!(
                    "{OP}: the part is not convex around the fillet beside face {} (face {id}{} has \
                     material on both sides, at {point:?}), so the wedge a turn adds there has no \
                     bound that keeps it out of the part's other features; refusing",
                    face.id,
                    named(other)
                ),
            ));
        }
        planes.push((outward, outward_offset));
    }
    Ok(TangentSurround { planes, inner_wall_depth: depth * 1.5 + tolerance })
}

/// Add a half-space unless an equal one (same normal, same offset within the
/// band) is already listed: two cell edges on one carrier — a bookkeeping split,
/// or an edge and the extension the reflex cut drew through it — must not put
/// two coincident faces on the polytope.
fn push_unique(spaces: &mut Vec<HalfSpace>, space: HalfSpace, tolerance: f64) {
    let band = tolerance.max(1e-9) * 10.0;
    if spaces.iter().any(|other| {
        other.normal.sub(space.normal).length() <= 1e-9 && (other.offset - space.offset).abs() <= band
    }) {
        return;
    }
    spaces.push(space);
}

/// What a cell's edge lies on: the carrier of the face across that edge (an
/// edge of the trim, or the extension of one the reflex cut drew), or the
/// hinge line a turn splits the face along.
#[derive(Clone, Copy, Debug, PartialEq)]
enum EdgeSource {
    Neighbour(u64),
    Hinge,
}

/// A 2-D frame on a moved face's carrier: `origin + x·u + y·v`, with
/// `u × v = n̂`, so counter-clockwise in `(x, y)` is counter-clockwise about
/// the OUTWARD normal.
#[derive(Clone, Copy, Debug)]
struct Frame {
    origin: Vec3,
    u: Vec3,
    v: Vec3,
}

impl Frame {
    fn new(origin: Vec3, normal: Vec3) -> Result<Self, String> {
        let u = normal.perpendicular()?.normalized()?;
        let v = normal.cross(u).normalized()?;
        Ok(Self { origin, u, v })
    }

    fn drop(&self, point: Vec3) -> [f64; 2] {
        let delta = point.sub(self.origin);
        [delta.dot(self.u), delta.dot(self.v)]
    }

    fn lift(&self, point: [f64; 2]) -> Vec3 {
        self.origin.add(self.u.scale(point[0])).add(self.v.scale(point[1]))
    }

    /// The line the carrier `n̂·x = o` and the carrier `m̂·x = p` meet in, in
    /// this frame, as `(point, unit direction)`; `None` when they are parallel.
    fn hinge(&self, normal: Vec3, offset: f64, moved: Vec3, moved_offset: f64) -> Option<Line2> {
        let direction = normal.cross(moved);
        if direction.length() <= 1e-12 {
            return None;
        }
        let direction = direction.normalized().ok()?;
        // A point on both planes: the frame's origin is on the first; slide it
        // within the first plane along the in-plane normal of the second.
        let across = direction.cross(normal).normalized().ok()?;
        let rate = moved.dot(across);
        if rate.abs() <= 1e-12 {
            return None;
        }
        let _ = offset;
        let point = self.origin.add(across.scale((moved_offset - moved.dot(self.origin)) / rate));
        let [px, py] = self.drop(point);
        let [qx, qy] = self.drop(point.add(direction));
        Some(Line2 {
            point: [px, py],
            direction: [qx - px, qy - py],
        })
    }

    /// The plane through the cell's `edge`, perpendicular to the face, as an
    /// outward half-space read from the cell's inside: the cell is on its `≤`
    /// side.
    fn edge_plane(&self, cell: &Cell, edge: usize) -> (Vec3, f64) {
        let a = cell.points[edge];
        let b = cell.points[(edge + 1) % cell.points.len()];
        // Counter-clockwise polygon: the outward normal of edge a→b is the
        // edge direction turned clockwise.
        let d = [b[0] - a[0], b[1] - a[1]];
        let length = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-300);
        let out = [d[1] / length, -d[0] / length];
        let normal = self.u.scale(out[0]).add(self.v.scale(out[1]));
        let normal = normal.normalized().unwrap_or(normal);
        (normal, normal.dot(self.lift(a)))
    }
}

/// A line in a `Frame`.
#[derive(Clone, Copy, Debug)]
struct Line2 {
    point: [f64; 2],
    direction: [f64; 2],
}

impl Line2 {
    /// Signed distance of `p` from the line: positive to the LEFT of the
    /// direction.
    fn side(&self, p: [f64; 2]) -> f64 {
        let d = self.direction;
        let length = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-300);
        (d[0] * (p[1] - self.point[1]) - d[1] * (p[0] - self.point[0])) / length
    }
}

/// A planar polygon with each edge's source: edge `k` runs from `points[k]`
/// to `points[k + 1]` (wrapping) and lies on `sources[k]`. Wound
/// counter-clockwise about the face's outward normal.
#[derive(Clone, Debug)]
struct Cell {
    points: Vec<[f64; 2]>,
    sources: Vec<EdgeSource>,
}

impl Cell {
    fn signed_area(&self) -> f64 {
        let n = self.points.len();
        (0..n)
            .map(|i| {
                let a = self.points[i];
                let b = self.points[(i + 1) % n];
                crate::polygon::area_term(a, b)
            })
            .sum::<f64>()
            * 0.5
    }

    /// The area centroid — strictly inside a convex cell.
    fn centroid(&self) -> [f64; 2] {
        let n = self.points.len();
        let area = self.signed_area();
        if area.abs() <= 1e-300 {
            let mean = self.points.iter().fold([0.0, 0.0], |s, p| [s[0] + p[0], s[1] + p[1]]);
            return [mean[0] / n as f64, mean[1] / n as f64];
        }
        let mut cx = 0.0;
        let mut cy = 0.0;
        for i in 0..n {
            let a = self.points[i];
            let b = self.points[(i + 1) % n];
            let w = crate::polygon::area_term(a, b);
            cx += (a[0] + b[0]) * w;
            cy += (a[1] + b[1]) * w;
        }
        [cx / (6.0 * area), cy / (6.0 * area)]
    }

    /// The first vertex where the boundary turns RIGHT (a reflex corner of a
    /// counter-clockwise polygon), or `None` for a convex one. A straight
    /// continuation (a bookkeeping split of one edge) is not a turn.
    fn reflex_vertex(&self, band: f64) -> Option<usize> {
        let n = self.points.len();
        (0..n).find(|&i| {
            let p = self.points[(i + n - 1) % n];
            let q = self.points[i];
            let r = self.points[(i + 1) % n];
            let a = [q[0] - p[0], q[1] - p[1]];
            let b = [r[0] - q[0], r[1] - q[1]];
            let la = (a[0] * a[0] + a[1] * a[1]).sqrt();
            let lb = (b[0] * b[0] + b[1] * b[1]).sqrt();
            if la <= band || lb <= band {
                return false;
            }
            // The turn's sine times the shorter edge: a right turn deeper than
            // the band.
            (a[0] * b[1] - a[1] * b[0]) / la.max(lb) < -band
        })
    }
}

/// The polygon a moved face's trim is, with its frame. `islands` are the
/// face's inner loops, each read as the polygon of the REGION it encloses
/// (wound counter-clockwise like the trim) in the same frame.
struct TrimPolygon {
    frame: Frame,
    points: Vec<[f64; 2]>,
    sources: Vec<EdgeSource>,
    islands: Vec<TrimPolygon>,
}

/// Read a moved face's trim as a polygon in its own frame: every loop of
/// straight edges, every edge shared with exactly one other face, which is
/// the edge's source. The loop enclosing the largest area is the outer trim
/// and every other loop an ISLAND (a hole through the face, or the foot of a
/// boss standing on it), whose walls bound the island's own tools
/// (`recut_moved_planes_rigid`). Refuses by name what it cannot read: a curved
/// edge (which a planar neighbour cannot produce) and an edge no other face
/// holds.
fn trim_polygon(
    solid: &BrepSolid,
    face: &FaceRecord,
    normal: Vec3,
    band: f64,
) -> Result<TrimPolygon, KernelRefusal> {
    if face.loops.is_empty() {
        return Err(KernelRefusal::unsupported(
            KernelStage::Classify,
            "thin_trim",
            format!("{OP}: face {}{} has no trim loop", face.id, named(face)),
        ));
    }
    let first = loop_polygon(solid, face, 0, normal, band, None)?;
    let mut loops = vec![first];
    for index in 1..face.loops.len() {
        let frame = loops[0].frame;
        loops.push(loop_polygon(solid, face, index, normal, band, Some(frame))?);
    }
    let area = |polygon: &TrimPolygon| {
        Cell { points: polygon.points.clone(), sources: polygon.sources.clone() }.signed_area().abs()
    };
    let outer = (0..loops.len())
        .max_by(|&i, &j| area(&loops[i]).total_cmp(&area(&loops[j])))
        .expect("a face has a loop");
    let mut polygon = loops.swap_remove(outer);
    polygon.islands = loops;
    Ok(polygon)
}

/// One loop of a moved face (`loop_index`) as a counter-clockwise polygon in
/// `frame` (or a frame of its own at its first corner), with each edge's
/// source; see [`trim_polygon`].
fn loop_polygon(
    solid: &BrepSolid,
    face: &FaceRecord,
    loop_index: usize,
    normal: Vec3,
    band: f64,
    frame: Option<Frame>,
) -> Result<TrimPolygon, KernelRefusal> {
    let id = face.id;
    let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
    let vertices: HashMap<u64, Vec3> =
        solid.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
    // The face across each edge of this face.
    let mut across: HashMap<u64, u64> = HashMap::default();
    for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
        if other.id == id {
            continue;
        }
        for coedge in other.loops.iter().flat_map(|wire| &wire.coedges) {
            across.entry(coedge.edge_id).or_insert(other.id);
        }
    }
    let mut points3: Vec<Vec3> = Vec::new();
    let mut sources: Vec<EdgeSource> = Vec::new();
    for coedge in &face.loops[loop_index].coedges {
        let edge = edges.get(&coedge.edge_id).ok_or_else(|| {
            KernelRefusal::input(
                KernelStage::Collect,
                "missing_edge",
                format!("{OP}: face {id} uses edge {} which the solid does not hold", coedge.edge_id),
            )
        })?;
        if edge.degenerate {
            continue;
        }
        let (start_id, end_id) = if coedge.forward {
            (edge.start_vertex_id, edge.end_vertex_id)
        } else {
            (edge.end_vertex_id, edge.start_vertex_id)
        };
        let start = *vertices.get(&start_id).ok_or_else(|| {
            KernelRefusal::input(
                KernelStage::Collect,
                "missing_vertex",
                format!("{OP}: edge {} starts at vertex {start_id}, which the solid does not hold", edge.id),
            )
        })?;
        let end = *vertices.get(&end_id).ok_or_else(|| {
            KernelRefusal::input(
                KernelStage::Collect,
                "missing_vertex",
                format!("{OP}: edge {} ends at vertex {end_id}, which the solid does not hold", edge.id),
            )
        })?;
        // Straight: the curve's midpoint is the chord's.
        let middle = edge
            .curve
            .evaluate(0.5 * (edge.t0 + edge.t1))
            .or_refuse(KernelStage::Classify, "evaluate")?;
        let chord_middle = start.add(end).scale(0.5);
        if middle.sub(chord_middle).length() > band.max(1e-9) * 100.0 {
            return Err(KernelRefusal::unsupported(
                KernelStage::Classify,
                "curved_edge",
                format!(
                    "{OP}: edge {} of face {id}{} is not straight (its midpoint is {:.3e} off its \
                     chord), so the trim is not a polygon this road can cut into cells",
                    edge.id,
                    named(face),
                    middle.sub(chord_middle).length()
                ),
            ));
        }
        let neighbour = *across.get(&edge.id).ok_or_else(|| {
            KernelRefusal::unsupported(
                KernelStage::Classify,
                "open_edge",
                format!(
                    "{OP}: edge {} of face {id}{} is held by no other face, so nothing bounds the \
                     tool there",
                    edge.id,
                    named(face)
                ),
            )
        })?;
        points3.push(start);
        sources.push(EdgeSource::Neighbour(neighbour));
    }
    if points3.len() < 3 {
        return Err(KernelRefusal::unsupported(
            KernelStage::Classify,
            "thin_trim",
            format!("{OP}: face {id}{} has fewer than three corners", named(face)),
        ));
    }
    let frame = match frame {
        Some(frame) => frame,
        None => Frame::new(points3[0], normal).map_err(|error| {
            KernelRefusal::internal(KernelStage::Classify, "frame", format!("{OP}: {error}"))
        })?,
    };
    let mut points: Vec<[f64; 2]> = points3.iter().map(|point| frame.drop(*point)).collect();
    let probe = Cell { points: points.clone(), sources: sources.clone() };
    if probe.signed_area() < 0.0 {
        // Wound clockwise about the outward normal: reverse, keeping each
        // edge's source with its edge.
        points.reverse();
        sources.reverse();
        sources.rotate_left(1);
        let _ = &mut points;
    }
    Ok(TrimPolygon { frame, points, sources, islands: Vec::new() })
}

/// `BREP_RECUT_TURNED_ISLANDS` (default on; `=0` restores): the re-cut road carries a face
/// with islands through a TURN as well as a translation, each island cut along
/// the hinge like the trim (the island block of `recut_moved_planes_rigid`);
/// off, a turned face with an island refuses `island_trim`.
fn turned_islands_enabled() -> bool {
    switch!(live "BREP_RECUT_TURNED_ISLANDS", true)
}

/// Cut a trim polygon into convex cells: first along its own reflex corners
/// (each cut extends the edge ARRIVING at the corner through the interior to
/// the boundary, so the new edge lies on that edge's own carrier), then, for
/// a turn, along the hinge wherever it crosses a cell. Cells thinner than the
/// band are dropped.
fn convex_cells(
    polygon: &TrimPolygon,
    hinge: Option<Line2>,
    band: f64,
    scale: f64,
) -> Result<Vec<Cell>, String> {
    let area_floor = (band * scale).max(1e-18);
    let mut pending = vec![Cell {
        points: polygon.points.clone(),
        sources: polygon.sources.clone(),
    }];
    let mut convex: Vec<Cell> = Vec::new();
    let mut rounds = 0usize;
    while let Some(cell) = pending.pop() {
        rounds += 1;
        if rounds > 256 {
            return Err("the reflex cut did not converge in 256 rounds".into());
        }
        let cell = dedupe(cell, band);
        if cell.points.len() < 3 || cell.signed_area().abs() <= area_floor {
            continue;
        }
        match cell.reflex_vertex(band) {
            None => convex.push(cell),
            Some(vertex) => {
                let (first, second) = split_at_reflex(&cell, vertex, band)?;
                pending.push(first);
                pending.push(second);
            }
        }
    }
    let Some(hinge) = hinge else { return Ok(convex) };
    let mut cells: Vec<Cell> = Vec::new();
    for cell in convex {
        let sides: Vec<f64> = cell.points.iter().map(|point| hinge.side(*point)).collect();
        let high = sides.iter().copied().fold(f64::MIN, f64::max);
        let low = sides.iter().copied().fold(f64::MAX, f64::min);
        if high > band && low < -band {
            for half in split_by_line(&cell, &sides, band) {
                let half = dedupe(half, band);
                if half.points.len() >= 3 && half.signed_area().abs() > area_floor {
                    cells.push(half);
                }
            }
        } else {
            cells.push(cell);
        }
    }
    Ok(cells)
}

/// Drop consecutive points closer than the band, keeping the source of the
/// edge that LEAVES the surviving point.
fn dedupe(cell: Cell, band: f64) -> Cell {
    let mut points: Vec<[f64; 2]> = Vec::new();
    let mut sources: Vec<EdgeSource> = Vec::new();
    for (point, source) in cell.points.iter().zip(&cell.sources) {
        if let Some(last) = points.last() {
            if (last[0] - point[0]).hypot(last[1] - point[1]) <= band {
                // The edge leaving the merged point is this one's.
                *sources.last_mut().expect("as many sources as points") = *source;
                continue;
            }
        }
        points.push(*point);
        sources.push(*source);
    }
    while points.len() >= 2 {
        let first = points[0];
        let last = points[points.len() - 1];
        if (last[0] - first[0]).hypot(last[1] - first[1]) <= band {
            points.pop();
            let source = sources.pop().expect("as many sources as points");
            let _ = source;
        } else {
            break;
        }
    }
    Cell { points, sources }
}

/// Cut `cell` at its reflex `vertex`: the edge arriving there is extended
/// through the interior to the first boundary edge it meets, and the polygon
/// is split along that segment. Both pieces keep every edge's source, and
/// the new edge takes the arriving edge's.
fn split_at_reflex(cell: &Cell, vertex: usize, band: f64) -> Result<(Cell, Cell), String> {
    let n = cell.points.len();
    // Rotate so the reflex vertex is index 0; the arriving edge is then n − 1.
    let points: Vec<[f64; 2]> = (0..n).map(|i| cell.points[(vertex + i) % n]).collect();
    let sources: Vec<EdgeSource> = (0..n).map(|i| cell.sources[(vertex + i) % n]).collect();
    let p0 = points[0];
    let prev = points[n - 1];
    let d = [p0[0] - prev[0], p0[1] - prev[1]];
    let length = (d[0] * d[0] + d[1] * d[1]).sqrt();
    if length <= band {
        return Err("a reflex corner with a zero-length arriving edge".into());
    }
    let d = [d[0] / length, d[1] / length];
    // The first edge the ray meets, not counting the two at the corner.
    let mut best: Option<(usize, f64, f64)> = None;
    for j in 1..(n - 1) {
        let a = points[j];
        let b = points[(j + 1) % n];
        let e = [b[0] - a[0], b[1] - a[1]];
        let denominator = d[0] * e[1] - d[1] * e[0];
        if denominator.abs() <= 1e-15 {
            continue;
        }
        let w = [a[0] - p0[0], a[1] - p0[1]];
        let t = (w[0] * e[1] - w[1] * e[0]) / denominator;
        let s = (w[0] * d[1] - w[1] * d[0]) / denominator;
        let e_length = (e[0] * e[0] + e[1] * e[1]).sqrt().max(1e-300);
        let s_band = band / e_length;
        if t <= band || s < -s_band || s > 1.0 + s_band {
            continue;
        }
        if best.map_or(true, |(_, best_t, _)| t < best_t) {
            best = Some((j, t, s.clamp(0.0, 1.0)));
        }
    }
    let Some((j, t, s)) = best else {
        return Err(format!("the extension of the edge arriving at corner {vertex} meets no boundary edge"));
    };
    let hit = [p0[0] + d[0] * t, p0[1] + d[1] * t];
    let a = points[j];
    let b = points[(j + 1) % n];
    let e_length = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt().max(1e-300);
    let at_a = s * e_length <= band;
    let at_b = (1.0 - s) * e_length <= band;
    let arriving = sources[n - 1];
    // First piece: P0 … Pj (, hit), closed back to P0 along the extension.
    let mut first_points: Vec<[f64; 2]> = points[0..=j].to_vec();
    let mut first_sources: Vec<EdgeSource> = sources[0..j].to_vec();
    if at_b {
        first_points.push(b);
        first_sources.push(sources[j]);
    } else if !at_a {
        first_points.push(hit);
        first_sources.push(sources[j]);
    }
    first_sources.push(arriving);
    // Second piece: (hit,) P(j+1) … P(n−1), closed back along the extension
    // through P0, which is a straight continuation and is dropped.
    let mut second_points: Vec<[f64; 2]> = Vec::new();
    let mut second_sources: Vec<EdgeSource> = Vec::new();
    if at_a {
        second_points.push(a);
        second_sources.push(sources[j]);
    } else if !at_b {
        second_points.push(hit);
        second_sources.push(sources[j]);
    }
    for k in (j + 1)..n {
        second_points.push(points[k]);
        second_sources.push(sources[k]);
    }
    // The last source is that of P(n−1) → P0 → hit: the arriving edge's.
    *second_sources.last_mut().expect("the second piece has an edge") = arriving;
    Ok((
        Cell { points: first_points, sources: first_sources },
        Cell { points: second_points, sources: second_sources },
    ))
}

/// Split a CONVEX cell by a line, given each vertex's signed side; the two
/// halves keep their edges' sources and the edges along the line are `Hinge`.
fn split_by_line(cell: &Cell, sides: &[f64], band: f64) -> [Cell; 2] {
    let n = cell.points.len();
    let mut positive = Cell { points: Vec::new(), sources: Vec::new() };
    let mut negative = Cell { points: Vec::new(), sources: Vec::new() };
    for j in 0..n {
        let p = cell.points[j];
        let q = cell.points[(j + 1) % n];
        let (fp, fq) = (sides[j], sides[(j + 1) % n]);
        let source = cell.sources[j];
        let p_on = fp.abs() <= band;
        let q_on = fq.abs() <= band;
        // P itself, to every side it is on. Only an on-line point's leaving
        // edge can run along the line, and only when Q is off that side. A
        // point strictly on a side keeps the edge's source even when the edge
        // crosses: the piece from P to the crossing is still that edge.
        if fp > band || p_on {
            positive.points.push(p);
            positive.sources.push(if !p_on || fq > band || q_on { source } else { EdgeSource::Hinge });
        }
        if fp < -band || p_on {
            negative.points.push(p);
            negative.sources.push(if !p_on || fq < -band || q_on { source } else { EdgeSource::Hinge });
        }
        // A strict crossing: the crossing point goes to both sides.
        if (fp > band && fq < -band) || (fp < -band && fq > band) {
            let t = fp / (fp - fq);
            let x = [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t];
            if fp > band {
                positive.points.push(x);
                positive.sources.push(EdgeSource::Hinge);
                negative.points.push(x);
                negative.sources.push(source);
            } else {
                negative.points.push(x);
                negative.sources.push(EdgeSource::Hinge);
                positive.points.push(x);
                positive.sources.push(source);
            }
        }
    }
    [positive, negative]
}

/// A TURNED cell must move one way only. The wedge on the other side of the
/// carriers' common line — the same bounds, the carrier pair swapped — is the
/// material the cell would carry the other way; any corner it has further than
/// the band from BOTH carriers means that wedge has volume inside the cell's
/// bounds, and the tool this road builds would leave it untouched. A cell the
/// hinge split left on one side of the hinge has that hinge among its bounds,
/// so the other wedge is squeezed onto the line and reads zero.
fn one_way_only(
    id: u64,
    clip: &[HalfSpace],
    sides: &[HalfSpace],
    other: [HalfSpace; 2],
    tolerance: f64,
    name: impl Fn() -> String,
) -> Result<(), KernelRefusal> {
    let band = tolerance.max(1e-9) * 10.0;
    let spaces: Vec<HalfSpace> = clip.iter().chain(sides).chain(&other).copied().collect();
    let mut depth = 0.0f64;
    for a in 0..spaces.len() {
        for b in (a + 1)..spaces.len() {
            for c in (b + 1)..spaces.len() {
                let Some(point) = three_plane_point(&spaces[a], &spaces[b], &spaces[c]) else {
                    continue;
                };
                if spaces
                    .iter()
                    .any(|space| space.normal.dot(point) - space.offset > band)
                {
                    continue;
                }
                // How far inside the two carriers this corner is.
                let inside = other
                    .iter()
                    .map(|space| space.offset - space.normal.dot(point))
                    .fold(0.0f64, f64::max);
                depth = depth.max(inside);
            }
        }
    }
    if depth > band * 1e3 {
        return Err(KernelRefusal::ill_posed(
            KernelStage::Classify,
            "one_way_only",
            format!(
                "{OP}: the motion turns face {id}{} so that the line its old and new carriers meet \
                 in crosses its own bounds — part of the face moves into the body and part out of it \
                 (the other wedge reaches {depth:.3e} past them), so one tool would add material \
                 where the other takes it away; refusing rather than choosing",
                name()
            ),
        ));
    }
    Ok(())
}

/// The one way this road could return a plausible WRONG body, closed.
///
/// A cell's tool is the INTERSECTION of the half-spaces its edges state, and
/// that intersection is the cell only while the cell IS the region they
/// enclose — true of every convex polygon, and of nothing reflex. Measured,
/// before the reflex cut existed, on an L pocket whose arms are
/// `x[5,15]×y[5,10]` and `x[5,10]×y[10,15]` in a `20×20×10` block: the
/// intersection of the L's six bounds is its CONVEX CORE `x[5,10]×y[5,10]`, the
/// floor pushed out through the bottom built **16F 39E 25V, 3600** where the
/// through-L is **3250**, and `validate()` was clean, the scan was clean, no
/// closed form existed downstream and nothing refused. The reflex cut is what
/// makes every cell convex; this reads each cell's corners and edge midpoints
/// against its bounds at their HOME positions so that a cell the cut left
/// reflex refuses by name instead of cutting its core.
fn cell_is_its_bounds(
    face: &FaceRecord,
    cell: &Cell,
    frame: &Frame,
    at_home: &[HalfSpace],
    scale: f64,
) -> Result<(), KernelRefusal> {
    // The cell's boundary lies ON these carriers, so the reading is an
    // equality and the band only has to absorb the residual a built body
    // carries. Every violation this is here to catch is of the order of the
    // feature's own size.
    let band = (scale * 1e-4).max(1e-6);
    let n = cell.points.len();
    let mut worst = 0.0f64;
    for i in 0..n {
        let a = cell.points[i];
        let b = cell.points[(i + 1) % n];
        for point in [a, [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]] {
            let point = frame.lift(point);
            for space in at_home {
                worst = worst.max(space.normal.dot(point) - space.offset);
            }
        }
    }
    if worst > band {
        return Err(KernelRefusal::unsupported(
            KernelStage::Classify,
            "reflex_trim",
            format!(
                "{OP}: face {}{} has a boundary point {worst:.3e} outside one of its own \
                 bounding carriers, so its trim is not the region its bounding carriers \
                 enclose — their intersection is the trim's CONVEX CORE, and the tool this \
                 road would build is that core rather than all the material the motion \
                 moves. Refusing rather than cutting some of it",
                face.id,
                named(face)
            ),
        ));
    }
    Ok(())
}


fn face_by_id(solid: &BrepSolid, id: u64) -> Result<&FaceRecord, KernelRefusal> {
    solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| face.id == id)
        .ok_or_else(|| {
            KernelRefusal::input(
                KernelStage::Collect,
                "face_id",
                format!("{OP}: no face with id {id} on this solid"),
            )
        })
}

fn named(face: &FaceRecord) -> String {
    face.name
        .as_ref()
        .map(|name| format!(" '{name}'"))
        .unwrap_or_default()
}

/// Every face that shares an edge with `id`.

/// The body's axis-aligned bounds, from its vertices.
fn solid_bounds(solid: &BrepSolid) -> Result<(Vec3, Vec3), KernelRefusal> {
    if solid.vertices.is_empty() {
        return Err(KernelRefusal::input(
            KernelStage::Collect,
            "empty_solid",
            format!("{OP}: the solid has no vertices to bound"),
        ));
    }
    let mut low = Vec3::new(f64::MAX, f64::MAX, f64::MAX);
    let mut high = Vec3::new(f64::MIN, f64::MIN, f64::MIN);
    for vertex in &solid.vertices {
        low = Vec3::new(
            low.x.min(vertex.point.x),
            low.y.min(vertex.point.y),
            low.z.min(vertex.point.z),
        );
        high = Vec3::new(
            high.x.max(vertex.point.x),
            high.y.max(vertex.point.y),
            high.z.max(vertex.point.z),
        );
    }
    Ok((low, high))
}

/// Six half-spaces around `bounds`, grown by `margin` on every side.
fn box_half_spaces((low, high): (Vec3, Vec3), margin: f64) -> Vec<HalfSpace> {
    let low = Vec3::new(low.x - margin, low.y - margin, low.z - margin);
    let high = Vec3::new(high.x + margin, high.y + margin, high.z + margin);
    vec![
        HalfSpace { normal: Vec3::new(1.0, 0.0, 0.0), offset: high.x },
        HalfSpace { normal: Vec3::new(-1.0, 0.0, 0.0), offset: -low.x },
        HalfSpace { normal: Vec3::new(0.0, 1.0, 0.0), offset: high.y },
        HalfSpace { normal: Vec3::new(0.0, -1.0, 0.0), offset: -low.y },
        HalfSpace { normal: Vec3::new(0.0, 0.0, 1.0), offset: high.z },
        HalfSpace { normal: Vec3::new(0.0, 0.0, -1.0), offset: -low.z },
    ]
}

/// The bounded convex polytope a set of half-spaces encloses, as a solid.
///
/// The vertices are every triple of half-spaces' common point that satisfies
/// all of them; the faces are one per half-space that carries three or more of
/// those vertices, wound so the face normal is the half-space's own — which is
/// outward, because the polytope is on the `≤` side of every one. A half-space
/// that carries fewer than three is redundant and contributes no face.
///
/// `inside` is a point the polytope must contain; it is what makes an empty or
/// degenerate intersection a refusal rather than a body nobody asked for.
pub(super) fn convex_solid(
    spaces: &[HalfSpace],
    inside: Vec3,
    tolerance: f64,
) -> Result<BrepSolid, String> {
    let band = tolerance.max(1e-9) * 10.0;
    for space in spaces {
        if space.normal.dot(inside) - space.offset > -band {
            return Err(format!(
                "the seat point is not strictly inside the half-space set (it is {:.3e} past one \
                 of them), so the slab and its bounds enclose nothing",
                space.normal.dot(inside) - space.offset
            ));
        }
    }
    // Corners: every triple's common point that every half-space admits.
    let mut corners: Vec<Vec3> = Vec::new();
    for a in 0..spaces.len() {
        for b in (a + 1)..spaces.len() {
            for c in (b + 1)..spaces.len() {
                let Some(point) = three_plane_point(&spaces[a], &spaces[b], &spaces[c]) else {
                    continue;
                };
                if spaces
                    .iter()
                    .any(|space| space.normal.dot(point) - space.offset > band)
                {
                    continue;
                }
                if corners
                    .iter()
                    .any(|other| other.sub(point).length() <= band)
                {
                    continue;
                }
                corners.push(point);
            }
        }
    }
    if corners.len() < 4 {
        return Err(format!(
            "the half-space set has {} corner(s), which is not a bounded volume",
            corners.len()
        ));
    }

    let vertices: Vec<VertexRecord> = corners
        .iter()
        .enumerate()
        .map(|(index, point)| VertexRecord { id: index as u64 + 1, point: *point })
        .collect();
    let mut edges: Vec<EdgeRecord> = Vec::new();
    let mut edge_index: HashMap<(usize, usize), u64> = HashMap::default();
    let mut faces: Vec<FaceRecord> = Vec::new();
    let mut next_id = 1000u64;

    for space in spaces {
        let mut on: Vec<usize> = (0..corners.len())
            .filter(|&index| (space.normal.dot(corners[index]) - space.offset).abs() <= band)
            .collect();
        if on.len() < 3 {
            continue;
        }
        // Wind them about the face's own centroid, counter-clockwise as seen
        // from OUTSIDE (the `+normal` side), which is the sense a solid's face
        // needs.
        let centroid = on
            .iter()
            .fold(Vec3::new(0.0, 0.0, 0.0), |sum, &index| sum.add(corners[index]))
            .scale(1.0 / on.len() as f64);
        let u_dir = corners[on[0]].sub(centroid).normalized()?;
        let v_dir = space.normal.cross(u_dir).normalized()?;
        on.sort_by(|&a, &b| {
            let angle = |index: usize| {
                let delta = corners[index].sub(centroid);
                delta.dot(v_dir).atan2(delta.dot(u_dir))
            };
            angle(a).total_cmp(&angle(b))
        });
        faces.push(polygon_face(
            &vertices,
            &on,
            space.normal,
            &mut edges,
            &mut edge_index,
            &mut next_id,
        )?);
    }
    if faces.len() < 4 {
        return Err(format!(
            "the half-space set produced {} face(s), which does not close a volume",
            faces.len()
        ));
    }

    let shell_id = next_id + 1;
    let solid_id = next_id + 2;
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id: solid_id,
        vertices,
        edges,
        shells: vec![ShellRecord { id: shell_id, faces }],
        genus: 0,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(format!("the tool polytope did not validate: {issues:?}"));
    }
    Ok(solid)
}

/// Where three half-spaces' carriers meet, or `None` when they do not meet in
/// a point.
pub(super) fn three_plane_point(a: &HalfSpace, b: &HalfSpace, c: &HalfSpace) -> Option<Vec3> {
    let cross = b.normal.cross(c.normal);
    let determinant = a.normal.dot(cross);
    if determinant.abs() <= 1e-9 {
        return None;
    }
    let point = cross
        .scale(a.offset)
        .add(c.normal.cross(a.normal).scale(b.offset))
        .add(a.normal.cross(b.normal).scale(c.offset))
        .scale(1.0 / determinant);
    Some(point)
}

/// One planar face of the polytope, from corners already wound about `normal`.
/// Shared edges are minted once and reused, so the shell closes.
fn polygon_face(
    vertices: &[VertexRecord],
    corners: &[usize],
    normal: Vec3,
    edges: &mut Vec<EdgeRecord>,
    edge_index: &mut HashMap<(usize, usize), u64>,
    next_id: &mut u64,
) -> Result<FaceRecord, String> {
    let origin_point = vertices[corners[0]].point;
    let u_dir = vertices[corners[1]]
        .point
        .sub(origin_point)
        .normalized()?;
    let v_dir = normal.cross(u_dir).normalized()?;
    let mut low_u = f64::MAX;
    let mut low_v = f64::MAX;
    let mut high_u = f64::MIN;
    let mut high_v = f64::MIN;
    let projected: Vec<(f64, f64)> = corners
        .iter()
        .map(|&index| {
            let delta = vertices[index].point.sub(origin_point);
            let (u, v) = (delta.dot(u_dir), delta.dot(v_dir));
            low_u = low_u.min(u);
            low_v = low_v.min(v);
            high_u = high_u.max(u);
            high_v = high_v.max(v);
            (u, v)
        })
        .collect();
    let plane_origin = origin_point.add(u_dir.scale(low_u)).add(v_dir.scale(low_v));
    let surface = make_plane(
        plane_origin,
        u_dir,
        v_dir,
        high_u - low_u,
        high_v - low_v,
    )?;

    let mut coedges: Vec<CoedgeRecord> = Vec::with_capacity(corners.len());
    for index in 0..corners.len() {
        let start = corners[index];
        let end = corners[(index + 1) % corners.len()];
        let key = if start < end { (start, end) } else { (end, start) };
        let edge_id = match edge_index.get(&key) {
            Some(id) => *id,
            None => {
                let id = *next_id;
                *next_id += 1;
                edges.push(EdgeRecord {
                    id,
                    curve: make_line(vertices[key.0].point, vertices[key.1].point)?,
                    t0: 0.0,
                    t1: 1.0,
                    start_vertex_id: vertices[key.0].id,
                    end_vertex_id: vertices[key.1].id,
                    degenerate: false,
                    name: None,
                });
                edge_index.insert(key, id);
                id
            }
        };
        let start_uv = projected[index];
        let end_uv = projected[(index + 1) % corners.len()];
        coedges.push(CoedgeRecord {
            id: *next_id,
            edge_id,
            forward: vertices[start].id
                == edges
                    .iter()
                    .find(|edge| edge.id == edge_id)
                    .expect("the edge was just minted")
                    .start_vertex_id,
            pcurve: parameter_line(
                start_uv.0 - low_u,
                start_uv.1 - low_v,
                end_uv.0 - low_u,
                end_uv.1 - low_v,
            )?,
        });
        *next_id += 1;
    }
    let loop_id = *next_id;
    *next_id += 1;
    let face_id = *next_id;
    *next_id += 1;
    Ok(FaceRecord {
        id: face_id,
        surface,
        same_sense: true,
        loops: vec![LoopRecord { id: loop_id, coedges }],
        name: None,
    })
}

/// Give the re-cut body the ORIGINAL body's face names back.
///
/// The boolean mints its own faces, so a collect would lose every name the
/// cut touched. A result face whose carrier is an original face's carrier —
/// at its MOVED position, for a face in the selection — is that face, and takes
/// its name; a carrier that comes back as two faces gives the second `name_1`,
/// the spelling the crossing repair's own split already uses. A name whose
/// carrier is no longer on the body is simply not stamped: the face is gone,
/// which for this road is an answer rather than a loss.
fn restamp(
    mut cut: BrepSolid,
    original: &BrepSolid,
    moved: &HashSet<u64>,
    motion: &Motion,
    tolerance: f64,
) -> BrepSolid {
    let band = tolerance.max(1e-9) * 1e3;
    // Every original name, with the plane it should be found on.
    let mut wanted: Vec<(String, Vec3, f64)> = Vec::new();
    for face in original.shells.iter().flat_map(|shell| &shell.faces) {
        let Some(name) = face.name.clone() else { continue };
        let Ok(plane) = plane_of_surface(&face.surface, band, OP) else {
            continue;
        };
        let normal = if face.same_sense {
            plane.normal
        } else {
            plane.normal.scale(-1.0)
        };
        let (normal, offset) = if moved.contains(&face.id) {
            motion.plane(normal, normal.dot(plane.origin))
        } else {
            (normal, normal.dot(plane.origin))
        };
        wanted.push((name, normal, offset));
    }
    let taken: HashSet<String> = cut
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .filter_map(|face| face.name.clone())
        .collect();
    let mut used: HashMap<String, usize> = HashMap::default();
    for name in &taken {
        used.insert(name.clone(), 1);
    }
    for shell in &mut cut.shells {
        for face in &mut shell.faces {
            if face.name.is_some() {
                continue;
            }
            let Ok(plane) = plane_of_surface(&face.surface, band, OP) else {
                continue;
            };
            let normal = if face.same_sense {
                plane.normal
            } else {
                plane.normal.scale(-1.0)
            };
            let offset = normal.dot(plane.origin);
            let Some((name, _, _)) = wanted.iter().find(|(_, other, other_offset)| {
                other.sub(normal).length() <= 1e-9 && (other_offset - offset).abs() <= band
            }) else {
                continue;
            };
            let count = used.entry(name.clone()).or_insert(0);
            *count += 1;
            face.name = Some(if *count == 1 {
                name.clone()
            } else {
                format!("{name}_{}", *count - 1)
            });
        }
    }
    cut
}