BREP_construction 0.34.1

Rust B-rep CAD kernel (next.BREP.io): solid construction: extrusions, revolutions, sweeps and lofts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
//! `BREP_SWEEP_TUBE_BOOLEAN` (default off): the boolean of two swept rings
//! (two `Tube`s), cut by each other's exact membership rather than by
//! surface/surface intersection.
//!
//! A point lies in a swept ring where some pose of its core circle comes
//! within r of it; the least distance over the motion (`depth`) is a sign
//! certified by the motion's speed bound. Each operand's faces, as its own
//! sweep built them, are cut along the zero set of the other's depth − r:
//! - kept outside the other for a union;
//! - kept inside it for an intersection;
//! - the first's kept outside and the second's kept inside (turned about) for
//!   a difference.
//!
//! Where both motions place the ring alike (the shared pose), the two
//! boundaries touch at the points where both grazing curves on that torus
//! cross. There the zero set crosses itself (an X, the gap quadratic about
//! the point), and those points are made vertices outright.
//!
//! Operands are recognised by a record the tumbled sweep leaves (`record`):
//! the body's digest with its tube. A body that has been transformed or edited
//! has another digest, so it is a miss, and the general boolean runs.
use super::Tube;
use crate::{BooleanOperation, BrepSolid, KernelRefusal, KernelStage, Vec3};
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Mutex;

/// The switch, default off.
pub fn tube_boolean_on() -> bool {
    crate::switch!("BREP_SWEEP_TUBE_BOOLEAN", false)
}


fn refuse(what: &'static str, message: String) -> KernelRefusal {
    KernelRefusal::unsupported(KernelStage::Classify, what, format!("tube boolean: {message}"))
}

/// The bodies the tumbled sweep built from rings, by digest (bounded: the
/// oldest records go first past `KEEP`).
static RECORDS: Mutex<Vec<(u64, Tube)>> = Mutex::new(Vec::new());
const KEEP: usize = 64;

/// A digest of the body's topology and vertex positions (bit-exact): a clone
/// has the same one; a transformed or edited body has another.
fn digest(solid: &BrepSolid) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    let faces: usize = solid.shells.iter().map(|shell| shell.faces.len()).sum();
    (solid.shells.len(), faces, solid.edges.len(), solid.vertices.len()).hash(&mut hasher);
    for vertex in &solid.vertices {
        [vertex.point.x.to_bits(), vertex.point.y.to_bits(), vertex.point.z.to_bits()].hash(&mut hasher);
    }
    let controls = |hasher: &mut std::collections::hash_map::DefaultHasher, points: &mut dyn Iterator<Item = &crate::Vec4>| {
        for control in points {
            [control.x.to_bits(), control.y.to_bits(), control.z.to_bits(), control.w.to_bits()].hash(hasher);
        }
    };
    for edge in &solid.edges {
        controls(&mut hasher, &mut edge.curve.control_points.iter());
    }
    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
        face.same_sense.hash(&mut hasher);
        controls(&mut hasher, &mut face.surface.control_points.iter().flatten());
    }
    hasher.finish()
}

/// Record that `solid` is the sweep of `tube`, and register the route.
pub fn record(solid: &BrepSolid, tube: Tube) {
    crate::register_dedicated_boolean(route);
    let key = digest(solid);
    if let Ok(mut records) = RECORDS.lock() {
        records.retain(|(known, _)| *known != key);
        records.push((key, tube));
        let excess = records.len().saturating_sub(KEEP);
        records.drain(..excess);
    }
}

fn recorded(solid: &BrepSolid) -> Option<Tube> {
    let key = digest(solid);
    RECORDS.lock().ok()?.iter().rev().find(|(known, _)| *known == key).map(|(_, tube)| *tube)
}

/// The dedicated route: `None` unless both operands are recorded tubes.
fn route(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<Result<BrepSolid, KernelRefusal>> {
    if !tube_boolean_on() {
        return None;
    }
    let (a, b) = (recorded(first)?, recorded(second)?);
    // Two pieces of one motion (a sweep's halves joined) share whole stretches
    // of poses: the general boolean joins them.
    if same_motion(&a, &b) {
        return None;
    }
    // A pair refused here once is not tried again: the general boolean's own
    // retries call back in with the same operands.
    let key = (digest(first), digest(second), operation as u8);
    if REFUSED.with(|refused| refused.borrow().contains(&key)) {
        return None;
    }
    let answer = tube_boolean(&a, first, &b, second, operation);
    if let Err(refusal) = &answer {
        if std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok() {
            eprintln!("tube boolean: refused: {}", refusal.message);
        }
        REFUSED.with(|refused| refused.borrow_mut().push(key));
    }
    Some(answer)
}

thread_local! {
    static REFUSED: std::cell::RefCell<Vec<(u64, u64, u8)>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// The same ring under the same motion (bit for bit): pieces of one sweep.
fn same_motion(a: &Tube, b: &Tube) -> bool {
    let bits = |v: crate::Vec3| [v.x.to_bits(), v.y.to_bits(), v.z.to_bits()];
    let ring = |t: &Tube| (bits(t.centre), bits(t.axis), t.major.to_bits(), t.minor.to_bits());
    let motion = |t: &Tube| (t.motion.points.map(bits), t.motion.directions.map(bits), t.motion.rates.map(f64::to_bits));
    ring(a) == ring(b) && motion(a) == motion(b)
}

/// The boolean of `first` (the sweep of `a`) and `second` (the sweep of `b`).
pub fn tube_boolean(a: &Tube, first: &BrepSolid, b: &Tube, second: &BrepSolid, operation: BooleanOperation) -> Result<BrepSolid, KernelRefusal> {
    let debug = std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok();
    let started = web_time::Instant::now();
    let lap = |what: &str| {
        if debug {
            eprintln!("tube boolean: {what} by {:.2} s", started.elapsed().as_secs_f64());
        }
    };
    let crossing = crossing(a, b).map_err(|why| refuse("tube_boolean_trace", why))?;
    lap("crossing traced");
    let imprint = sections(a, first, b, second, &crossing).map_err(|why| refuse("tube_boolean_sections", why))?;
    lap("sections made");
    let solid = assemble_by_membership(a, first, b, second, &imprint, operation);
    lap("assembled");
    solid
}

/// One tube's membership: the least distance from a point to its core circle
/// over the motion, with the time that reaches it.
#[derive(Clone, Copy)]
pub struct Member<'a> {
    pub tube: &'a Tube,
}

impl Member<'_> {
    /// The ring's size (major + minor): every tolerance is a fraction of it.
    pub fn size(&self) -> f64 {
        self.tube.major + self.tube.minor
    }

    /// (depth, time) over the whole motion. The distance is read at 160
    /// poses; each of the four least local minima is polished by golden
    /// section within its two neighbouring intervals (its basin). Every other
    /// interval is cleared by the motion's speed bound against the least
    /// found less 1e-9 of the size, halving where it is not; a lower pose
    /// found so becomes a minimum and is polished too. A speed bound alone
    /// cannot certify a quadratic least finely (the intervals it must split
    /// grow as 1/√width), so each basin is read by its own polish.
    pub fn at(&self, q: Vec3) -> (f64, f64) {
        ORACLE_CALLS.with(|c| c.set(c.get() + 1));
        let tube = self.tube;
        let (from, to) = (tube.from, tube.to);
        let range = to - from;
        let count = 160usize;
        let h = range / count as f64;
        let time = |k: usize| from + h * k as f64;
        let values: Vec<f64> = (0..=count).map(|k| reach_of(tube, q, time(k))).collect();
        let polish = |lo: f64, hi: f64| -> (f64, f64) {
            // Newton on the derivative by central differences, kept in the
            // bracket; golden section where it would leave it or stalls.
            let delta = 1e-6 * range;
            let mut t = 0.5 * (lo + hi);
            let mut newton = None;
            for _ in 0..12 {
                let (f0, fp, fm) = (reach_of(tube, q, t), reach_of(tube, q, t + delta), reach_of(tube, q, t - delta));
                let (d1, d2) = ((fp - fm) / (2.0 * delta), (fp - 2.0 * f0 + fm) / (delta * delta));
                if !(d2 > 0.0) {
                    break;
                }
                let next = t - d1 / d2;
                if !(next > lo && next < hi) {
                    break;
                }
                if (next - t).abs() <= 1e-13 * range {
                    newton = Some((reach_of(tube, q, next), next));
                    break;
                }
                t = next;
            }
            if let Some(found) = newton {
                return found;
            }
            let ratio = 0.5 * (5f64.sqrt() - 1.0);
            let (mut lo, mut hi) = (lo, hi);
            let (mut c, mut d) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo));
            let (mut fc, mut fd) = (reach_of(tube, q, c), reach_of(tube, q, d));
            while hi - lo > 1e-15 * range {
                if fc < fd {
                    hi = d;
                    d = c;
                    fd = fc;
                    c = hi - ratio * (hi - lo);
                    fc = reach_of(tube, q, c);
                } else {
                    lo = c;
                    c = d;
                    fc = fd;
                    d = lo + ratio * (hi - lo);
                    fd = reach_of(tube, q, d);
                }
            }
            if fc < fd { (fc, c) } else { (fd, d) }
        };
        let mut minima: Vec<usize> = (0..=count).filter(|&k| (k == 0 || values[k] <= values[k - 1]) && (k == count || values[k] <= values[k + 1])).collect();
        minima.sort_by(|&x, &y| values[x].total_cmp(&values[y]));
        minima.truncate(4);
        let mut best = (f64::INFINITY, from);
        let mut basins: Vec<(f64, f64)> = Vec::new();
        for &k in &minima {
            let (lo, hi) = (time(k.saturating_sub(1)), time((k + 1).min(count)));
            basins.push((lo, hi));
            let (value, t) = polish(lo, hi);
            for (v, t) in [(value, t), (values[k], time(k))] {
                if v < best.0 {
                    best = (v, t);
                }
            }
        }
        // Clear the rest by the speed bound.
        let speed = tube.reach_speed(q);
        // (A pose within this of the least found is a near tie, which the
        // polished basins already read; deeper ones the bound must clear.)
        let tolerance = 1e-6 * self.size();
        let mut stack: Vec<(f64, f64, f64, f64, usize)> = (0..count)
            .filter(|&k| !basins.iter().any(|&(lo, hi)| time(k) >= lo && time(k + 1) <= hi))
            .map(|k| (time(k), time(k + 1), values[k], values[k + 1], 0))
            .collect();
        while let Some((a, b, fa, fb, level)) = stack.pop() {
            if fa.min(fb) - speed * (b - a) * 0.5 >= best.0 - tolerance {
                continue;
            }
            if level >= 24 {
                // a basin finer than the samples: polish it
                let (value, t) = polish(a, b);
                if value < best.0 {
                    best = (value, t);
                }
                continue;
            }
            let m = 0.5 * (a + b);
            let fm = reach_of(tube, q, m);
            if fm < best.0 - tolerance && fm < fa && fm < fb {
                let (value, t) = polish(a, b);
                if value < best.0 {
                    best = (value, t);
                }
            }
            stack.push((a, m, fa, fm, level + 1));
            stack.push((m, b, fm, fb, level + 1));
        }
        (best.0, best.1)
    }

    /// The distance's local least near time `guess` (the sheet of the
    /// boundary that time's pose gives, continued across a crease): golden
    /// section in a bracket about the guess, moved while the least sits on
    /// its edge.
    pub fn near(&self, q: Vec3, guess: f64) -> (f64, f64) {
        let tube = self.tube;
        let range = tube.to - tube.from;
        let w = 2e-3 * range;
        let mut centre = guess.clamp(tube.from, tube.to);
        let ratio = 0.5 * (5f64.sqrt() - 1.0);
        let mut best = (reach_of(tube, q, centre), centre);
        for _ in 0..20 {
            let (mut lo, mut hi) = ((centre - w).max(tube.from), (centre + w).min(tube.to));
            let (bracket_lo, bracket_hi) = (lo, hi);
            let (mut c, mut d) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo));
            let (mut fc, mut fd) = (reach_of(tube, q, c), reach_of(tube, q, d));
            while hi - lo > 1e-15 * range {
                if fc < fd {
                    hi = d;
                    d = c;
                    fd = fc;
                    c = hi - ratio * (hi - lo);
                    fc = reach_of(tube, q, c);
                } else {
                    lo = c;
                    c = d;
                    fc = fd;
                    d = lo + ratio * (hi - lo);
                    fd = reach_of(tube, q, d);
                }
            }
            best = if fc < fd { (fc, c) } else { (fd, d) };
            let at_edge = (best.1 - bracket_lo < 1e-3 * w && bracket_lo > tube.from) || (bracket_hi - best.1 < 1e-3 * w && bracket_hi < tube.to);
            if !at_edge {
                break;
            }
            centre = best.1;
        }
        best
    }

    /// The gradient of the depth at q where time `t` reaches it: the unit
    /// vector from the nearest point of the core circle at that pose.
    pub fn gradient(&self, q: Vec3, t: f64) -> Vec3 {
        let tube = self.tube;
        let pose = tube.motion.pose(t);
        let local = pose.invert(q).sub(tube.centre);
        let up = local.dot(tube.axis);
        let radial = local.sub(tube.axis.scale(up));
        let length = radial.length();
        let nearest = if length > 0.0 { radial.scale(tube.major / length) } else { tube.x.scale(tube.major) };
        let away = local.sub(nearest);
        let away = away.scale(1.0 / away.length().max(1e-300));
        pose.rotate(away)
    }
}

thread_local! {
    static ORACLE_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    static REACH_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

fn reach_of(tube: &Tube, q: Vec3, t: f64) -> f64 {
    REACH_CALLS.with(|c| c.set(c.get() + 1));
    tube.reach(q, t)
}

/// (global depth reads, distance reads) on this thread so far.
pub fn oracle_counts() -> (u64, u64) {
    (ORACLE_CALLS.with(|c| c.get()), REACH_CALLS.with(|c| c.get()))
}

/// A point of the crossing (both depths r), with the times reaching it.
#[derive(Clone, Copy, Debug)]
pub struct CrossPoint {
    pub point: Vec3,
    pub times: [f64; 2],
}

/// The crossing of the two boundaries: arcs (closed loops, or arcs between
/// nodes), and the nodes (where the two boundaries touch).
#[derive(Clone, Debug, Default)]
pub struct Crossing {
    pub arcs: Vec<Arc>,
    pub nodes: Vec<Vec3>,
}

#[derive(Clone, Debug)]
pub struct Arc {
    pub points: Vec<CrossPoint>,
    pub closed: bool,
    /// The node each end reaches (index into `nodes`), where it does.
    pub ends: [Option<usize>; 2],
}

fn solve3(rows: [Vec3; 3], rhs: [f64; 3]) -> Option<Vec3> {
    let det = rows[0].dot(rows[1].cross(rows[2]));
    let scale = rows[0].length() * rows[1].length() * rows[2].length();
    if !(det.abs() > 1e-14 * scale) {
        return None;
    }
    // Cramer, by the columns' cross products.
    let (c0, c1, c2) = (rows[1].cross(rows[2]), rows[2].cross(rows[0]), rows[0].cross(rows[1]));
    Some(c0.scale(rhs[0]).add(c1.scale(rhs[1])).add(c2.scale(rhs[2])).scale(1.0 / det))
}

/// Newton onto both depths = r within the plane through `anchor` square to
/// `normal`.
fn polish(members: [Member; 2], start: Vec3, anchor: Vec3, normal: Vec3) -> Option<CrossPoint> {
    let size = members[0].size().max(members[1].size());
    let r = [members[0].tube.minor, members[1].tube.minor];
    let mut x = start;
    for _ in 0..40 {
        let (da, ta) = members[0].at(x);
        let (db, tb) = members[1].at(x);
        let f = [da - r[0], db - r[1], normal.dot(x.sub(anchor))];
        let (ga, gb) = (members[0].gradient(x, ta), members[1].gradient(x, tb));
        if f.iter().all(|v| v.abs() <= 1e-13 * size) {
            return Some(CrossPoint { point: x, times: [ta, tb] });
        }
        let step = solve3([ga, gb, normal], f)?;
        if !(step.length() <= 0.1 * size) {
            return None;
        }
        x = x.sub(step);
    }
    None
}

/// How a locked polish ended.
enum Locked {
    /// On the boundary of both: the global depths agree.
    Held(CrossPoint),
    /// Converged on the locked sheets, but another pose of either motion
    /// reaches the point (the step crossed a crease).
    Covered(CrossPoint),
    Failed,
}

/// [`polish`] on the sheets of the times `guesses` (each depth read near
/// its guess, so Newton never jumps between sheets at a crease), then held
/// to the global depths.
fn polish_locked(members: [Member; 2], start: Vec3, anchor: Vec3, normal: Vec3, guesses: [f64; 2]) -> Locked {
    let size = members[0].size().max(members[1].size());
    let r = [members[0].tube.minor, members[1].tube.minor];
    let mut x = start;
    let mut times = guesses;
    for _ in 0..40 {
        let (da, ta) = members[0].near(x, times[0]);
        let (db, tb) = members[1].near(x, times[1]);
        times = [ta, tb];
        let f = [da - r[0], db - r[1], normal.dot(x.sub(anchor))];
        if f.iter().all(|v| v.abs() <= 1e-13 * size) {
            let point = CrossPoint { point: x, times };
            let ((ga, _), (gb, _)) = (members[0].at(x), members[1].at(x));
            if ga < da - 1e-12 * size || gb < db - 1e-12 * size {
                return Locked::Covered(point);
            }
            return Locked::Held(point);
        }
        let (na, nb) = (members[0].gradient(x, ta), members[1].gradient(x, tb));
        let Some(step) = solve3([na, nb, normal], f) else { return Locked::Failed };
        if !(step.length() <= 0.1 * size) {
            return Locked::Failed;
        }
        x = x.sub(step);
    }
    Locked::Failed
}

/// Across a crease: `here` is on the boundary of both, and a step of `h`
/// along `along` on the same sheets is covered. The crease (where another
/// pose takes over) is found by bisecting the step; from it the crossing
/// leaves on the new sheets, in whichever direction holds.
fn cross_crease(members: [Member; 2], here: CrossPoint, along: Vec3, h: f64, size: f64) -> Option<(CrossPoint, CrossPoint, Vec3)> {
    let at = |s: f64| -> Locked {
        let predicted = here.point.add(along.scale(s));
        polish_locked(members, predicted, predicted, along, here.times)
    };
    let (mut lo, mut hi) = (0.0f64, h);
    let mut last_held = here;
    for _ in 0..50 {
        if hi - lo <= 1e-12 * size {
            break;
        }
        let m = 0.5 * (lo + hi);
        match at(m) {
            Locked::Held(point) => {
                lo = m;
                last_held = point;
            }
            Locked::Covered(_) => hi = m,
            Locked::Failed => return None,
        }
    }
    // The new sheets: the global times just past the crease.
    let past = match at(hi) {
        Locked::Covered(point) | Locked::Held(point) => point.point,
        Locked::Failed => return None,
    };
    let ((_, ta), (_, tb)) = (members[0].at(past), members[1].at(past));
    let crease = last_held;
    let normal_a = members[0].gradient(crease.point, ta);
    let normal_b = members[1].gradient(crease.point, tb);
    let t = normal_a.cross(normal_b);
    let t = t.scale(1.0 / t.length().max(1e-300));
    let step = 1e-4 * size;
    let mut best: Option<(f64, CrossPoint, Vec3)> = None;
    for direction in [t, t.scale(-1.0)] {
        let predicted = crease.point.add(direction.scale(step));
        if let Locked::Held(point) = polish_locked(members, predicted, predicted, direction, [ta, tb]) {
            let score = direction.dot(along);
            if best.as_ref().is_none_or(|b| score > b.0) {
                best = Some((score, point, direction));
            }
        }
    }
    best.map(|(_, point, direction)| (crease, point, direction))
}

/// The unit tangent of the crossing at a point: along both boundaries.
fn tangent(members: [Member; 2], p: &CrossPoint) -> Option<Vec3> {
    let t = members[0].gradient(p.point, p.times[0]).cross(members[1].gradient(p.point, p.times[1]));
    let length = t.length();
    (length > 1e-12).then(|| t.scale(1.0 / length))
}

/// Where both motions place the ring alike, the points of that torus where
/// both grazing curves cross (each motion's velocity square to the torus's
/// normal), kept where neither solid's other poses reach them.
pub fn shared_pose_nodes(a: &Tube, b: &Tube) -> Vec<Vec3> {
    let size = (a.major + a.minor).max(b.major + b.minor);
    if (a.major - b.major).abs() > 1e-12 * size || (a.minor - b.minor).abs() > 1e-12 * size {
        return Vec::new();
    }
    // The ring's core circle at a pose, as three of its points.
    let marks = |tube: &Tube, t: f64| -> [Vec3; 3] {
        let pose = tube.motion.pose(t);
        [tube.centre, tube.centre.add(tube.x.scale(tube.major)), tube.centre.add(tube.y.scale(tube.major))].map(|p| pose.apply(p))
    };
    // Equal circles: centres and axes alike (the rings are round, so a turn
    // about their axis does not matter).
    let apart = |ta: f64, tb: f64| -> f64 {
        let (pa, pb) = (a.motion.pose(ta), b.motion.pose(tb));
        let (ca, cb) = (pa.apply(a.centre), pb.apply(b.centre));
        let (za, zb) = (pa.rotate(a.axis), pb.rotate(b.axis));
        ca.sub(cb).length() + a.major * za.cross(zb).length() + a.major * (za.dot(zb) - 1.0).abs()
    };
    let _ = marks;
    let n = 64;
    let at = |i: usize, tube: &Tube| tube.from + (tube.to - tube.from) * i as f64 / n as f64;
    let grid: Vec<Vec<f64>> = (0..=n).map(|i| (0..=n).map(|j| apart(at(i, a), at(j, b))).collect()).collect();
    let mut poses: Vec<(f64, f64)> = Vec::new();
    for i in 0..=n {
        for j in 0..=n {
            let v = grid[i][j];
            let least = (i.saturating_sub(1)..=(i + 1).min(n)).all(|x| (j.saturating_sub(1)..=(j + 1).min(n)).all(|y| grid[x][y] >= v));
            if !least || v > 0.2 * size {
                continue;
            }
            let (mut c, mut h, mut best) = ((at(i, a), at(j, b)), [(a.to - a.from) / n as f64, (b.to - b.from) / n as f64], v);
            for _ in 0..200 {
                let mut moved = false;
                for (x, y) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (1.0, -1.0)] {
                    let w = ((c.0 + h[0] * x).clamp(a.from, a.to), (c.1 + h[1] * y).clamp(b.from, b.to));
                    let d = apart(w.0, w.1);
                    if d < best {
                        (best, c, moved) = (d, w, true);
                    }
                }
                if !moved {
                    h = [h[0] * 0.5, h[1] * 0.5];
                    if h[0] < 1e-16 * (a.to - a.from) {
                        break;
                    }
                }
            }
            if best <= 1e-10 * size && !poses.iter().any(|p| (p.0 - c.0).abs() < 1e-6 && (p.1 - c.1).abs() < 1e-6) {
                poses.push(c);
            }
        }
    }
    let mut nodes: Vec<Vec3> = Vec::new();
    let (ma, mb) = (Member { tube: a }, Member { tube: b });
    for (ta, tb) in poses {
        let pose = a.motion.pose(ta);
        let point = |psi: f64, phi: f64| -> (Vec3, Vec3) {
            let (s, c) = psi.sin_cos();
            let radial = a.x.scale(c).add(a.y.scale(s));
            let normal = radial.scale(phi.cos()).add(a.axis.scale(phi.sin()));
            (pose.apply(a.centre.add(radial.scale(a.major)).add(normal.scale(a.minor))), pose.rotate(normal))
        };
        let rates = |psi: f64, phi: f64| -> [f64; 2] {
            let (x, normal) = point(psi, phi);
            [a.motion.velocity(ta, x).dot(normal), b.motion.velocity(tb, x).dot(normal)]
        };
        let (nu, nv) = (360usize, 180usize);
        let tau = std::f64::consts::TAU;
        let value: Vec<Vec<[f64; 2]>> = (0..=nu).map(|i| (0..=nv).map(|j| rates(tau * i as f64 / nu as f64, tau * j as f64 / nv as f64)).collect()).collect();
        for i in 0..nu {
            for j in 0..nv {
                let corners = [value[i][j], value[i + 1][j], value[i][j + 1], value[i + 1][j + 1]];
                let changes = |k: usize| corners.iter().any(|c| c[k] <= 0.0) && corners.iter().any(|c| c[k] >= 0.0);
                if !(changes(0) && changes(1)) {
                    continue;
                }
                // Newton in (ψ, φ) from the cell's middle, numeric Jacobian.
                let (mut u, mut v) = (tau * (i as f64 + 0.5) / nu as f64, tau * (j as f64 + 0.5) / nv as f64);
                let mut converged = false;
                for _ in 0..50 {
                    let f = rates(u, v);
                    if f[0].abs().max(f[1].abs()) <= 1e-15 * size {
                        converged = true;
                        break;
                    }
                    let h = 1e-7;
                    let (fu, fv) = (rates(u + h, v), rates(u, v + h));
                    let j11 = (fu[0] - f[0]) / h;
                    let j12 = (fv[0] - f[0]) / h;
                    let j21 = (fu[1] - f[1]) / h;
                    let j22 = (fv[1] - f[1]) / h;
                    let det = j11 * j22 - j12 * j21;
                    if !(det.abs() > 0.0) {
                        break;
                    }
                    let (du, dv) = ((j22 * f[0] - j12 * f[1]) / det, (j11 * f[1] - j21 * f[0]) / det);
                    if du.abs().max(dv.abs()) > 0.1 {
                        break;
                    }
                    u -= du;
                    v -= dv;
                    if du.abs().max(dv.abs()) < 1e-15 {
                        converged = true;
                        break;
                    }
                }
                if !converged {
                    continue;
                }
                let (x, _) = point(u, v);
                if nodes.iter().any(|n| n.sub(x).length() < 1e-9 * size) {
                    continue;
                }
                // Exposed on both: no other pose of either motion reaches it.
                let ((da, _), (db, _)) = (ma.at(x), mb.at(x));
                if da >= a.minor - 1e-12 * size && db >= b.minor - 1e-12 * size {
                    nodes.push(x);
                }
            }
        }
    }
    nodes
}

/// The crossing of the two tubes' boundaries, traced from seeds where A's K
/// (where A exposes it) and B's K change side of the other.
pub fn crossing(a: &Tube, b: &Tube) -> Result<Crossing, String> {
    let members = [Member { tube: a }, Member { tube: b }];
    let size = members[0].size().max(members[1].size());
    let nodes = shared_pose_nodes(a, b);
    let started = web_time::Instant::now();
    let mut tracing = 0.0f64;
    let mut arcs: Vec<Arc> = Vec::new();
    // (by the traced polyline, not its points: twin arcs between the same
    // two nodes run close beside each other, so a seed is skipped only
    // when it lies on a traced arc's own chords)
    let near_traced = |arcs: &[Arc], x: Vec3, within: f64| {
        arcs.iter().any(|arc| {
            arc.points.windows(2).any(|w| {
                let (a, b) = (w[0].point, w[1].point);
                let ab = b.sub(a);
                let t = (x.sub(a).dot(ab) / ab.dot(ab).max(1e-300)).clamp(0.0, 1.0);
                a.add(ab.scale(t)).sub(x).length() < within
            })
        })
    };
    // Each node is met by exactly four arc ends (two crossings through an X)
    // where the shared pose t = 0 lies inside both motions; where it is an end
    // pose of either, the X is cut by that end cap and only an even count is
    // asked. A seed grid too coarse for a pair of close twins misses one; the
    // grid is then doubled until every node's ends are found.
    let interior = |t: &Tube| t.from < 0.0 && t.to > 0.0;
    let full_x = interior(a) && interior(b);
    for refinement in 0..3usize {
        if refinement > 0 {
            arcs.clear();
        }
        for (own, other) in [(0usize, 1usize), (1, 0)] {
            let tube = members[own].tube;
            let (ns, np) = (96usize << refinement, 36usize << refinement);
            // g: other depth − r where own exposes K, None where own covers it.
            // (K where its own motion covers it is not skipped: a seed there
            // polishes onto the crossing itself or fails, as the polish reads
            // both global depths.)
            let sample = |i: usize, j: usize| -> Option<(Vec3, f64)> {
                let (sigma, psi) = (4.0 * (i as f64 + 0.5) / ns as f64, std::f64::consts::TAU * j as f64 / np as f64);
                let q = tube.k_at(sigma, psi)?;
                Some((q, members[other].at(q).0 - members[other].tube.minor))
            };
            let grid: Vec<Vec<Option<(Vec3, f64)>>> = (0..ns).map(|i| (0..np).map(|j| sample(i, j)).collect()).collect();
            for i in 0..ns {
                for j in 0..np {
                    let Some((p, gp)) = grid[i][j] else { continue };
                    for (k, l) in [((i + 1) % ns, j), (i, (j + 1) % np)] {
                        let Some((q, gq)) = grid[k][l] else { continue };
                        if gp.signum() == gq.signum() {
                            continue;
                        }
                        // the zero on the chord, by bisection on the other depth
                        let (mut lo, mut hi) = (0.0f64, 1.0f64);
                        // (a seed: the polish that follows settles it exactly)
                        for _ in 0..20 {
                            let m = 0.5 * (lo + hi);
                            let x = p.add(q.sub(p).scale(m));
                            let g = members[other].at(x).0 - members[other].tube.minor;
                            if g.signum() == gp.signum() {
                                lo = m;
                            } else {
                                hi = m;
                            }
                        }
                        let seed = p.add(q.sub(p).scale(0.5 * (lo + hi)));
                        let chord = q.sub(p).length();
                        // (the seed is off the crossing by about its chord's
                        // sagitta; the polished start is on it, and on a traced
                        // arc it lies within the arc's own chords' sagitta)
                        if near_traced(&arcs, seed, 0.5 * chord) {
                            continue;
                        }
                        let normal = q.sub(p).scale(1.0 / chord.max(1e-300));
                        let Some(start) = polish(members, seed, seed, normal) else { continue };
                        if near_traced(&arcs, start.point, 2e-3 * size) {
                            continue;
                        }
                        let trace_started = web_time::Instant::now();
                        arcs.push(trace_arc(members, start, &nodes, size)?);
                        tracing += trace_started.elapsed().as_secs_f64();
                    }
                }
            }
        }
        let ends_at = |k: usize| arcs.iter().flat_map(|arc| arc.ends).filter(|end| *end == Some(k)).count();
        if (0..nodes.len()).all(|k| if full_x { ends_at(k) == 4 } else { ends_at(k) % 2 == 0 && ends_at(k) <= 4 }) {
            break;
        }
        if refinement == 2 {
            let degrees: Vec<usize> = (0..nodes.len()).map(ends_at).collect();
            return Err(format!("the crossing's nodes are met by {degrees:?} arc ends, not {} each", if full_x { "four" } else { "an even count" }));
        }
    }
    if std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok() {
        let points: usize = arcs.iter().map(|arc| arc.points.len()).sum();
        let (calls, reads) = oracle_counts();
        eprintln!("crossing: {} arcs ({points} points) in {:.2} s, of which tracing {tracing:.2} s; {calls} depth reads, {reads} distance reads", arcs.len(), started.elapsed().as_secs_f64());
    }
    Ok(Crossing { arcs, nodes })
}

/// The arc through `start`, traced both ways until it closes or reaches a node.
fn trace_arc(members: [Member; 2], start: CrossPoint, nodes: &[Vec3], size: f64) -> Result<Arc, String> {
    let direction = tangent(members, &start).ok_or("a crossing seed lies where the boundaries touch")?;
    let (forward, forward_end, closed) = trace_way(members, start, direction, nodes, size, None)?;
    if closed {
        return Ok(Arc { points: forward, closed: true, ends: [None, None] });
    }
    let (backward, backward_end, _) = trace_way(members, start, direction.scale(-1.0), nodes, size, Some(forward_end))?;
    let mut points: Vec<CrossPoint> = backward.into_iter().rev().collect();
    points.pop();
    points.extend(forward);
    Ok(Arc { points, closed: false, ends: [backward_end, forward_end] })
}

/// One way along the crossing: the points (from `start`), the node reached (if
/// any), and whether it came back round to `start`.
#[allow(clippy::type_complexity)]
fn trace_way(members: [Member; 2], start: CrossPoint, direction: Vec3, nodes: &[Vec3], size: f64, _other_end: Option<Option<usize>>) -> Result<(Vec<CrossPoint>, Option<usize>, bool), String> {
    let mut points = vec![start];
    let mut along = direction;
    let (mut h, h_min, h_max) = (0.01 * size, 1e-7 * size, 0.012 * size);
    let mut travelled = 0.0;
    for _ in 0..200_000 {
        let here = *points.last().unwrap();
        // A node within reach ends the arc there.
        if let Some((k, node)) = nodes.iter().enumerate().find(|(_, n)| n.sub(here.point).length() < 2.0 * h.max(1e-3 * size)) {
            let to = node.sub(here.point);
            if to.dot(along) > 0.0 || to.length() < 1e-9 * size {
                points.push(CrossPoint { point: *node, times: here.times });
                return Ok((points, Some(k), false));
            }
        }
        let predicted = here.point.add(along.scale(h));
        // On the current sheets; where the step crosses a crease (another
        // pose reaches the point) it halves, and at the least steps it takes
        // the sheets the global depths name there.
        let next = match polish_locked(members, predicted, predicted, along, here.times) {
            Locked::Held(point) => Some(point),
            Locked::Covered(_) => {
                // a crease within the step: cross it exactly
                if let Some((crease, past, direction)) = cross_crease(members, here, along, h, size) {
                    if std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok() {
                        eprintln!("crossing: a crease at ({:.6}, {:.6}, {:.6}), times {:?} -> {:?}, turn {:.3}", crease.point.x, crease.point.y, crease.point.z, here.times, past.times, direction.dot(along).clamp(-1.0, 1.0).acos());
                    }
                    travelled += crease.point.sub(here.point).length() + past.point.sub(crease.point).length();
                    points.push(crease);
                    points.push(past);
                    along = direction;
                    h = (1e-3 * size).max(h_min);
                    continue;
                }
                None
            }
            Locked::Failed => polish(members, predicted, predicted, along),
        };
        let accepted = next.and_then(|next| {
            let chord = next.point.sub(here.point);
            let length = chord.length();
            if !(length > 0.2 * h && length < 2.0 * h) {
                return None;
            }
            let mut t = tangent(members, &next)?;
            if t.dot(chord) < 0.0 {
                t = t.scale(-1.0);
            }
            // A sharp turn is a crease (a time jumped): accepted at any angle
            // when a step this short still turns; else the step halves.
            let jumped = (next.times[0] - here.times[0]).abs() > 1e-3 * (members[0].tube.to - members[0].tube.from)
                || (next.times[1] - here.times[1]).abs() > 1e-3 * (members[1].tube.to - members[1].tube.from);
            let turn = t.dot(along).clamp(-1.0, 1.0).acos();
            // (A crease turns the crossing at once: a turn that survives the
            // step halving down to the least steps is taken as one.)
            if turn > 0.1 && h > 4.0 * h_min {
                return None;
            }
            if turn > 0.1 && std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok() {
                eprintln!("crossing: a crease at ({:.6}, {:.6}, {:.6}), turn {turn:.3}, time jumped {jumped}", next.point.x, next.point.y, next.point.z);
            }
            Some((next, t, length))
        });
        match accepted {
            Some((next, t, length)) => {
                travelled += length;
                points.push(next);
                along = t;
                h = (h * 1.5).min(h_max);
                if travelled > 4.0 * h_max && next.point.sub(start.point).length() < 1.5 * h_max {
                    // closing: the start lies just ahead
                    let back = start.point.sub(next.point);
                    if back.dot(along) > 0.0 {
                        points.push(start);
                        return Ok((points, None, true));
                    }
                }
            }
            None => {
                h *= 0.5;
                if h < h_min {
                    let predicted = here.point.add(along.scale(4.0 * h_min));
                    let (ga, gb) = (members[0].gradient(here.point, here.times[0]), members[1].gradient(here.point, here.times[1]));
                    let next = polish(members, predicted, predicted, along);
                    return Err(format!(
                        "the crossing trace stalls at ({:.6}, {:.6}, {:.6}) (times {:.6} {:.6}, normals' sine {:.3e}, next {:?})",
                        here.point.x, here.point.y, here.point.z, here.times[0], here.times[1], ga.cross(gb).length(), next
                    ));
                }
            }
        }
    }
    Err("the crossing trace does not end".into())
}

/// The back half of the boolean, from an imprint of the two operands: their
/// edges split where the sections meet them, their faces cut into fragments,
/// each fragment kept by the exact membership of the other tube at its test
/// points (not by ray casts against the other body), and the kept fragments
/// assembled into a solid by the kernel's assembler.
pub fn assemble_by_membership(
    a: &Tube,
    first: &BrepSolid,
    b: &Tube,
    second: &BrepSolid,
    imprint: &crate::ImprintResultRecord,
    operation: BooleanOperation,
) -> Result<BrepSolid, KernelRefusal> {
    let options = crate::BooleanOptions::default();
    let policy = crate::boolean::boolean_policy(first, second, &options)?;
    let tolerance = policy.model;
    let (split_first, _) = crate::apply_edge_splits_with_map(first, 0, imprint)?;
    let (split_second, _) = crate::apply_edge_splits_with_map(second, 1, imprint)?;
    let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, imprint, None)?;
    let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, imprint, None)?;
    if std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok() {
        eprintln!("tube boolean: {} + {} fragments", fragments_a.len(), fragments_b.len());
    }
    let members = [Member { tube: a }, Member { tube: b }];
    // Whether each operand's fragments are kept inside the other.
    let keep_inside = match operation {
        BooleanOperation::Union => [false, false],
        BooleanOperation::Intersect => [true, true],
        BooleanOperation::Subtract => [false, true],
    };
    let mut selected = Vec::new();
    let (mut kept, mut ambiguous) = (0usize, 0usize);
    for fragment in fragments_a.into_iter().chain(fragments_b) {
        let own = fragment.operand as usize;
        let other = members[1 - own];
        // The other's depth − r at each test point: the votes of the points
        // clearly off its boundary decide.
        let band = 1e-7 * other.size();
        let (mut inside, mut outside) = (0usize, 0usize);
        for point in std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied()) {
            let g = other.at(point).0 - other.tube.minor;
            if g < -band {
                inside += 1;
            } else if g > band {
                outside += 1;
            }
        }
        if inside == outside {
            ambiguous += 1;
            return Err(refuse("tube_boolean_select", format!(
                "a fragment of operand {own} (face {}) is not clearly inside or outside the other ({inside} in, {outside} out)",
                fragment.source_face_id
            )));
        }
        let is_inside = inside > outside;
        if is_inside != keep_inside[own] {
            continue;
        }
        let mut fragment = fragment;
        if own == 1 && matches!(operation, BooleanOperation::Subtract) {
            fragment.same_sense = !fragment.same_sense;
            for loop_record in &mut fragment.loops {
                loop_record.coedges.reverse();
                for coedge in &mut loop_record.coedges {
                    coedge.forward = !coedge.forward;
                    coedge.pcurve = coedge.pcurve.reversed().map_err(|why| refuse("tube_boolean_reverse", why.to_string()))?;
                }
            }
        }
        kept += 1;
        selected.push(fragment);
    }
    if std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok() {
        eprintln!("tube boolean: {kept} fragments kept ({ambiguous} ambiguous)");
    }
    let solids: crate::boolean::HashMap<u8, &BrepSolid> = [(0u8, &split_first), (1u8, &split_second)].into_iter().collect();
    let solid = crate::boolean::assemble::with_exact_sections(|| crate::boolean::assemble_fragments(selected, &solids, imprint, tolerance))?;
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(refuse("tube_boolean_validate", format!("the result does not validate: {:?}", issues.first())));
    }
    Ok(solid)
}

/// Where the crossing meets an edge of an operand (or a node): one vertex of
/// the sections, with the edges it splits.
#[derive(Clone, Debug)]
struct SectionVertex {
    point: Vec3,
    /// (operand, edge id, parameter)
    on_edges: Vec<(u8, u64, f64)>,
}

/// Every point of `solid`'s edges where the other member's depth crosses r,
/// by sign changes on samples spaced at most `spacing` apart (bisected to
/// the parameter's rounding), and where an edge passes through a node.
fn edge_crossings(operand: u8, solid: &BrepSolid, other: Member, nodes: &[Vec3], vertices: &mut Vec<SectionVertex>) -> Result<(), String> {
    let size = other.size();
    let spacing = 2e-2 * size;
    let r = other.tube.minor;
    for edge in &solid.edges {
        if edge.degenerate {
            continue;
        }
        let at = |s: f64| edge.curve.evaluate(s).map_err(|why| why.to_string());
        // length, roughly
        let coarse: Vec<Vec3> = (0..=64).map(|k| at(edge.t0 + (edge.t1 - edge.t0) * k as f64 / 64.0)).collect::<Result<_, _>>()?;
        let length: f64 = coarse.windows(2).map(|w| w[1].sub(w[0]).length()).sum();
        let count = ((length / spacing).ceil() as usize).clamp(16, 20_000);
        let params: Vec<f64> = (0..=count).map(|k| edge.t0 + (edge.t1 - edge.t0) * k as f64 / count as f64).collect();
        let points: Vec<Vec3> = params.iter().map(|&s| at(s)).collect::<Result<_, _>>()?;
        let values: Vec<f64> = points.iter().map(|&p| other.at(p).0 - r).collect();
        let mut add = |point: Vec3, s: f64| {
            vertices.push(SectionVertex { point, on_edges: vec![(operand, edge.id, s)] });
        };
        // The depth is 1-Lipschitz in space: a span whose ends' |g| add to
        // more than its length holds no root. Spans that are not so cleared
        // are halved, so a crossing in and out between two samples is found.
        let mut spans: Vec<(f64, f64, Vec3, Vec3, f64, f64, usize)> = (0..count).map(|k| (params[k], params[k + 1], points[k], points[k + 1], values[k], values[k + 1], 0)).collect();
        let mut brackets: Vec<(f64, f64, f64)> = Vec::new();
        // Within a node's ball the node is the only vertex: the depth only
        // touches r there, and the crossing's four arcs leave it inside the
        // faces (`sections` makes the node a vertex of each edge through it).
        let ball = 1e-3 * size;
        let in_ball = |p: Vec3| nodes.iter().any(|n| n.sub(p).length() < ball);
        while let Some((sa, sb, pa, pb, ga, gb, level)) = spans.pop() {
            if in_ball(pa) && in_ball(pb) {
                continue;
            }
            if ga == 0.0 {
                add(pa, sa);
                continue;
            }
            if gb.signum() != ga.signum() && gb != 0.0 {
                brackets.push((sa, sb, ga));
                continue;
            }
            // (1.05: the edge's arc between two close stations, by its chord.
            // These roots only seed arcs the grid missed; the face walk finds
            // every passage itself, so the halving stays shallow.)
            if ga.abs() + gb.abs() > 1.05 * pb.sub(pa).length() || level >= 6 {
                continue;
            }
            let sm = 0.5 * (sa + sb);
            let pm = at(sm)?;
            let gm = other.at(pm).0 - r;
            spans.push((sa, sm, pa, pm, ga, gm, level + 1));
            spans.push((sm, sb, pm, pb, gm, gb, level + 1));
        }
        if values[count] == 0.0 {
            add(points[count], params[count]);
        }
        for (lo, hi, ga) in brackets {
            if in_ball(at(lo)?) || in_ball(at(hi)?) {
                continue;
            }
            let (mut lo, mut hi) = (lo, hi);
            for _ in 0..60 {
                let m = 0.5 * (lo + hi);
                if (other.at(at(m)?).0 - r).signum() == ga.signum() {
                    lo = m;
                } else {
                    hi = m;
                }
                if hi - lo <= 1e-15 * (edge.t1 - edge.t0).abs() {
                    break;
                }
            }
            let s = 0.5 * (lo + hi);
            add(at(s)?, s);
        }
        // Nodes on this edge (the depth touches r there without changing sign).
        for node in nodes {
            let (k, _) = points.iter().enumerate().map(|(k, p)| (k, p.sub(*node).length())).min_by(|x, y| x.1.total_cmp(&y.1)).unwrap();
            let (mut lo, mut hi) = (params[k.saturating_sub(1)], params[(k + 1).min(count)]);
            let ratio = 0.5 * (5f64.sqrt() - 1.0);
            let distance = |s: f64| at(s).map(|p| p.sub(*node).length()).unwrap_or(f64::INFINITY);
            for _ in 0..100 {
                let (c, d) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo));
                if distance(c) < distance(d) {
                    hi = d;
                } else {
                    lo = c;
                }
            }
            let s = 0.5 * (lo + hi);
            if distance(s) <= 1e-6 * size {
                // the point on the edge, which its split will carry
                vertices.push(SectionVertex { point: at(s)?, on_edges: vec![(operand, edge.id, s)] });
            }
        }
    }
    Ok(())
}

/// One section piece: its points along the crossing (from vertex to vertex)
/// and its end vertices (indices into the welded vertices).
struct Piece {
    points: Vec<Vec3>,
    /// The times reaching each point (an end vertex takes its neighbour's).
    times: Vec<[f64; 2]>,
    ends: [usize; 2],
    /// The face of each operand holding it.
    faces: [u64; 2],
}

/// A coarse grid of points on a face's surface, for seeding its feet.
struct FaceGrid {
    id: u64,
    points: Vec<(Vec3, [f64; 2])>,
    low: Vec3,
    high: Vec3,
}

fn face_grids(solid: &BrepSolid) -> Vec<FaceGrid> {
    let mut grids = Vec::new();
    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
        let (Ok([u0, u1]), Ok([v0, v1])) = (face.surface.domain_u(), face.surface.domain_v()) else { continue };
        let n = 32usize;
        let mut points = Vec::with_capacity((n + 1) * (n + 1));
        let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
        for i in 0..=n {
            for j in 0..=n {
                let (u, v) = (u0 + (u1 - u0) * i as f64 / n as f64, v0 + (v1 - v0) * j as f64 / n as f64);
                if let Ok(p) = face.surface.evaluate(u, v) {
                    low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
                    high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
                    points.push((p, [u, v]));
                }
            }
        }
        grids.push(FaceGrid { id: face.id, points, low, high });
    }
    grids
}

/// The face of `solid` holding `point` (within `within` of its surface and
/// inside its trim), with the point's (u, v) there: feet seeded from each
/// face's nearest grid points.
fn face_holding(solid: &BrepSolid, grids: &[FaceGrid], point: Vec3, within: f64) -> Option<(u64, [f64; 2])> {
    let mut best: Option<(f64, u64, [f64; 2])> = None;
    for grid in grids {
        let pad = 0.05 * grid.high.sub(grid.low).length() + within;
        if point.x < grid.low.x - pad || point.y < grid.low.y - pad || point.z < grid.low.z - pad || point.x > grid.high.x + pad || point.y > grid.high.y + pad || point.z > grid.high.z + pad {
            continue;
        }
        let Some(face) = face_of(solid, grid.id) else { continue };
        let mut seeds: Vec<(f64, [f64; 2])> = grid.points.iter().map(|(p, uv)| (p.sub(point).length(), *uv)).collect();
        seeds.sort_by(|x, y| x.0.total_cmp(&y.0));
        for (_, seed) in seeds.iter().take(3) {
            let Ok(foot) = crate::projection::project_point_to_surface_from_seed(&face.surface, point, *seed) else { continue };
            if !(foot.distance <= within) {
                continue;
            }
            let class = crate::parameter_point_in_face(face, crate::Vec2 { x: foot.u, y: foot.v }, 1e-9);
            if !matches!(class, Ok(crate::PolygonClass::Inside) | Ok(crate::PolygonClass::Boundary)) {
                continue;
            }
            if best.as_ref().is_none_or(|b| foot.distance < b.0) {
                best = Some((foot.distance, face.id, [foot.u, foot.v]));
            }
            break;
        }
    }
    best.map(|(_, id, uv)| (id, uv))
}

/// Whether `point` lies on a traced arc (polished onto the crossing across
/// the nearest chords).
fn on_some_arc(members: [Member; 2], arcs: &[Arc], point: Vec3, size: f64) -> bool {
    let mut candidates: Vec<(f64, &CrossPoint, &CrossPoint)> = Vec::new();
    for arc in arcs {
        for w in arc.points.windows(2) {
            let (p, q) = (w[0].point, w[1].point);
            let d = q.sub(p);
            let along = d.dot(d);
            let f = if along > 0.0 { (point.sub(p).dot(d) / along).clamp(0.0, 1.0) } else { 0.0 };
            let distance = p.add(d.scale(f)).sub(point).length();
            if distance <= 2e-3 * size {
                candidates.push((distance, &w[0], &w[1]));
            }
        }
    }
    candidates.sort_by(|x, y| x.0.total_cmp(&y.0));
    candidates.iter().take(6).any(|&(chord, p, q)| {
        if chord <= 1e-9 * size {
            return true;
        }
        let d = q.point.sub(p.point);
        let normal = d.scale(1.0 / d.length().max(1e-300));
        match polish_locked(members, point, point, normal, p.times) {
            Locked::Held(x) | Locked::Covered(x) => x.point.sub(point).length() <= 2e-5 * size,
            Locked::Failed => false,
        }
    })
}

/// The foot of `point` on `face` (seeded from its grid's nearest points),
/// with its (u, v), where it lies within the face's trim.
fn foot_on(face: &crate::FaceRecord, grid: &FaceGrid, point: Vec3) -> Option<(f64, [f64; 2])> {
    let mut seeds: Vec<(f64, [f64; 2])> = grid.points.iter().map(|(p, uv)| (p.sub(point).length(), *uv)).collect();
    seeds.sort_by(|x, y| x.0.total_cmp(&y.0));
    let mut best: Option<(f64, [f64; 2])> = None;
    for (_, seed) in seeds.iter().take(3) {
        let Ok(foot) = crate::projection::project_point_to_surface_from_seed(&face.surface, point, *seed) else { continue };
        if best.is_none_or(|b| foot.distance < b.0) {
            best = Some((foot.distance, [foot.u, foot.v]));
        }
    }
    best
}

/// Whether (u, v) lies in the face's trim (or on its boundary).
fn in_face(face: &crate::FaceRecord, uv: [f64; 2]) -> bool {
    matches!(crate::parameter_point_in_face(face, crate::Vec2 { x: uv[0], y: uv[1] }, 1e-9), Ok(crate::PolygonClass::Inside) | Ok(crate::PolygonClass::Boundary))
}

/// An arc's walk through one operand's faces.
struct Walked {
    /// The face holding each segment of the arc.
    faces: Vec<u64>,
    /// (position along the arc, vertex) where it passes between two faces.
    vertices: Vec<(f64, SectionVertex)>,
}

/// Walk an arc through `solid`'s faces: each point's foot is read on the
/// face holding the last (seeded from its (u, v)); where it leaves that face,
/// the face holding it is found anew, and the passage between the two is
/// solved on the edge they share (a root of the other member's depth on
/// it). Two faces that share no edge (the arc cut a corner between two of
/// its points) are bridged by the crossing's own points between.
fn walk_faces(members: [Member; 2], solid: &BrepSolid, grids: &[FaceGrid], operand: u8, points: &[CrossPoint], closed: bool, size: f64) -> Result<Walked, String> {
    let other = members[1 - operand as usize];
    let within = 1e-5 * size;
    let n = points.len();
    let segments = n - 1;
    // The face (and (u, v)) of a point: the current face if it holds it.
    let holding = |current: Option<(u64, [f64; 2])>, point: Vec3| -> Option<(u64, [f64; 2])> {
        if let Some((id, uv)) = current {
            let face = face_of(solid, id)?;
            if let Ok(foot) = crate::projection::project_point_to_surface_from_seed(&face.surface, point, uv) {
                if foot.distance <= within && in_face(face, [foot.u, foot.v]) {
                    return Some((id, [foot.u, foot.v]));
                }
            }
        }
        // (an operand's faces are fits, and near a crease its trims may
        // stand off the exact crease: a looser reading where the tight finds none)
        face_holding(solid, grids, point, within).or_else(|| face_holding(solid, grids, point, 2e-3 * size))
    };
    // The faces at segment middles (a segment's ends may be nodes, which lie
    // on edges), from the arc's start.
    let mut faces = Vec::with_capacity(segments);
    let mut vertices: Vec<(f64, SectionVertex)> = Vec::new();
    let mut current: Option<(u64, [f64; 2])> = None;
    let mut middles: Vec<(Vec3, u64)> = Vec::with_capacity(segments);
    for k in 0..segments {
        let middle_guess = points[k].point.add(points[k + 1].point).scale(0.5);
        let normal = points[k + 1].point.sub(points[k].point);
        let normal = normal.scale(1.0 / normal.length().max(1e-300));
        // (a locked polish may run off along its sheets to a far root, one
        // another pose covers: the middle stays within its own segment)
        let reach = 0.5 * points[k + 1].point.sub(points[k].point).length();
        let held = |x: CrossPoint| (x.point.sub(middle_guess).length() <= reach).then_some(x.point);
        let middle = match polish_locked(members, middle_guess, middle_guess, normal, points[k].times) {
            Locked::Held(x) | Locked::Covered(x) => held(x),
            Locked::Failed => None,
        }
        .or_else(|| polish(members, middle_guess, middle_guess, normal).and_then(held))
        .unwrap_or(middle_guess);
        let found = holding(current, middle).ok_or_else(|| format!(
            "the crossing at ({:.6}, {:.6}, {:.6}) lies on no face of operand {operand}", middle.x, middle.y, middle.z
        ))?;
        current = Some(found);
        faces.push(found.0);
        middles.push((middle, found.0));
    }
    // Passages between consecutive segment middles held by different faces.
    let count = if closed { segments } else { segments - 1 };
    for k in 0..count {
        let next = (k + 1) % segments;
        let (from, to) = (middles[k], middles[next]);
        if from.1 == to.1 {
            continue;
        }
        // from segment k's middle to segment next's middle, through point k + 1
        let mut found: Vec<(f64, SectionVertex)> = Vec::new();
        passage(members, other, solid, grids, operand, from, to, points[(k + 1) % segments].times, size, 0, &mut |vertex, at| {
            let (p, q) = (from.0, to.0);
            let d = q.sub(p);
            let f = if d.dot(d) > 0.0 { (at.sub(p).dot(d) / d.dot(d)).clamp(0.0, 1.0) } else { 0.5 };
            found.push((f, vertex));
        })?;
        // Each vertex's place on the arc: its nearest chord about the joint.
        for (_, vertex) in found {
            let mut best = (f64::INFINITY, (k + 1) as f64);
            for offset in 0..6usize {
                let raw = k as i64 - 2 + offset as i64;
                if !closed && (raw < 0 || raw as usize >= segments) {
                    continue;
                }
                let seg = raw.rem_euclid(segments as i64) as usize;
                let (p, q) = (points[seg].point, points[seg + 1].point);
                let d = q.sub(p);
                let f = if d.dot(d) > 0.0 { (vertex.point.sub(p).dot(d) / d.dot(d)).clamp(0.0, 1.0) } else { 0.0 };
                let distance = p.add(d.scale(f)).sub(vertex.point).length();
                if distance < best.0 {
                    best = (distance, seg as f64 + f);
                }
            }
            vertices.push((best.1 % segments as f64, vertex));
        }
    }
    Ok(Walked { faces, vertices })
}

/// The passage of the crossing from face `from.1` (at point `from.0`) to face
/// `to.1` (at `to.0`): a vertex on their shared edge, or, where they share
/// none, the crossing's point between found on its face and both halves
/// resolved.
#[allow(clippy::too_many_arguments)]
fn passage(
    members: [Member; 2],
    other: Member,
    solid: &BrepSolid,
    grids: &[FaceGrid],
    operand: u8,
    from: (Vec3, u64),
    to: (Vec3, u64),
    times: [f64; 2],
    size: f64,
    level: usize,
    emit: &mut dyn FnMut(SectionVertex, Vec3),
) -> Result<(), String> {
    let (Some(face_a), Some(face_b)) = (face_of(solid, from.1), face_of(solid, to.1)) else { return Err("a walked face is missing".into()) };
    let edges_of = |face: &crate::FaceRecord| -> Vec<u64> { face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)).collect() };
    let (ea, eb) = (edges_of(face_a), edges_of(face_b));
    let shared: Vec<u64> = ea.iter().copied().filter(|e| eb.contains(e)).collect();
    let r = other.tube.minor;
    let g = |p: Vec3| other.at(p).0 - r;
    // the shared edge nearest the passage
    let mut best: Option<(f64, &crate::topology::EdgeRecord, f64, f64)> = None;
    for id in &shared {
        let Some(edge) = solid.edges.iter().find(|e| e.id == *id) else { continue };
        let (Ok(fa), Ok(fb)) = (crate::project_point_to_curve(&edge.curve, from.0), crate::project_point_to_curve(&edge.curve, to.0)) else { continue };
        let distance = fa.distance + fb.distance;
        if best.is_none_or(|b| distance < b.0) {
            best = Some((distance, edge, fa.u, fb.u));
        }
    }
    if let Some((_, edge, sa, sb)) = best {
        let (t0, t1) = (edge.t0.min(edge.t1), edge.t0.max(edge.t1));
        let at = |s: f64| edge.curve.evaluate(s).map_err(|why| why.to_string());
        let (mut lo, mut hi) = (sa.min(sb), sa.max(sb));
        for widen in 0..4 {
            let pad = (hi - lo).max(1e-6 * (t1 - t0)) * if widen == 0 { 0.25 } else { 2f64.powi(widen) };
            let (a, b) = ((lo - pad).max(t0), (hi + pad).min(t1));
            let count = 24usize;
            let params: Vec<f64> = (0..=count).map(|k| a + (b - a) * k as f64 / count as f64).collect();
            let values: Vec<f64> = params.iter().map(|&s| at(s).map(g)).collect::<Result<_, _>>()?;
            let middle: f64 = 0.5 * (sa + sb);
            let mut root: Option<(f64, f64, f64)> = None;
            for k in 0..count {
                if values[k] == 0.0 || values[k].signum() != values[k + 1].signum() {
                    let distance = (0.5 * (params[k] + params[k + 1]) - middle).abs();
                    if root.is_none_or(|r| distance < r.0) {
                        root = Some((distance, params[k], params[k + 1]));
                    }
                }
            }
            if let Some((_, mut x, mut y)) = root {
                let gx = g(at(x)?);
                if gx != 0.0 {
                    for _ in 0..60 {
                        let m = 0.5 * (x + y);
                        if g(at(m)?).signum() == gx.signum() {
                            x = m;
                        } else {
                            y = m;
                        }
                        if y - x <= 1e-15 * (t1 - t0) {
                            break;
                        }
                    }
                }
                let s = 0.5 * (x + y);
                let point = at(s)?;
                emit(SectionVertex { point, on_edges: vec![(operand, edge.id, s)] }, point);
                return Ok(());
            }
            lo = a;
            hi = b;
        }
        // No sign change: the crossing runs all but along the edge (each
        // face a fit, the root pair is lost in their gap): the vertex is the
        // edge's point of least |depth − r| near the passage, if that is tiny.
        {
            let (a, b) = ((sa.min(sb) - 0.5 * (sa - sb).abs()).max(t0), (sa.max(sb) + 0.5 * (sa - sb).abs()).min(t1));
            let count = 64usize;
            let mut least = (f64::INFINITY, a);
            for k in 0..=count {
                let s = a + (b - a) * k as f64 / count as f64;
                let value = g(at(s)?).abs();
                if value < least.0 {
                    least = (value, s);
                }
            }
            let h = (b - a) / count as f64;
            let (mut x, mut y) = ((least.1 - h).max(t0), (least.1 + h).min(t1));
            let ratio = 0.5 * (5f64.sqrt() - 1.0);
            for _ in 0..80 {
                let (c, d) = (y - ratio * (y - x), x + ratio * (y - x));
                if g(at(c)?).abs() < g(at(d)?).abs() {
                    y = d;
                } else {
                    x = c;
                }
            }
            let s = 0.5 * (x + y);
            let point = at(s)?;
            if g(point).abs() <= 1e-5 * size {
                emit(SectionVertex { point, on_edges: vec![(operand, edge.id, s)] }, point);
                return Ok(());
            }
        }
        return Err(format!(
            "the crossing passes from face {} to face {} of operand {operand} but its depth has no root on their edge {}",
            from.1, to.1, edge.id
        ));
    }
    // No shared edge: the crossing's point between, and each half.
    if level >= 24 || from.0.sub(to.0).length() <= 1e-8 * size {
        return Err(format!(
            "the crossing passes from face {} to face {} of operand {operand} through a corner near ({:.6}, {:.6}, {:.6})",
            from.1, to.1, from.0.x, from.0.y, from.0.z
        ));
    }
    let guess = from.0.add(to.0).scale(0.5);
    let normal = to.0.sub(from.0);
    let normal = normal.scale(1.0 / normal.length().max(1e-300));
    let middle = match polish_locked(members, guess, guess, normal, times) {
        Locked::Held(x) | Locked::Covered(x) => x.point,
        Locked::Failed => return Err("a crossing point between two faces does not polish".into()),
    };
    let (id, _) = face_holding(solid, grids, middle, 1e-5 * size).or_else(|| face_holding(solid, grids, middle, 2e-3 * size)).ok_or("a crossing point between two faces lies on no face")?;
    passage(members, other, solid, grids, operand, from, (middle, id), times, size, level + 1, emit)?;
    passage(members, other, solid, grids, operand, (middle, id), to, times, size, level + 1, emit)
}

fn solid_vertices_near(solid: &BrepSolid, a: Vec3, z: Vec3, within: f64) -> Vec<String> {
    solid.vertices.iter().filter(|v| v.point.sub(a).length() < within || v.point.sub(z).length() < within).map(|v| {
        let edges: Vec<u64> = solid.edges.iter().filter(|e| e.start_vertex_id == v.id || e.end_vertex_id == v.id).map(|e| e.id).collect();
        format!("v{} ({:.6}, {:.6}, {:.6}) edges {edges:?}", v.id, v.point.x, v.point.y, v.point.z)
    }).collect()
}

fn face_of(solid: &BrepSolid, id: u64) -> Option<&crate::FaceRecord> {
    solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == id)
}

/// The imprint of the two operands from the traced crossing: its vertices
/// where it meets their edges (and the nodes), its pieces between them each
/// on one face of either, with a pcurve on each, and the operands' edge splits.
pub fn sections(a: &Tube, first: &BrepSolid, b: &Tube, second: &BrepSolid, crossing: &Crossing) -> Result<crate::ImprintResultRecord, String> {
    let mut crossing = crossing.clone();
    let crossing = &mut crossing;
    let members = [Member { tube: a }, Member { tube: b }];
    let size = members[0].size().max(members[1].size());
    let debug = std::env::var("BREP_DEBUG_TUBE_BOOLEAN").is_ok();
    let started = web_time::Instant::now();
    let solids = [first, second];
    // 1. Arcs the seeds missed: any root of the other's depth on an
    //    operand edge that lies off every traced arc starts a trace.
    let mut raw: Vec<SectionVertex> = Vec::new();
    edge_crossings(0, first, members[1], &crossing.nodes, &mut raw)?;
    edge_crossings(1, second, members[0], &crossing.nodes, &mut raw)?;
    for v in &raw {
        if on_some_arc(members, &crossing.arcs, v.point, size) {
            continue;
        }
        let ((_, ta), (_, tb)) = (members[0].at(v.point), members[1].at(v.point));
        let along = members[0].gradient(v.point, ta).cross(members[1].gradient(v.point, tb));
        // A touch is no crossing: where one member ends on the shared pose,
        // the other's sheet is tangent to that end cap all along its own
        // grazing curve there, and neither boundary passes through the other.
        if along.length() < 1e-3 {
            continue;
        }
        let along = along.scale(1.0 / along.length().max(1e-300));
        let start = match polish_locked(members, v.point, v.point, along, [ta, tb]) {
            Locked::Held(point) => point,
            _ => polish(members, v.point, v.point, along).ok_or_else(|| format!(
                "a root of the depth on an operand edge at ({:.6}, {:.6}, {:.6}) lies off every traced arc and does not polish onto the crossing",
                v.point.x, v.point.y, v.point.z
            ))?,
        };
        let arc = trace_arc(members, start, &crossing.nodes, size)?;
        if debug {
            eprintln!("sections: an arc of {} points traced from an edge root at ({:.6}, {:.6}, {:.6})", arc.points.len(), v.point.x, v.point.y, v.point.z);
        }
        crossing.arcs.push(arc);
    }
    if debug {
        eprintln!("sections: {} edge roots, {} arcs by {:.2} s", raw.len(), crossing.arcs.len(), started.elapsed().as_secs_f64());
    }
    // 2. The vertices: each node (on the edges that pass through it), and
    //    every place an arc passes from one face of an operand to another
    //    (walked along the arc, solved on the edge the two faces share).
    let mut vertices: Vec<SectionVertex> = Vec::new();
    let mut node_vertex: Vec<usize> = Vec::new();
    for node in &crossing.nodes {
        let mut vertex = SectionVertex { point: *node, on_edges: Vec::new() };
        let mut moved = false;
        for (operand, solid) in solids.iter().enumerate() {
            for edge in &solid.edges {
                if edge.degenerate {
                    continue;
                }
                let Ok(foot) = crate::project_point_to_curve(&edge.curve, *node) else { continue };
                if foot.distance <= 1e-6 * size && foot.u > edge.t0.min(edge.t1) && foot.u < edge.t0.max(edge.t1) {
                    if !moved {
                        // the edge's own point, which its split will carry
                        vertex.point = edge.curve.evaluate(foot.u).map_err(|why| why.to_string())?;
                        moved = true;
                    }
                    vertex.on_edges.push((operand as u8, edge.id, foot.u));
                }
            }
        }
        node_vertex.push(vertices.len());
        vertices.push(vertex);
    }
    let grids = [face_grids(first), face_grids(second)];
    // cuts[arc]: (position along the arc's points, vertex)
    let mut cuts: Vec<Vec<(f64, usize)>> = vec![Vec::new(); crossing.arcs.len()];
    // faces[arc][operand][segment]: the face holding the segment
    let mut faces: Vec<[Vec<u64>; 2]> = Vec::with_capacity(crossing.arcs.len());
    for (arc_index, arc) in crossing.arcs.iter().enumerate() {
        let n = arc.points.len();
        if let [Some(first_node), Some(last_node)] = arc.ends {
            cuts[arc_index].push((0.0, node_vertex[first_node]));
            cuts[arc_index].push(((n - 1) as f64, node_vertex[last_node]));
        }
        let mut arc_faces: [Vec<u64>; 2] = [vec![0; n - 1], vec![0; n - 1]];
        for operand in 0..2usize {
            let walked = walk_faces(members, solids[operand], &grids[operand], operand as u8, &arc.points, arc.closed, size)?;
            for (segment, face) in walked.faces.iter().enumerate() {
                arc_faces[operand][segment] = *face;
            }
            for (position, vertex) in walked.vertices {
                // weld with a vertex already made there
                let index = match vertices.iter().position(|w| w.point.sub(vertex.point).length() <= 2e-6 * size) {
                    Some(index) => {
                        vertices[index].on_edges.extend(vertex.on_edges);
                        index
                    }
                    None => {
                        vertices.push(vertex);
                        vertices.len() - 1
                    }
                };
                cuts[arc_index].push((position, index));
            }
        }
        faces.push(arc_faces);
    }
    if debug {
        // how far each vertex stands off the exact crossing
        let mut worst = (0.0f64, Vec3::new(0.0, 0.0, 0.0));
        for (arc_index, arc) in crossing.arcs.iter().enumerate() {
            for &(position, index) in &cuts[arc_index] {
                let seg = (position.floor() as usize).min(arc.points.len() - 2);
                let (p, q) = (arc.points[seg], arc.points[seg + 1]);
                let d = q.point.sub(p.point);
                let normal = d.scale(1.0 / d.length().max(1e-300));
                let v = vertices[index].point;
                if let Locked::Held(x) | Locked::Covered(x) = polish_locked(members, v, v, normal, p.times) {
                    let off = x.point.sub(v).length();
                    if off > worst.0 {
                        worst = (off, v);
                    }
                }
            }
        }
        eprintln!("sections: {} vertices walked by {:.2} s; the farthest {:.3e} off the exact crossing at ({:.6}, {:.6}, {:.6})", vertices.len(), started.elapsed().as_secs_f64(), worst.0, worst.1.x, worst.1.y, worst.1.z);
    }
    // 3. Cut each arc at its vertices.
    let mut pieces: Vec<Piece> = Vec::new();
    for (arc_index, arc) in crossing.arcs.iter().enumerate() {
        let mut marks = std::mem::take(&mut cuts[arc_index]);
        marks.sort_by(|x, y| x.0.total_cmp(&y.0));
        marks.dedup_by(|x, y| x.1 == y.1 && (x.0 - y.0).abs() < 1e-9);
        let points: Vec<Vec3> = arc.points.iter().map(|p| p.point).collect();
        if marks.is_empty() {
            return Err(format!("a traced arc of {} points meets no operand edge and no node", points.len()));
        }
        let segments = points.len() - 1;
        let n = marks.len();
        let spans = if arc.closed { n } else { n - 1 };
        for c in 0..spans {
            let (from, to) = (marks[c], marks[(c + 1) % n]);
            let to_position = if arc.closed && c + 1 == n { to.0 + segments as f64 } else { to.0 };
            let (start, end) = (vertices[from.1].point, vertices[to.1].point);
            let mut inner: Vec<(Vec3, [f64; 2])> = Vec::new();
            let mut k = from.0.floor() as usize + 1;
            while (k as f64) < to_position {
                let at = &arc.points[k % segments];
                inner.push((at.point, at.times));
                k += 1;
            }
            let length: f64 = {
                let mut chain = vec![start];
                chain.extend(inner.iter().map(|(p, _)| *p));
                chain.push(end);
                chain.windows(2).map(|w| w[1].sub(w[0]).length()).sum()
            };
            // The arc's own points next to an end vertex are dropped: a crease
            // or seed point there would sit almost on the vertex (or past it).
            let zone = (2e-3 * size).min(length / 3.0);
            let edge_times = |position: f64| arc.points[(position.round() as usize).min(segments) % segments.max(1)].times;
            let start_times = inner.first().map_or(edge_times(from.0), |x| x.1);
            let end_times = inner.last().map_or(edge_times(to_position), |x| x.1);
            let mut clean: Vec<Vec3> = vec![start];
            let mut times: Vec<[f64; 2]> = vec![start_times];
            for (p, t) in inner {
                if p.sub(start).length() < zone || p.sub(end).length() < zone {
                    continue;
                }
                clean.push(p);
                times.push(t);
            }
            clean.push(end);
            times.push(end_times);
            // the faces of the piece: its middle segment's
            let middle = ((0.5 * (from.0 + to_position)).floor() as usize % segments).min(segments - 1);
            pieces.push(Piece { points: clean, times, ends: [from.1, to.1], faces: [faces[arc_index][0][middle], faces[arc_index][1][middle]] });
        }
    }
    // The record.
    let mut record = crate::ImprintResultRecord::default();
    let vertex_ids: Vec<u64> = (0..vertices.len()).map(|k| 1 + k as u64).collect();
    record.vertices = vertices.iter().zip(&vertex_ids).map(|(v, &id)| crate::ImprintVertex { id, point: v.point }).collect();
    let mut splits: HashMap<(u8, u64), Vec<f64>> = HashMap::new();
    for v in &vertices {
        for &(operand, edge, s) in &v.on_edges {
            splits.entry((operand, edge)).or_default().push(s);
        }
    }
    record.edge_splits = splits.into_iter().map(|((operand, edge), parameters)| crate::EdgeSplitRecord::new(operand, edge, parameters)).collect();
    let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::new();
    let (mut holding_seconds, mut projecting_seconds, mut projected_points) = (0.0f64, 0.0f64, 0usize);
    let mut face_gap = 0.0f64;
    for (index, piece) in pieces.iter().enumerate() {
        let id = 1 + index as u64;
        let middle = piece.points[piece.points.len() / 2];
        let middle = if piece.points.len() == 2 { piece.points[0].add(piece.points[1]).scale(0.5) } else { middle };
        // The faces holding the piece, found once at its middle.
        let mut holders = Vec::with_capacity(2);
        for operand in 0..2u8 {
            let solid = solids[operand as usize];
            let holding_started = web_time::Instant::now();
            let face_id = piece.faces[operand as usize];
            let face = face_of(solid, face_id).ok_or("a section piece's face is missing")?;
            let grid = grids[operand as usize].iter().find(|g| g.id == face_id).ok_or("a section piece's face has no grid")?;
            let middle_uv = foot_on(face, grid, middle).ok_or_else(|| format!(
                "a section piece's middle ({:.6}, {:.6}, {:.6}) has no foot on face {face_id} of operand {operand}", middle.x, middle.y, middle.z
            ))?.1;
            holding_seconds += holding_started.elapsed().as_secs_f64();
            holders.push((operand, face, middle_uv));
        }
        // Fit the curve and both pcurves through the piece's points; where a
        // fit strays between two points, the exact crossing's point between
        // them is added, and all are fitted again.
        let mut points = piece.points.clone();
        let mut round = 0usize;
        let mut times = piece.times.clone();
        let curve_band = 8e-7 * size;
        let (curve, params, pcurves) = loop {
            round += 1;
            let mut params = vec![0.0];
            for w in points.windows(2) {
                params.push(params.last().unwrap() + w[1].sub(w[0]).length());
            }
            let degree = 3.min(points.len() - 1);
            let curve = crate::interpolate_curve(&points, degree, &params).map_err(|why| format!("a section piece does not fit: {why}"))?;
            let projecting_started = web_time::Instant::now();
            let n = points.len();
            let mut fits = Vec::with_capacity(2);
            for (operand, face, middle_uv) in &holders {
                let start = if n == 2 { 0 } else { n / 2 };
                let mut uv = vec![[0.0f64; 2]; n];
                let mut far = 0.0f64;
                let mut gaps = vec![0.0f64; n];
                let foot = crate::projection::project_point_to_surface_from_seed(&face.surface, points[start], *middle_uv).map_err(|why| why.to_string())?;
                uv[start] = [foot.u, foot.v];
                far = far.max(foot.distance);
                gaps[start] = foot.distance;
                for k in (start + 1)..n {
                    let foot = crate::projection::project_point_to_surface_from_seed(&face.surface, points[k], uv[k - 1]).map_err(|why| why.to_string())?;
                    uv[k] = [foot.u, foot.v];
                    far = far.max(foot.distance);
                    gaps[k] = foot.distance;
                }
                for k in (0..start).rev() {
                    let foot = crate::projection::project_point_to_surface_from_seed(&face.surface, points[k], uv[k + 1]).map_err(|why| why.to_string())?;
                    uv[k] = [foot.u, foot.v];
                    far = far.max(foot.distance);
                    gaps[k] = foot.distance;
                }
                if far > 1e-5 * size && debug {
                    let list: Vec<String> = (0..n).map(|k| format!("{:.0}@({:.3},{:.3})", gaps[k] * 1e6, uv[k][0], uv[k][1])).collect();
                    eprintln!("sections: piece gaps (1e-6) and (u, v) on face {}: {}", face.id, list.join(" "));
                }
                if far > 1e-5 * size {
                    let (a, z) = (points[0], points[n - 1]);
                    let (umin, umax) = uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |m, w| (m.0.min(w[0]), m.1.max(w[0])));
                    let (vmin, vmax) = uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |m, w| (m.0.min(w[1]), m.1.max(w[1])));
                    let face_edges: Vec<u64> = face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)).collect();
                    let ends: Vec<String> = piece.ends.iter().map(|&e| format!("{:?} on {:?}", vertices[e].point, vertices[e].on_edges)).collect();
                    let corners: Vec<String> = solid_vertices_near(solids[*operand as usize], a, z, 0.05 * size);
                    return Err(format!(
                        "a section piece leaves face {} of operand {operand} ({:.3e} off it; {n} points from ({:.6}, {:.6}, {:.6}) to ({:.6}, {:.6}, {:.6}); u {umin:.4}..{umax:.4} of {:?}, v {vmin:.4}..{vmax:.4} of {:?}); face edges {face_edges:?}; ends {ends:?}; operand vertices near {corners:?}",
                        face.id, far, a.x, a.y, a.z, z.x, z.y, z.z, face.surface.domain_u().ok(), face.surface.domain_v().ok()
                    ));
                }
                let flat: Vec<Vec3> = uv.iter().map(|w| Vec3::new(w[0], w[1], 0.0)).collect();
                let pcurve = crate::interpolate_curve(&flat, degree, &params).map_err(|why| format!("a section pcurve does not fit: {why}"))?;
                fits.push(pcurve);
            }
            projecting_seconds += projecting_started.elapsed().as_secs_f64();
            projected_points += n;
            // Read each span's middle: the curve against the exact crossing,
            // each pcurve's image against the curve.
            let mut refine: Vec<usize> = Vec::new();
            for k in 0..n - 1 {
                let t = 0.5 * (params[k] + params[k + 1]);
                let Ok(on_curve) = curve.evaluate(t) else { refine.push(k); continue };
                let chord = points[k + 1].sub(points[k]);
                let normal = chord.scale(1.0 / chord.length().max(1e-300));
                let guess = if k == 0 { times[1.min(n - 1)] } else { times[k] };
                let exact = match polish_locked(members, on_curve, on_curve, normal, guess) {
                    Locked::Held(point) | Locked::Covered(point) => point.point,
                    Locked::Failed => on_curve,
                };
                // (A face is a fit of its envelope: it stands its own small
                // gap off the exact crossing, which no refinement closes. The
                // pcurve is held to the curve point's foot on the face.)
                // (the curve near an end follows its vertex, which stands on
                // its operand's edge up to that edge's fit off the crossing)
                // (within 1e-3 of the size of an end, the exact crossing may
                // already follow another sheet past an operand's fitted
                // crease: there only the pcurves are held)
                let mut miss = (exact.sub(on_curve).length() - curve_band).max(0.0);
                for ((_, face, _), pcurve) in holders.iter().zip(&fits) {
                    let Ok(w) = pcurve.evaluate(t) else { miss = f64::INFINITY; continue };
                    let Ok(image) = face.surface.evaluate(w.x, w.y) else { miss = f64::INFINITY; continue };
                    let Ok(foot) = crate::projection::project_point_to_surface_from_seed(&face.surface, on_curve, [w.x, w.y]) else { miss = f64::INFINITY; continue };
                    face_gap = face_gap.max(foot.distance);
                    miss = miss.max(image.sub(foot.point).length());
                }
                if miss > 2e-7 * size {
                    refine.push(k);
                    if round >= 7 && debug {
                        eprintln!("sections: span {k} of {n} strays {miss:.3e} at ({:.6}, {:.6}, {:.6}) (curve off the crossing {:.3e})", on_curve.x, on_curve.y, on_curve.z, exact.sub(on_curve).length());
                    }
                }
            }
            if refine.is_empty() || round >= 8 {
                if !refine.is_empty() {
                    let (a, z) = (points[0], points[n - 1]);
                    return Err(format!(
                        "a section piece's fits do not settle within 2e-7 of the size ({} spans stray; {n} points from ({:.6}, {:.6}, {:.6}) to ({:.6}, {:.6}, {:.6}))",
                        refine.len(), a.x, a.y, a.z, z.x, z.y, z.z
                    ));
                }
                break (curve, params, fits);
            }
            // the exact crossing's point at each straying span's middle
            let mut added: Vec<(usize, Vec3)> = Vec::new();
            let mut added_times: Vec<[f64; 2]> = Vec::new();
            for &k in &refine {
                let middle = points[k].add(points[k + 1]).scale(0.5);
                let chord = points[k + 1].sub(points[k]);
                let normal = chord.scale(1.0 / chord.length().max(1e-300));
                let guess = if k == 0 { times[1.min(points.len() - 1)] } else { times[k] };
                let exact = match polish_locked(members, middle, middle, normal, guess) {
                    Locked::Held(point) | Locked::Covered(point) => point,
                    Locked::Failed => return Err("a section piece's middle point does not polish onto the crossing".into()),
                };
                added.push((k, exact.point));
                added_times.push(exact.times);
            }
            for ((k, point), t) in added.into_iter().zip(added_times).rev() {
                points.insert(k + 1, point);
                times.insert(k + 1, t);
            }
        };
        let mut pcurve_records = Vec::with_capacity(2);
        let mut supports = Vec::with_capacity(2);
        for ((operand, face, _), pcurve) in holders.iter().zip(pcurves) {
            pcurve_records.push(crate::FacePcurve { operand: *operand, face_id: face.id, pcurve });
            supports.push(crate::FaceKey { operand: *operand, face_id: face.id });
            by_face.entry((*operand, face.id)).or_default().push(id);
        }
        let pcurves = pcurve_records;
        let [t0, t1] = [0.0, *params.last().unwrap()];
        record.pieces.push(crate::ImprintPieceRecord::new(id, curve, [t0, t1], [vertex_ids[piece.ends[0]], vertex_ids[piece.ends[1]]], pcurves, [supports[0], supports[1]]));
    }
    if debug {
        eprintln!("sections: {} pieces with their pcurves by {:.2} s (faces found in {holding_seconds:.2} s; {projected_points} points projected in {projecting_seconds:.2} s; the faces stand at most {face_gap:.3e} off the crossing)", record.pieces.len(), started.elapsed().as_secs_f64());
    }
    record.by_face = by_face.into_iter().map(|((operand, face_id), piece_ids)| crate::FaceImprints { operand, face_id, piece_ids }).collect();
    record.section_evidence = true;
    record.tangent_nodes = crossing.nodes.clone();
    Ok(record)
}