BREP_kernel 0.27.0

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

/// Seam fractions sampled to decide that a face carries the seam.
const STATIONS: [f64; 5] = [0.0, 0.25, 0.5, 0.75, 1.0];
/// Faces closer than this to parallel make no corner a fillet weld can fill.
const MIN_CORNER_SIN: f64 = 0.035; // about 2 degrees

#[derive(Clone, Debug)]
pub(super) struct JointFace {
    pub name: String,
    pub solid: String,
    handle: u32,
    face_id: u64,
    /// The outward normal at the seam's start.
    normal: Vec3,
    /// For a picked face across a root gap from a straight seam: the offset
    /// from the seam to its foot on the face (constant along the seam).
    gap: Option<Vec3>,
}

impl JointFace {
    pub(super) fn same(&self, other: &JointFace) -> bool {
        same(self, other)
    }
}

/// The fitted section at the seam's start: unit leg directions along each
/// joint face and the faces they lie on, leg 1 first.
#[derive(Clone, Debug)]
pub(super) struct Fit {
    pub faces: [JointFace; 2],
    pub legs: [Vec3; 2],
    /// The offset from the seam to the section's root: zero, or across a
    /// root gap onto the gapped face's plane.
    pub root: Vec3,
    /// How far along each leg from the root its face begins (the gap a leg
    /// crosses; zero for a leg that starts on its face).
    pub skip: [f64; 2],
    /// The stretch of the run (fractions from its start) the bead runs
    /// along: the whole run, or for a bridged section the part both faces
    /// back ([`backed_span`]).
    pub span: (f64, f64),
}

impl Fit {
    /// Where both legs start off the root (each face begins a gap from it),
    /// the distance along each leg at which the bead's section begins: the
    /// section is the quadrilateral from one face's first point through the
    /// toes to the other's, bridging the root opening. Zero otherwise (the
    /// root triangle, as every other joint).
    pub(super) fn bridge(&self) -> [f64; 2] {
        if self.skip[0] > 0.0 && self.skip[1] > 0.0 { self.skip } else { [0.0, 0.0] }
    }

    /// This fit carried `fraction` along `seam`: the section and the joint
    /// faces' normals where that fraction of the run starts.
    pub(super) fn carried(&self, seam: &Seam, fraction: f64) -> Fit {
        let face = |face: &JointFace| JointFace {
            normal: seam.carry(fraction, face.normal),
            gap: face.gap.map(|gap| seam.carry(fraction, gap)),
            ..face.clone()
        };
        Fit {
            faces: [face(&self.faces[0]), face(&self.faces[1])],
            legs: [seam.carry(fraction, self.legs[0]), seam.carry(fraction, self.legs[1])],
            root: seam.carry(fraction, self.root),
            skip: self.skip,
            span: self.span,
        }
    }
}

/// Why a seam has no fitted section. AUTO placement falls back to the manual
/// orientation on any of these; FITTED placement reports them.
pub(super) type NoFit = String;

/// How a seam segment runs, and so how a section is carried along it.
#[derive(Clone, Copy, Debug)]
pub(super) enum Run {
    /// Straight: the section is extruded along the tangent.
    Line,
    /// A circular arc of `angle` radians, right-handed about `axis` through
    /// `centre`: the section is revolved.
    Arc { centre: Vec3, axis: Vec3, angle: f64 },
}

#[derive(Clone, Debug)]
pub(super) struct Seam {
    pub start: Vec3,
    /// The unit tangent at the start.
    pub tangent: Vec3,
    pub length: f64,
    pub run: Run,
    /// The solid holding the seam edge, when the seam is a resident edge.
    pub owner: Option<String>,
}

/// `v` turned by `angle` radians right-handed about the unit `axis`.
fn rotate(v: Vec3, axis: Vec3, angle: f64) -> Vec3 {
    let (sin, cos) = angle.sin_cos();
    v.scale(cos).add(axis.cross(v).scale(sin)).add(axis.scale(axis.dot(v) * (1.0 - cos)))
}

impl Seam {
    pub(super) fn line(start: Vec3, tangent: Vec3, length: f64, owner: Option<String>) -> Seam {
        Seam { start, tangent, length, run: Run::Line, owner }
    }

    /// The seam a curve runs along: a straight line or a circular arc (a full
    /// circle included). `None` for any other curve.
    pub(super) fn from_curve(curve: &NurbsCurve, owner: Option<String>) -> Result<Option<Seam>, String> {
        let [t0, t1] = curve.domain()?;
        let start = curve.evaluate(t0)?;
        let end = curve.evaluate(t1)?;
        if curve.degree == 1 && curve.control_points.len() == 2 {
            let delta = end.sub(start);
            return Ok(Some(Seam::line(start, delta.normalized()?, delta.length(), owner)));
        }
        // Sampled recognition at a tolerance relative to the curve's size: an
        // arc a sketch or a primitive built is exact to rounding.
        let scale = curve.control_points.iter()
            .map(|pole| if pole.w.abs() > 1e-300 { Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w) } else { Vec3::ZERO })
            .map(|point| point.sub(start).length()).fold(1.0_f64, f64::max);
        let Some(circle) = crate::recognize_circle(curve, t0, t1, 1e-9 * scale) else { return Ok(None) };
        // The axis turns with the curve: its start tangent is `axis × radius`.
        let radial = start.sub(circle.centre);
        let tangent = curve.unit_tangent(t0, t0, t1)?;
        let axis = if circle.axis.cross(radial).dot(tangent) >= 0.0 { circle.axis } else { circle.axis.scale(-1.0) };
        let to = end.sub(circle.centre);
        let mut angle = axis.dot(radial.cross(to)).atan2(radial.dot(to));
        if angle <= 1e-12 {
            angle += std::f64::consts::TAU;
        }
        let tangent = axis.cross(radial).normalized()?;
        Ok(Some(Seam { start, tangent, length: circle.radius * angle, run: Run::Arc { centre: circle.centre, axis, angle }, owner }))
    }

    pub(super) fn at(&self, fraction: f64) -> Vec3 {
        match self.run {
            Run::Line => self.start.add(self.tangent.scale(self.length * fraction)),
            Run::Arc { centre, axis, angle } => centre.add(rotate(self.start.sub(centre), axis, angle * fraction)),
        }
    }

    /// A direction fixed in the section at the start, carried to `fraction`.
    pub(super) fn carry(&self, fraction: f64, direction: Vec3) -> Vec3 {
        match self.run {
            Run::Line => direction,
            Run::Arc { axis, angle, .. } => rotate(direction, axis, angle * fraction),
        }
    }

    /// The stretch of this run from `from` to `to` (fractions of it) as a run
    /// of its own.
    pub(super) fn part(&self, from: f64, to: f64) -> Seam {
        let run = match self.run {
            Run::Line => Run::Line,
            Run::Arc { centre, axis, angle } => Run::Arc { centre, axis, angle: angle * (to - from) },
        };
        Seam { start: self.at(from), tangent: self.carry(from, self.tangent), length: self.length * (to - from), run, owner: self.owner.clone() }
    }

    pub(super) fn end_tangent(&self) -> Vec3 {
        self.carry(1.0, self.tangent)
    }

    pub(super) fn is_line(&self) -> bool {
        matches!(self.run, Run::Line)
    }

    fn tolerance(&self) -> f64 {
        1e-6_f64.max(self.length * 1e-12)
    }
}

/// Where a straight run's bead is cut at a cornered join: the mitre plane
/// (a point and its normal, pointing along the seam) at each end, and how far
/// the run is extended past that end so the cut has material to trim.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct Trim {
    pub ends: [Option<(Vec3, Vec3, f64)>; 2],
}

/// The section `points` (a closed polygon at the seam's start, square to it)
/// carried along the seam: extruded along a straight run (and mitred where
/// `trim` says), revolved along an arc.
pub(super) fn sweep(seam: &Seam, points: &[Vec3], trim: &Trim) -> Result<crate::BrepSolid, String> {
    sweep_section(seam, points, None, trim)
}

/// A circular arc from `a` to `b` in the plane of `a`, `b` and `root`,
/// bulging `height` away from `root` (negative: towards it) at its middle:
/// its centre, radius, the angle it turns through (more than a half turn
/// where the height exceeds half the chord) and the point at its middle.
pub(super) fn contour_arc(root: Vec3, a: Vec3, b: Vec3, height: f64) -> Result<(Vec3, f64, f64, Vec3), String> {
    let chord = b.sub(a);
    let half = chord.length() * 0.5;
    let middle = a.add(chord.scale(0.5));
    // Away from the root, square to the chord, in the section's plane.
    let toward = middle.sub(root);
    let out = toward.sub(chord.scale(toward.dot(chord) / chord.dot(chord))).normalized()?;
    let depth = height.abs();
    let radius = (half * half + depth * depth) / (2.0 * depth);
    let bulge = if height > 0.0 { out } else { out.scale(-1.0) };
    // The centre stands `radius − depth` back from the chord (past it, for
    // more than a half turn).
    let centre = middle.sub(bulge.scale(radius - depth));
    let angle = 2.0 * half.atan2(radius - depth);
    Ok((centre, radius, angle, middle.add(bulge.scale(depth))))
}

/// How far the bead sections (root offset, then the toe offsets from the
/// root) reach from the seam, a convex face's whole circle included (a
/// bound past the arc itself).
pub(super) fn section_reach(sections: &[[Vec3; 3]], contour: Option<f64>) -> Result<f64, String> {
    let mut reach = 0.0_f64;
    for [root, a, b] in sections {
        reach = reach.max(root.length()).max(root.add(*a).length()).max(root.add(*b).length());
        // A concave arc stays inside the section's triangle.
        if let Some(height) = contour.filter(|height| *height > 0.0) {
            let (centre, radius, _, _) = contour_arc(*root, root.add(*a), root.add(*b), height)?;
            reach = reach.max(centre.length() + radius);
        }
    }
    Ok(reach)
}

/// [`sweep`] of a three-point bead section (root, toe, toe) whose face from
/// the first toe to the second is the circular arc [`contour_arc`] of
/// `contour` height when one is given.
pub(super) fn sweep_section(seam: &Seam, points: &[Vec3], contour: Option<f64>, trim: &Trim) -> Result<crate::BrepSolid, String> {
    let mut outline = Vec::with_capacity(points.len());
    for i in 0..points.len() {
        let (from, to) = (points[i], points[(i + 1) % points.len()]);
        match contour {
            Some(height) if i == 1 && points.len() == 3 => {
                let (centre, _, _, apex) = contour_arc(points[0], from, to, height)?;
                outline.push(Side::Arc { from, to, centre, through: apex });
            }
            _ => outline.push(Side::Line(from, to)),
        }
    }
    sweep_outline(seam, &outline, trim)
}

/// [`sweep_section`] of a bridged section `[first point on face 1, toe 1,
/// toe 2, first point on face 2]` whose legs meet at `root` (off the section):
/// the face between the toes is the contour arc as for the root triangle.
fn sweep_bridged(seam: &Seam, root: Vec3, points: [Vec3; 4], contour: Option<f64>, trim: &Trim) -> Result<crate::BrepSolid, String> {
    let mut outline = Vec::with_capacity(4);
    for i in 0..4 {
        let (from, to) = (points[i], points[(i + 1) % 4]);
        match contour {
            Some(height) if i == 1 => {
                let (centre, _, _, apex) = contour_arc(root, from, to, height)?;
                outline.push(Side::Arc { from, to, centre, through: apex });
            }
            _ => outline.push(Side::Line(from, to)),
        }
    }
    sweep_outline(seam, &outline, trim)
}

/// One side of a closed section outline at a run's start, square to it.
#[derive(Clone, Copy, Debug)]
pub(super) enum Side {
    Line(Vec3, Vec3),
    /// A circular arc about `centre` from `from` to `to`, through `through`
    /// (any point of it strictly between the ends).
    Arc { from: Vec3, to: Vec3, centre: Vec3, through: Vec3 },
}

impl Side {
    fn moved(self, shift: Vec3) -> Side {
        match self {
            Side::Line(a, b) => Side::Line(a.add(shift), b.add(shift)),
            Side::Arc { from, to, centre, through } => Side::Arc { from: from.add(shift), to: to.add(shift), centre: centre.add(shift), through: through.add(shift) },
        }
    }

    fn curve(self) -> Result<NurbsCurve, String> {
        match self {
            Side::Line(a, b) => crate::make_line(a, b),
            Side::Arc { from, to, centre, through } => {
                let radius = from.sub(centre).length();
                let x_axis = from.sub(centre).normalized()?;
                // The turn from `from` that passes `through`: its plane's
                // normal, then the angle to `to` measured that way round.
                let mut normal = x_axis.cross(through.sub(centre));
                let toward = to.sub(centre);
                if normal.length() <= 1e-12 * radius {
                    return Err("an arc's middle point is opposite its start".into());
                }
                normal = normal.normalized()?;
                let y_axis = normal.cross(x_axis);
                let mut angle = toward.dot(y_axis).atan2(toward.dot(x_axis));
                if angle <= 0.0 {
                    angle += std::f64::consts::TAU;
                }
                crate::make_arc(centre, x_axis, y_axis, radius, 0.0, angle)
            }
        }
    }
}

/// The closed outline `sides` carried along the seam: extruded along a
/// straight run (and mitred where `trim` says), revolved along an arc.
pub(super) fn sweep_outline(seam: &Seam, sides: &[Side], trim: &Trim) -> Result<crate::BrepSolid, String> {
    match seam.run {
        Run::Line => {
            let before = trim.ends[0].map_or(0.0, |(_, _, extend)| extend);
            let after = trim.ends[1].map_or(0.0, |(_, _, extend)| extend);
            let shift = seam.tangent.scale(-before);
            let profile = sides.iter().map(|side| side.moved(shift).curve()).collect::<Result<Vec<_>, _>>()?;
            let mut solid = crate::extrude_profile_brep(&profile, seam.tangent, seam.length + before + after)
                .map_err(|error| error.to_string())?;
            for (end, cut) in trim.ends.iter().enumerate() {
                let Some((point, normal, _)) = cut else { continue };
                let (below, above) = crate::split_solid_by_plane(&solid, *point, *normal)
                    .map_err(|error| format!("could not mitre the bead: {error}"))?;
                // The start cut keeps what lies ahead of it, the end cut what lies behind.
                solid = if end == 0 { above } else { below };
            }
            Ok(solid)
        }
        Run::Arc { centre, axis, angle } => {
            if trim.ends.iter().any(Option::is_some) {
                return Err("an arc is never mitred".into());
            }
            let profile = sides.iter().map(|side| side.curve()).collect::<Result<Vec<_>, _>>()?;
            crate::revolve_profile_brep(&profile, centre, axis, angle)
        }
    }
}

fn with_face<T>(handle: u32, face_id: u64, f: impl FnOnce(&FaceRecord) -> Result<T, String>) -> Result<T, String> {
    crate::with_registered_solid_str(handle, |solid| {
        let face = solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == face_id)
            .ok_or_else(|| format!("face {face_id} is no longer resident"))?;
        f(face)
    })
}

pub(super) fn face_class(face: &FaceRecord, point: Vec3, tolerance: f64) -> Result<Option<PolygonClass>, String> {
    let projection = crate::project_point_to_surface(&face.surface, point)?;
    if projection.distance > tolerance {
        return Ok(None);
    }
    crate::parameter_point_in_face(face, Vec2 { x: projection.u, y: projection.v }, tolerance).map(Some)
}

/// The face's outward normal at the seam's start if the seam lies on it along
/// its whole length, inside or on its trim, and the normal is carried with the
/// section: constant along a straight run, turning about an arc's axis.
fn carries_seam(face: &FaceRecord, seam: &Seam) -> Result<Option<Vec3>, String> {
    let tolerance = seam.tolerance();
    let mut normal: Option<Vec3> = None;
    for fraction in STATIONS {
        let point = seam.at(fraction);
        if !matches!(face_class(face, point, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
            return Ok(None);
        }
        let (_, outward) = crate::fillet::face_plane_normal(face, point).map_err(|refusal| refusal.to_string())?;
        match normal {
            None => normal = Some(outward),
            // A face that turns against the section is not a joint face.
            Some(first) => {
                let carried = seam.carry(fraction, first);
                if carried.cross(outward).length() > 1e-9 || carried.dot(outward) < 0.0 {
                    return Ok(None);
                }
            }
        }
    }
    Ok(normal)
}

/// An axis-aligned box around the body. A NURBS curve or surface lies in the
/// convex hull of its poles, so the poles of every edge and every face carrier
/// bound the body, curved face interiors included.
fn bounds(solid: &crate::BrepSolid) -> (Vec3, Vec3) {
    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
    let edge_poles = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
    let face_poles = solid.shells.iter().flat_map(|shell| &shell.faces)
        .flat_map(|face| face.surface.control_points.iter().flatten());
    for pole in edge_poles.chain(face_poles) {
        let w = if pole.w.abs() > 1e-300 { pole.w } else { 1.0 };
        let p = Vec3::new(pole.x / w, pole.y / w, pole.z / w);
        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));
    }
    (low, high)
}

fn solid_bounds_contain(solid: &crate::BrepSolid, points: &[Vec3], tolerance: f64) -> bool {
    let (low, high) = bounds(solid);
    points.iter().all(|p| {
        p.x >= low.x - tolerance && p.y >= low.y - tolerance && p.z >= low.z - tolerance
            && p.x <= high.x + tolerance && p.y <= high.y + tolerance && p.z <= high.z + tolerance
    })
}

/// A bead built by a weld feature (every face a bead face) offers no joint
/// faces to another weld; a body a bead was merged into still does. Every
/// body, beads included, is an obstacle to the bead.
fn is_weld_bead(solid: &crate::BrepSolid) -> bool {
    solid.shells.iter().flat_map(|shell| &shell.faces)
        .all(|face| face.name.as_deref().is_some_and(|name| name.contains(":BeadFace")))
}

/// Whether scene solid `name` is one of weld `weld`'s own beads (`{weld}`,
/// or `{weld}:Bead{n}` for a bead in several bodies).
pub(super) fn owned_by(name: &str, weld: &str) -> bool {
    name == weld || name.strip_prefix(weld).is_some_and(|rest| rest.starts_with(":Bead"))
}

/// Every resident face that carries the seam, in scene-name order.
fn candidates(scene: &SceneMap, seam: &Seam, exclude: &str) -> Result<Vec<JointFace>, String> {
    let ends = [seam.at(0.0), seam.at(1.0)];
    let mut names: Vec<(&String, &u32)> = scene.solids.iter().filter(|(name, _)| !owned_by(name, exclude)).collect();
    names.sort();
    let mut found = Vec::new();
    for (solid_name, &handle) in names {
        let faces = crate::with_registered_solid_str(handle, |solid| {
            if is_weld_bead(solid) || !solid_bounds_contain(solid, &ends, seam.tolerance()) {
                return Ok(Vec::new());
            }
            let mut faces = Vec::new();
            for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
                // A face this check cannot read (a degenerate normal at a pole,
                // a failed projection) is not a joint face; it is never fatal.
                if let Ok(Some(normal)) = carries_seam(face, seam) {
                    faces.push((face.id, face.name.clone(), normal));
                }
            }
            Ok(faces)
        })?;
        for (face_id, name, normal) in faces {
            let name = name.unwrap_or_else(|| format!("{solid_name} face {face_id}"));
            found.push(JointFace { name, solid: solid_name.clone(), handle, face_id, normal, gap: None });
        }
    }
    Ok(found)
}

/// A picked flat face standing a root gap off a straight seam: parallel to it,
/// the seam on its free side at one distance along the whole seam, and the gap
/// narrower than `widest`. `None` for any other face. Where on the face the
/// root lands depends on the other joint face (an oblique one moves it off the
/// seam's perpendicular foot), so the fit's corner probe, toe checks and the
/// support check decide that the face holds the root and its leg.
fn across_gap(scene: &SceneMap, seam: &Seam, name: &str, widest: f64) -> Result<Option<JointFace>, String> {
    if !seam.is_line() {
        return Ok(None);
    }
    let tolerance = seam.tolerance();
    for face in scene.resolve_face_group(name) {
        let found = with_face(face.handle, face.face_id, |record| {
            let mut first: Option<(Vec3, Vec3)> = None;
            for fraction in STATIONS {
                let point = seam.at(fraction);
                // The foot on the face's plane, not on its bounded carrier
                // (a projection there clamps to the patch's edge).
                let Ok((on, outward)) = crate::fillet::face_plane_normal(record, point) else { return Ok(None) };
                // Parallel to the seam, the seam outside the face.
                let gap = point.sub(on).dot(outward);
                if outward.dot(seam.tangent).abs() > 1e-9 || gap <= tolerance || gap >= widest {
                    return Ok(None);
                }
                // Flat: every pole of the carrier lies on that plane.
                let flat = record.surface.control_points.iter().flatten().all(|pole| {
                    let w = if pole.w.abs() > 1e-300 { pole.w } else { 1.0 };
                    Vec3::new(pole.x / w, pole.y / w, pole.z / w).sub(on).dot(outward).abs() <= tolerance
                });
                if !flat {
                    return Ok(None);
                }
                let offset = outward.scale(-gap);
                match first {
                    None => first = Some((offset, outward)),
                    Some((offset0, outward0)) => {
                        if offset.sub(offset0).length() > tolerance || outward.cross(outward0).length() > 1e-9 {
                            return Ok(None);
                        }
                    }
                }
            }
            Ok(first)
        })?;
        if let Some((offset, normal)) = found {
            let solid = scene.solids.iter().filter(|(_, handle)| **handle == face.handle)
                .map(|(name, _)| name.clone()).min().unwrap_or_default();
            return Ok(Some(JointFace { name: name.to_string(), solid, handle: face.handle, face_id: face.face_id, normal, gap: Some(offset) }));
        }
    }
    Ok(None)
}

/// The flat faces of the bodies offering `carriers` that stand a root gap
/// narrower than `widest` off the straight seam (see [`across_gap`]).
fn gapped_faces(scene: &SceneMap, seam: &Seam, carriers: &[JointFace], widest: f64) -> Result<Vec<JointFace>, String> {
    let mut handles: Vec<u32> = carriers.iter().map(|joint| joint.handle).collect();
    handles.sort_unstable();
    handles.dedup();
    let mut found = Vec::new();
    for handle in handles {
        let names: Vec<String> = crate::with_registered_solid_str(handle, |solid| {
            Ok(solid.shells.iter().flat_map(|shell| &shell.faces)
                .filter(|face| !carriers.iter().any(|joint| joint.handle == handle && joint.face_id == face.id))
                .filter_map(|face| face.name.clone()).collect())
        })?;
        for name in names {
            if let Some(joint) = across_gap(scene, seam, &name, widest)? {
                if joint.handle == handle {
                    found.push(joint);
                }
            }
        }
    }
    Ok(found)
}

/// Whether the named face stands a bridgeable root gap off a straight seam.
pub(super) fn bridges(scene: &SceneMap, seam: &Seam, name: &str, legs: [f64; 2]) -> Result<bool, String> {
    Ok(across_gap(scene, seam, name, legs[0].max(legs[1]))?.is_some())
}

/// Whether the named face, standing a root gap off this run, lies there:
/// the foot of the run's middle on its plane is on the face or within
/// `widest` of its boundary (a face elsewhere in that plane is not this
/// run's joint face).
fn bridges_here(scene: &SceneMap, seam: &Seam, name: &str, legs: [f64; 2]) -> Result<bool, String> {
    if !bridges(scene, seam, name, legs)? {
        return Ok(false);
    }
    let widest = legs[0].max(legs[1]);
    let tolerance = seam.tolerance();
    let middle = seam.at(0.5);
    for face in scene.resolve_face_group(name) {
        let near = crate::with_registered_solid_str(face.handle, |body| {
            let Some(record) = body.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == face.face_id) else { return Ok(false) };
            let Ok((on, normal)) = crate::fillet::face_plane_normal(record, middle) else { return Ok(false) };
            let foot = middle.sub(normal.scale(middle.sub(on).dot(normal)));
            if matches!(face_class(record, foot, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
                return Ok(true);
            }
            for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
                let Some(edge) = body.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
                for k in 0..=32 {
                    let point = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * k as f64 / 32.0)?;
                    if point.sub(foot).length() <= widest {
                        return Ok(true);
                    }
                }
            }
            Ok(false)
        })?;
        if near {
            return Ok(true);
        }
    }
    Ok(false)
}

/// The section's root for a pair: the offset from the seam to it and how far
/// each leg runs before its face begins. Across a root gap the root moves
/// along the face carrying the seam onto the gapped face's plane, backwards
/// along that face's leg; `None` when it cannot (both faces gapped, or the
/// faces too near parallel to meet).
fn root_of(pair: [&JointFace; 2], tangent: Vec3) -> Result<Option<(Vec3, [f64; 2])>, String> {
    let (gapped, carrier) = match (pair[0].gap, pair[1].gap) {
        (None, None) => return Ok(Some((Vec3::ZERO, [0.0, 0.0]))),
        (Some(_), None) => (0, 1),
        (None, Some(_)) => (1, 0),
        (Some(_), Some(_)) => return Ok(None),
    };
    let offset = pair[gapped].gap.expect("the gapped face");
    let normal = pair[gapped].normal;
    let leg = leg_direction(pair[carrier], pair[gapped], tangent)?;
    let across = leg.dot(normal);
    if across.abs() < MIN_CORNER_SIN {
        return Ok(None);
    }
    let shift = leg.scale(offset.dot(normal) / across);
    // The carrying face's leg runs from the root back across the gap.
    if shift.dot(leg) >= 0.0 {
        return Ok(None);
    }
    let mut skip = [0.0; 2];
    skip[carrier] = shift.length();
    Ok(Some((shift, skip)))
}

/// [`root_of`], with the gapped face's leg backed from where that face
/// begins. A face that holds the root (a flange edge standing a root gap off
/// the other flange's face) begins there; otherwise the root is the corner
/// of two faces that each begin a gap away from it (a corner-to-corner
/// joint's open V, between two square wall ends whose inside edges stand a
/// root opening apart) and that face's leg starts where the face does, so
/// the bead bridges the opening between the two faces' first points
/// ([`Fit::bridge`]). `None` when the face does not begin within `reach`.
fn backed_root(pair: [&JointFace; 2], seam: &Seam, probe: f64, reach: f64) -> Result<Option<(Vec3, [f64; 2])>, String> {
    let Some((root, mut skip)) = root_of(pair, seam.tangent)? else { return Ok(None) };
    let Some(gapped) = pair.iter().position(|face| face.gap.is_some()) else { return Ok(Some((root, skip))) };
    let tolerance = seam.tolerance();
    let leg = seam.carry(0.5, leg_direction(pair[gapped], pair[1 - gapped], seam.tangent)?);
    let middle = seam.at(0.5).add(seam.carry(0.5, root));
    let on = |s: f64| runs_onto(pair[gapped], middle.add(leg.scale(s)), tolerance);
    // The face holds the root (on it or its boundary): as every such joint.
    if on(0.0)? {
        return Ok(Some((root, skip)));
    }
    // The first sample on the face, then its edge by bisection. (Not from
    // the corner probe's distance: a root opening can be narrower than it.)
    const SAMPLES: usize = 64;
    let mut off = 0.0;
    for k in 1..=SAMPLES {
        let s = reach * k as f64 / SAMPLES as f64;
        if !on(s)? {
            off = s;
            continue;
        }
        let mut inside = s;
        while inside - off > tolerance * 1e-2 {
            let mid = 0.5 * (off + inside);
            if on(mid)? { inside = mid } else { off = mid }
        }
        // Exactly where the face begins: its straight edge along the seam
        // there (a bisection stops a tolerance short of it, which would leave
        // the support slab's end a sliver off the next face). A face beginning
        // at the root (within its tolerance), or with no straight edge there,
        // is read as holding it, as before (the corner probe then decides).
        let edge = edge_along(pair[gapped], middle, leg, seam.tangent, inside, tolerance)?;
        let Some(edge) = edge.filter(|edge| *edge > 10.0 * tolerance) else {
            return Ok(on(probe)?.then_some((root, skip)));
        };
        // Only a pair whose other leg is backed too: both faces begin off
        // the root, so the root is the corner of their planes in free space.
        if skip[1 - gapped] <= tolerance {
            return Ok(None);
        }
        skip[gapped] = edge;
        return Ok(Some((root, skip)));
    }
    Ok(None)
}

/// The longest stretch of a straight `seam` (fractions from its start) along
/// which each face holds its whole leg band, from where the face begins
/// (`skip`) to the toe (`sizes`), measured from the section's `root`; `None`
/// when no stretch is backed. The stretch ends where a boundary edge of a face
/// enters its band: a wall end not square to the seam, a relief's cut. Exact
/// for straight edges; a curved edge's extreme within the band is refined on
/// the curve. The whole seam (0, 1) when nothing enters the bands.
fn backed_span(seam: &Seam, faces: [&JointFace; 2], legs: [Vec3; 2], root: Vec3, skip: [f64; 2], sizes: [f64; 2]) -> Result<Option<(f64, f64)>, String> {
    let tolerance = seam.tolerance();
    let origin = seam.start.add(root);
    // Breaks along the seam (by length from its start).
    let mut breaks: Vec<f64> = Vec::new();
    for i in 0..2 {
        let (leg, low, high) = (legs[i], skip[i] + 10.0 * tolerance, sizes[i] - 10.0 * tolerance);
        let coords = |p: Vec3| { let d = p.sub(origin); (d.dot(seam.tangent), d.dot(leg)) };
        let curves: Vec<NurbsCurve> = crate::with_registered_solid_str(faces[i].handle, |solid| {
            let record = solid.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == faces[i].face_id)
                .ok_or_else(|| format!("face {} is no longer resident", faces[i].face_id))?;
            let mut curves = Vec::new();
            for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
                let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
                if edge.degenerate { continue; }
                curves.push(crate::feature_pipeline::features::common::trimmed_curve(&edge.curve, edge.t0, edge.t1)?);
            }
            Ok(curves)
        })?;
        for curve in &curves {
            let [t0, t1] = curve.domain()?;
            let at = |t: f64| -> Result<(f64, f64), String> { Ok(coords(curve.evaluate(t)?)) };
            const SAMPLES: usize = 512;
            let ts: Vec<f64> = (0..=SAMPLES).map(|k| t0 + (t1 - t0) * k as f64 / SAMPLES as f64).collect();
            let points = ts.iter().map(|t| at(*t)).collect::<Result<Vec<_>, _>>()?;
            let inside = |s: f64| s > low && s < high;
            for k in 0..SAMPLES {
                let ((f0, s0), (_, s1)) = (points[k], points[k + 1]);
                // Where the edge crosses the band's sides, by bisection on the curve.
                for bound in [low, high] {
                    if (s0 - bound) * (s1 - bound) < 0.0 {
                        let (mut a, mut b) = (ts[k], ts[k + 1]);
                        for _ in 0..80 {
                            let m = 0.5 * (a + b);
                            if (at(m)?.1 - bound) * (s0 - bound) > 0.0 { a = m } else { b = m }
                        }
                        breaks.push(at(0.5 * (a + b))?.0);
                    }
                }
                if inside(s0) {
                    breaks.push(f0);
                }
            }
            if inside(points[SAMPLES].1) {
                breaks.push(points[SAMPLES].0);
            }
            // A curved edge's extreme along the seam inside the band: refine
            // each local extreme of the samples on the curve.
            for k in 1..SAMPLES {
                let (prev, here, next) = (points[k - 1].0, points[k].0, points[k + 1].0);
                let extreme = (here >= prev && here >= next) || (here <= prev && here <= next);
                if !extreme || !inside(points[k].1) || (here - prev).abs() + (next - here).abs() <= 0.0 {
                    continue;
                }
                let maximum = here >= prev;
                let (mut a, mut b) = (ts[k - 1], ts[k + 1]);
                for _ in 0..100 {
                    let (m1, m2) = (a + (b - a) / 3.0, b - (b - a) / 3.0);
                    let (g1, g2) = (at(m1)?.0, at(m2)?.0);
                    if (g1 < g2) == maximum { a = m1 } else { b = m2 }
                }
                let (f, s) = at(0.5 * (a + b))?;
                if inside(s) {
                    breaks.push(f);
                }
            }
        }
    }
    breaks.push(0.0);
    breaks.push(seam.length);
    breaks.retain(|f| *f >= 0.0 && *f <= seam.length);
    breaks.sort_by(f64::total_cmp);
    // A stretch is backed where both bands lie on their faces at its middle.
    let backed = |f: f64| -> Result<bool, String> {
        for i in 0..2 {
            for k in 0..=16 {
                let s = skip[i] + (sizes[i] - skip[i]) * k as f64 / 16.0;
                if !runs_onto(faces[i], origin.add(seam.tangent.scale(f)).add(legs[i].scale(s)), tolerance)? {
                    return Ok(false);
                }
            }
        }
        Ok(true)
    };
    let mut best: Option<(f64, f64)> = None;
    for pair in breaks.windows(2) {
        let (a, b) = (pair[0], pair[1]);
        if b - a <= 100.0 * tolerance || best.is_some_and(|(x, y)| y - x >= b - a) {
            continue;
        }
        if backed(0.5 * (a + b))? {
            best = Some((a, b));
        }
    }
    let Some((a, b)) = best else { return Ok(None) };
    // By length from the seam's start; an end within the seam's tolerance of
    // the seam's own end is that end.
    let near = 10.0 * tolerance;
    Ok(Some((if a <= near { 0.0 } else { a }, if b >= seam.length - near { seam.length } else { b })))
}

/// The distance along `leg` from `from` to the straight edge of `face` that
/// runs along `tangent` and crosses the leg's line within ten tolerances of
/// `near`; `None` when no edge does.
fn edge_along(face: &JointFace, from: Vec3, leg: Vec3, tangent: Vec3, near: f64, tolerance: f64) -> Result<Option<f64>, String> {
    crate::with_registered_solid_str(face.handle, |solid| {
        let record = solid.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == face.face_id)
            .ok_or_else(|| format!("face {} is no longer resident", face.face_id))?;
        let mut best: Option<f64> = None;
        for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
            let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
            let (a, b) = (edge.curve.evaluate(edge.t0)?, edge.curve.evaluate(edge.t1)?);
            let Ok(along) = b.sub(a).normalized() else { continue };
            // Straight and along the seam.
            let middle = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1))?;
            if along.cross(tangent).length() > 1e-9 || middle.sub(a).cross(along).length() > tolerance {
                continue;
            }
            let d = a.sub(from);
            let s = d.dot(leg);
            let off = d.sub(leg.scale(s)).sub(along.scale(d.dot(along))).length();
            if off <= 10.0 * tolerance && (s - near).abs() <= 10.0 * tolerance && best.is_none_or(|b| (s - near).abs() < (b - near).abs()) {
                best = Some(s);
            }
        }
        Ok(best)
    })
}

/// The leg direction along `face`, on the free side of `other`.
fn leg_direction(face: &JointFace, other: &JointFace, tangent: Vec3) -> Result<Vec3, String> {
    let direction = face.normal.cross(tangent).normalized()?;
    Ok(if direction.dot(other.normal) < 0.0 { direction.scale(-1.0) } else { direction })
}

fn runs_onto(face: &JointFace, point: Vec3, tolerance: f64) -> Result<bool, String> {
    with_face(face.handle, face.face_id, |record| {
        Ok(matches!(face_class(record, point, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)))
    })
}

fn outside_solid(scene: &SceneMap, solid: &str, point: Vec3, tolerance: f64) -> Result<bool, String> {
    let handle = scene.solids.get(solid).copied().ok_or_else(|| format!("solid '{solid}' is no longer resident"))?;
    crate::with_registered_solid_str(handle, |body| {
        Ok(crate::classify_point(point, body, tolerance)?.class == PointClass::Out)
    })
}

/// Check the pair makes a corner with free space between the legs: both short
/// legs land on their faces and the wedge between them is outside every body
/// that offered a joint face.
fn corner(scene: &SceneMap, seam: &Seam, pair: [&JointFace; 2], solids: &[String], probe: f64, sizes: [f64; 2]) -> Result<Option<[Vec3; 2]>, String> {
    let reach = sizes[0].max(sizes[1]);
    if pair[0].normal.cross(pair[1].normal).length() < MIN_CORNER_SIN {
        return Ok(None);
    }
    let legs = [leg_direction(pair[0], pair[1], seam.tangent)?, leg_direction(pair[1], pair[0], seam.tangent)?];
    let Some((root, skip)) = backed_root(pair, seam, probe, reach)? else { return Ok(None) };
    let tolerance = seam.tolerance();
    let middle = seam.at(0.5).add(seam.carry(0.5, root));
    let carried = [seam.carry(0.5, legs[0]), seam.carry(0.5, legs[1])];
    for ((face, leg), skip) in pair.iter().zip(&carried).zip(skip) {
        if !runs_onto(face, middle.add(leg.scale(skip + probe)), tolerance)? {
            return Ok(None);
        }
    }
    let wedge = middle.add(carried[0].add(carried[1]).scale(probe / 3.0));
    let mut free = vec![wedge];
    if skip[0] > 0.0 && skip[1] > 0.0 {
        // A bridged section: both faces begin within the shorter leg, and
        // the opening between their first points is free space.
        if skip[0].max(skip[1]) >= sizes[0].min(sizes[1]) - tolerance {
            return Ok(None);
        }
        let opening = middle.add(carried[0].scale(skip[0])).add(middle.add(carried[1].scale(skip[1]))).scale(0.5);
        free.push(opening.add(carried[0].add(carried[1]).scale(probe / 3.0)));
    }
    for point in free {
        for solid in solids {
            if !outside_solid(scene, solid, point, tolerance * 0.1)? {
                return Ok(None);
            }
        }
    }
    Ok(Some(legs))
}

/// Find the joint along a straight or circular seam. `explicit` holds the faces the user
/// selected (in selection order, at most two). `legs` are the requested leg
/// sizes; the toe of each leg must stay on its face along the whole seam.
/// `previous`, the fit of the run before on a chain, keeps leg 1 on the face
/// leg 1 ran along there (checked before the leg sizes are).
pub(super) fn fit(scene: &SceneMap, seam: &Seam, explicit: &[String], exclude: &str, legs: [f64; 2], previous: Option<&Fit>) -> Result<Result<Fit, NoFit>, String> {
    if explicit.len() > 2 {
        return Err("select at most two joint faces".into());
    }
    let all = candidates(scene, seam, exclude)?;
    let mut chosen = Vec::new();
    for name in explicit {
        // A container name picks the member that carries the seam.
        let group = scene.resolve_face_group(name);
        if let Some(joint) = all.iter().find(|joint| group.iter().any(|face| joint.handle == face.handle && joint.face_id == face.face_id)) {
            chosen.push(JointFace { name: name.clone(), ..joint.clone() });
            continue;
        }
        // A flat face a root gap off a straight seam, narrower than the legs.
        if let Some(joint) = across_gap(scene, seam, name, legs[0].max(legs[1]))? {
            chosen.push(joint);
            continue;
        }
        return Ok(Err(format!("joint face '{name}' does not carry the seam along its whole length {}",
            if seam.is_line() { "as a flat face" } else { "square to the arc's axis or coaxial with it" })));
    }
    let mut solids: Vec<String> = all.iter().chain(chosen.iter()).map(|joint| joint.solid.clone()).collect();
    solids.sort();
    solids.dedup();
    // A picked face across a root gap pairs with the faces carrying the seam.
    let pool: Vec<JointFace> = all.iter().cloned().chain(chosen.iter().filter(|joint| joint.gap.is_some()).cloned()).collect();
    let probe = (legs[0].min(legs[1]) * 0.05).min(seam.length * 0.05).max(seam.tolerance() * 10.0);
    let mut pairs: Vec<([JointFace; 2], [Vec3; 2])> = Vec::new();
    match chosen.as_slice() {
        [first, second] => {
            if let Some(legs) = corner(scene, seam, [first, second], &solids, probe, legs)? {
                pairs.push(([first.clone(), second.clone()], legs));
            }
        }
        _ => {
            for (i, a) in pool.iter().enumerate() {
                for b in &pool[i + 1..] {
                    if let [only] = chosen.as_slice() {
                        if !(same(only, a) || same(only, b)) {
                            continue;
                        }
                    }
                    if corner(scene, seam, [a, b], &solids, probe, legs)?.is_some() {
                        let [f0, f1] = order(seam, chosen.first(), [a, b]);
                        let legs = [leg_direction(&f0, &f1, seam.tangent)?, leg_direction(&f1, &f0, seam.tangent)?];
                        pairs.push(([f0, f1], legs));
                    }
                }
            }
        }
    }
    // A seam with no corner along it: the inside edge of a square wall end at
    // a corner-to-corner joint. The other wall's face a root opening away is
    // found on the same body; only a pair whose legs are both backed off the
    // root is taken (the open V outside, or the inside corner: one picked face
    // chooses), so every other joint reads as before.
    if pairs.is_empty() && chosen.len() <= 1 && chosen.iter().all(|only| only.gap.is_none()) && seam.is_line() {
        let widest = legs[0].max(legs[1]);
        for gapped in gapped_faces(scene, seam, &all, widest)? {
            for carrier in &all {
                let bridged = backed_root([carrier, &gapped], seam, probe, widest)?
                    .is_some_and(|(_, skip)| skip[0] > 0.0 && skip[1] > 0.0);
                let wanted = chosen.first().is_none_or(|only| same(only, carrier));
                if wanted && bridged && corner(scene, seam, [carrier, &gapped], &solids, probe, legs)?.is_some() {
                    let [f0, f1] = order(seam, chosen.first(), [carrier, &gapped]);
                    let legs = [leg_direction(&f0, &f1, seam.tangent)?, leg_direction(&f1, &f0, seam.tangent)?];
                    pairs.push(([f0, f1], legs));
                }
            }
        }
    }
    let ([mut first, mut second], mut legs_dir) = match pairs.len() {
        0 if all.is_empty() => return Ok(Err(if seam.is_line() {
            "no face carries the seam as a flat face".into()
        } else {
            "no face carries the arc square to its axis or coaxial with it".into()
        })),
        0 => return Ok(Err(format!(
            "no concave corner along the seam between faces {}", list(&all)))),
        1 => pairs.pop().expect("one pair"),
        _ => return Ok(Err(format!(
            "several corners meet at the seam ({}); select the two joint faces",
            pairs.iter().map(|(faces, _)| format!("{} + {}", faces[0].name, faces[1].name)).collect::<Vec<_>>().join(", ")))),
    };
    if let Some(previous) = previous {
        if first.same(&previous.faces[1]) || second.same(&previous.faces[0]) {
            std::mem::swap(&mut first, &mut second);
            legs_dir.swap(0, 1);
        }
    }
    let tolerance = seam.tolerance();
    let Some((root, skip)) = backed_root([&first, &second], seam, probe, legs[0].max(legs[1]))? else {
        return Ok(Err(format!("no root across the gap between faces {} and {}", first.name, second.name)));
    };
    // A bridged section runs along the stretch both faces back: a wall end
    // that is not square to the seam (unequal bend angles), or one a relief
    // cuts, ends the bead short of the seam's ends.
    let span = if skip[0] > 0.0 && skip[1] > 0.0 && seam.is_line() {
        let refused = || format!("faces {} and {} back no stretch of the seam together", first.name, second.name);
        let Some((a, b)) = backed_span(seam, [&first, &second], legs_dir, root, skip, legs)? else { return Ok(Err(refused())) };
        // A trimmed end stands inside the faces by the weld's resolvable band
        // (a hundred weld floors, the support check's depth), more where a
        // face's edge meets it at a slant and the material under the leg runs
        // out before the face does; so may an end of the seam itself. The
        // first stretch whose exact support check holds: the backed stretch
        // as found, then both ends inset by a band, two, four, ...
        let base = 100.0 * crate::tolerance::WELD_FLOOR;
        let mut found = None;
        for k in 0..=8 {
            let inset = |end: f64, own: f64| if k == 0 { if end == own { 0.0 } else { base } } else { base * f64::powi(2.0, k) };
            let (from, to) = (a + inset(a, 0.0), b - inset(b, seam.length));
            if to - from <= base {
                break;
            }
            let span = (from / seam.length, to / seam.length);
            let trial = Fit { faces: [first.clone(), second.clone()], legs: legs_dir, root, skip, span };
            if supported(&seam.part(span.0, span.1), &trial, legs, &Trim { ends: [None, None] })?.is_ok() {
                found = Some(if from == 0.0 && to == seam.length { (0.0, 1.0) } else { span });
                break;
            }
        }
        match found {
            Some(span) => span,
            None => return Ok(Err(refused())),
        }
    } else {
        (0.0, 1.0)
    };
    let along = seam.part(span.0, span.1);
    for (((face, leg), size), skip) in [&first, &second].iter().zip(&legs_dir).zip(legs).zip(skip) {
        if size <= skip + tolerance {
            return Ok(Err(format!("leg {size} does not reach across the {skip} root gap onto joint face {}", face.name)));
        }
        for fraction in STATIONS {
            let toe = along.at(fraction).add(along.carry(fraction, root.add(leg.scale(size))));
            if !runs_onto(face, toe, tolerance)? {
                return Ok(Err(format!("leg {size} runs off joint face {}", face.name)));
            }
        }
    }
    Ok(Ok(Fit { faces: [first, second], legs: legs_dir, root, skip, span }))
}

// The far side of a fitted joint on one run: the mirror corner across the
// member standing on the joint (a T joint's web, a tube's wall). One joint
// face is the member's; the nearest face of the member's body straight
// across it (its outward normal opposite, at the member's thickness) meets
// the other, through face along the run carried across that thickness.
// Leg 1 stays on the through face when it is there on the near side, else
// on the member's far face. [`Chain::far_side`] joins the far runs of a
// chain.

/// A run's far side before it is fitted: the seam carried across the member
/// (`member` indexes the near fit's faces) and the member's far face.
#[derive(Clone, Debug)]
pub(super) struct FarRun {
    pub seam: Seam,
    member: usize,
    far_id: u64,
}

/// Find the far run of one fitted run: for each joint face as the member,
/// the nearest face of its body straight across it (outward normal opposite,
/// at the member's thickness) carries the seam carried across that
/// thickness, and the through face holds that far seam (on it, or a root gap
/// off it). Exactly one joint face may be the member.
pub(super) fn far_run(scene: &SceneMap, seam: &Seam, near: &Fit, legs: [f64; 2]) -> Result<Result<FarRun, NoFit>, String> {
    let tolerance = seam.tolerance();
    let mut found: Vec<FarRun> = Vec::new();
    for member in 0..2 {
        let face = &near.faces[member];
        let through = &near.faces[1 - member];
        // The member carries the seam; a face a root gap off it is the
        // through face (the plate the member stands the gap above).
        if face.gap.is_some() {
            continue;
        }
        // A point on the member's face halfway along the seam, halfway up the
        // part of its leg the face carries (past any root gap it crosses).
        let up = near.skip[member] + (legs[member] - near.skip[member]) * 0.5;
        let point = seam.at(0.5).add(seam.carry(0.5, near.root.add(near.legs[member].scale(up))));
        let inward = seam.carry(0.5, face.normal).scale(-1.0);
        let far = crate::with_registered_solid_str(face.handle, |solid| {
            let mut best: Option<(f64, u64)> = None;
            for record in solid.shells.iter().flat_map(|shell| &shell.faces) {
                if record.id == face.face_id {
                    continue;
                }
                let Ok((foot, outward)) = crate::fillet::face_plane_normal(record, point) else { continue };
                let across = foot.sub(point);
                let thickness = across.dot(inward);
                if thickness <= tolerance || across.sub(inward.scale(thickness)).length() > tolerance
                    || outward.dot(inward) < 1.0 - 1e-9 {
                    continue;
                }
                if !matches!(face_class(record, foot, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
                    continue;
                }
                if best.is_none_or(|(nearest, _)| thickness < nearest) {
                    best = Some((thickness, record.id));
                }
            }
            Ok(best)
        })?;
        let Some((thickness, far_id)) = far else { continue };
        // The seam carried across the member: along an arc the far run is
        // the coaxial arc at the far face's radius.
        let shift = face.normal.scale(-thickness);
        let start = seam.start.add(shift);
        let far_seam = match seam.run {
            Run::Line => Seam::line(start, seam.tangent, seam.length, None),
            Run::Arc { centre, axis, angle } => {
                let radial = start.sub(centre);
                let radius = radial.sub(axis.scale(radial.dot(axis))).length();
                if radius <= tolerance {
                    continue;
                }
                Seam { start, tangent: seam.tangent, length: radius * angle, run: seam.run, owner: None }
            }
        };
        // The through face holds the far seam's middle: on it, or (a gapped
        // through face) the root gap off it.
        let holds = if through.gap.is_some() {
            across_gap(scene, &far_seam, &through.name, legs[0].max(legs[1]))?.is_some()
        } else {
            runs_onto(through, far_seam.at(0.5), tolerance)?
        };
        if holds {
            found.push(FarRun { seam: far_seam, member, far_id });
        }
    }
    Ok(match found.len() {
        0 => Err("no far-side corner: neither joint face belongs to a member with a face straight across it on the other face".into()),
        1 => Ok(found.pop().expect("one far side")),
        _ => Err("both joint faces belong to members that continue past the joint; weld the far side's seam as its own weld".into()),
    })
}

/// Fit a far run (its seam as found, or trimmed to a chain's corners): the
/// member's far face and the through face, in the near fit's leg order.
pub(super) fn fit_far(scene: &SceneMap, far: &FarRun, near: &Fit, exclude: &str, legs: [f64; 2]) -> Result<Result<Fit, NoFit>, String> {
    let face = &near.faces[far.member];
    let through = &near.faces[1 - far.member];
    let joints = candidates(scene, &far.seam, exclude)?;
    let Some(far_face) = joints.iter().find(|joint| joint.handle == face.handle && joint.face_id == far.far_id) else {
        return Ok(Err("the member's far face does not carry the far side's seam".into()));
    };
    // A through face across a root gap is picked by name: the fit finds it
    // the gap off the far seam too.
    let through_name = if through.gap.is_some() {
        through.name.clone()
    } else {
        let Some(through_face) = joints.iter().find(|joint| same(joint, through)) else {
            return Ok(Err(format!("joint face {} does not carry the far side's seam", through.name)));
        };
        through_face.name.clone()
    };
    let picks = if far.member == 0 { [far_face.name.clone(), through_name] } else { [through_name, far_face.name.clone()] };
    fit(scene, &far.seam, &picks, exclude, legs, None)
}

/// Does the named face carry the whole seam (on or inside its trim)?
pub(super) fn carries(scene: &SceneMap, seam: &Seam, name: &str) -> Result<bool, String> {
    for face in scene.resolve_face_group(name) {
        if with_face(face.handle, face.face_id, |record| carries_any(record, seam))? {
            return Ok(true);
        }
    }
    Ok(false)
}

fn carries_any(face: &FaceRecord, seam: &Seam) -> Result<bool, String> {
    let tolerance = seam.tolerance();
    for fraction in STATIONS {
        if !matches!(face_class(face, seam.at(fraction), tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
            return Ok(false);
        }
    }
    Ok(true)
}

fn same(a: &JointFace, b: &JointFace) -> bool {
    a.handle == b.handle && a.face_id == b.face_id
}

fn list(faces: &[JointFace]) -> String {
    faces.iter().map(|face| face.name.as_str()).collect::<Vec<_>>().join(", ")
}

/// Leg 1 goes on the selected face, else on the seam owner's face, else on
/// the face whose name sorts first, so unequal legs never swap on rebuild.
fn order(seam: &Seam, selected: Option<&JointFace>, pair: [&JointFace; 2]) -> [JointFace; 2] {
    let first_wins = match selected {
        Some(selected) => same(selected, pair[0]) || !same(selected, pair[1]),
        None => {
            let owned = |face: &JointFace| seam.owner.as_deref() == Some(face.solid.as_str());
            match (owned(pair[0]), owned(pair[1])) {
                (true, false) => true,
                (false, true) => false,
                _ => (&pair[0].name, &pair[0].solid) <= (&pair[1].name, &pair[1].solid),
            }
        }
    };
    if first_wins { [pair[0].clone(), pair[1].clone()] } else { [pair[1].clone(), pair[0].clone()] }
}

/// Joins closer to straight than this (1 − cos of the turn) are tangent: the
/// two segments share the section there.
const TANGENT_JOIN: f64 = 1e-9;
/// A mitre plane must cut the runs it trims at least this squarely (cosine of
/// half the turn): past it the seam folds back on itself (about 168.5°, the
/// sweep's own mitre limit).
const MITRE_FLOOR: f64 = 0.1;

/// A seam of straight runs and circular arcs, head to tail, with the mitre
/// plane at each cornered join.
pub(super) struct Chain {
    pub runs: Vec<Seam>,
    /// `corners[k]`: the join after run `k` (the closing one last on a closed
    /// chain) as the mitre plane's point and forward normal, or `None` where
    /// the runs meet tangent.
    corners: Vec<(usize, usize, Option<(Vec3, Vec3)>)>,
}

impl Chain {
    /// Classify the joins of `runs` (ordered head to tail). A corner is
    /// mitred between two straight runs; a corner at an arc, or a turn that
    /// folds the seam back on itself, has no bead.
    pub(super) fn new(runs: Vec<Seam>) -> Result<Chain, NoFit> {
        let count = runs.len();
        let tolerance = runs.iter().map(Seam::tolerance).fold(0.0, f64::max);
        let closed = count > 1 && runs[count - 1].at(1.0).sub(runs[0].start).length() <= tolerance * 10.0;
        let mut corners = Vec::new();
        let joins: Vec<(usize, usize)> = (0..count.saturating_sub(1)).map(|k| (k, k + 1))
            .chain(closed.then(|| (count - 1, 0))).collect();
        let name = |k: usize| k + 1;
        for (a, b) in joins {
            let (out, into) = (runs[a].end_tangent(), runs[b].tangent);
            if out.dot(into) >= 1.0 - TANGENT_JOIN {
                corners.push((a, b, None));
                continue;
            }
            if !(runs[a].is_line() && runs[b].is_line()) {
                return Err(format!("segments {} and {} meet at a corner on an arc; a bead is mitred only between straight segments", name(a), name(b)));
            }
            let normal = out.add(into).normalized().map_err(|_| format!("the seam doubles back where segments {} and {} meet", name(a), name(b)))?;
            if out.dot(normal) < MITRE_FLOOR {
                return Err(format!("the seam turns back too sharply where segments {} and {} meet for a mitred bead", name(a), name(b)));
            }
            corners.push((a, b, Some((runs[b].start, normal))));
        }
        Ok(Chain { runs, corners })
    }

    pub(super) fn is_single_line(&self) -> bool {
        self.runs.len() == 1 && self.runs[0].is_line()
    }

    fn label(&self, k: usize) -> String {
        if self.runs.len() == 1 { String::new() } else { format!("segment {}: ", k + 1) }
    }

    /// The mitre cut at each end of each run, for a section reaching `reach`
    /// from the seam. A run too short for its two mitres has no bead.
    pub(super) fn trims(&self, reach: f64) -> Result<Vec<Trim>, NoFit> {
        let mut trims = vec![Trim::default(); self.runs.len()];
        let mut taken = vec![0.0_f64; self.runs.len()];
        for (a, b, corner) in &self.corners {
            let Some((point, normal)) = corner else { continue };
            let cos_half = self.runs[*b].tangent.dot(*normal);
            // A section point `w` off the seam meets the plane `w·tan(θ/2)`
            // from the join at most; extend past that before cutting.
            let tan_half = (1.0 - cos_half * cos_half).max(0.0).sqrt() / cos_half;
            let extend = reach * tan_half * 2.0 + reach * 0.01;
            trims[*a].ends[1] = Some((*point, *normal, extend));
            trims[*b].ends[0] = Some((*point, *normal, extend));
            taken[*a] += reach * tan_half;
            taken[*b] += reach * tan_half;
        }
        for (k, run) in self.runs.iter().enumerate() {
            if taken[k] >= run.length {
                return Err(format!("{}the segment is too short for the bead's mitred corners", self.label(k)));
            }
        }
        Ok(trims)
    }

    /// Fit every run. Leg 1 stays on the same face from run to run (fitting
    /// starts at the run carrying the first picked face and works outward
    /// both ways, each run ordered by its fitted neighbour), and where runs
    /// meet tangent their sections must agree.
    pub(super) fn fit(&self, scene: &SceneMap, explicit: &[String], exclude: &str, legs: [f64; 2]) -> Result<Result<Vec<Fit>, NoFit>, String> {
        let count = self.runs.len();
        // On a chain a picked face joins the runs it carries.
        let mut picked: Vec<Vec<String>> = Vec::with_capacity(count);
        for run in &self.runs {
            if count == 1 {
                picked.push(explicit.to_vec());
                continue;
            }
            let mut names = Vec::new();
            for name in explicit {
                // A picked face joins a run it carries, or one it stands a
                // root gap off (a straight run, the gap narrower than the legs).
                if carries(scene, run, name)? || bridges_here(scene, run, name, legs)? {
                    names.push(name.clone());
                }
            }
            picked.push(names);
        }
        let start = explicit.first()
            .and_then(|first| picked.iter().position(|names| names.first() == Some(first)))
            .unwrap_or(0);
        let order: Vec<(usize, Option<usize>)> = std::iter::once((start, None))
            .chain((start + 1..count).map(|k| (k, Some(k - 1))))
            .chain((0..start).rev().map(|k| (k, Some(k + 1))))
            .collect();
        let mut fitted: Vec<Option<Fit>> = vec![None; count];
        for (k, neighbour) in order {
            let next = neighbour.and_then(|n| fitted[n].as_ref());
            match fit(scene, &self.runs[k], &picked[k], exclude, legs, next)? {
                Ok(joint) => fitted[k] = Some(joint),
                Err(reason) => return Ok(Err(format!("{}{reason}", self.label(k)))),
            }
        }
        let fits: Vec<Fit> = fitted.into_iter().map(|fit| fit.expect("every run fitted")).collect();
        // A bead trimmed to the stretch its faces back is a single run's.
        if count > 1 && fits.iter().any(|fit| fit.span != (0.0, 1.0)) {
            return Ok(Err("the joint faces back only part of a segment of a seam of several segments".into()));
        }
        for (a, b, corner) in &self.corners {
            if corner.is_some() {
                continue;
            }
            let tolerance = self.runs[*a].tolerance().max(self.runs[*b].tolerance()) * 10.0;
            let roots = [self.runs[*a].carry(1.0, fits[*a].root), fits[*b].root];
            if roots[0].sub(roots[1]).length() > tolerance {
                return Ok(Err(format!("the joint changes where segments {} and {} meet", a + 1, b + 1)));
            }
            for (i, size) in legs.iter().enumerate() {
                let end = self.runs[*a].carry(1.0, fits[*a].legs[i]).scale(*size);
                let start = fits[*b].legs[i].scale(*size);
                if end.sub(start).length() > tolerance {
                    return Ok(Err(format!("the joint changes where segments {} and {} meet", a + 1, b + 1)));
                }
            }
        }
        Ok(Ok(fits))
    }

    /// The mitre cuts moved onto the bead's root: where a section's root
    /// stands off the seam (across a root gap), the two runs' root lines meet
    /// past the seam's corner, and the mitre plane passes through that point
    /// (its normal, the bisector, unchanged). `roots[k]` is run `k`'s root
    /// offset at its start. Refused where the root lines do not meet.
    pub(super) fn rooted(&self, trims: &[Trim], roots: &[Vec3]) -> Result<Vec<Trim>, NoFit> {
        let mut trims = trims.to_vec();
        for (a, b, corner) in &self.corners {
            let Some((point, normal)) = corner else { continue };
            let (ra, rb) = (self.runs[*a].carry(1.0, roots[*a]), roots[*b]);
            if ra.length() == 0.0 && rb.length() == 0.0 {
                continue;
            }
            let tolerance = self.runs[*a].tolerance().max(self.runs[*b].tolerance()) * 10.0;
            let Some(meet) = meet(point.add(ra), self.runs[*a].end_tangent(), point.add(rb), self.runs[*b].tangent, tolerance) else {
                return Err(format!("the bead's root steps where segments {} and {} meet (a root gap on one of them only, or of different widths)", a + 1, b + 1));
            };
            let moved = meet.sub(*point).length();
            for (run, end) in [(*a, 1), (*b, 0)] {
                if let Some((_, _, extend)) = trims[run].ends[end] {
                    trims[run].ends[end] = Some((meet, *normal, extend + 2.0 * moved));
                }
            }
        }
        Ok(trims)
    }

    /// The far side of every run (its mirror corner across the member
    /// standing on the joint), joined into the far seam's chain: the far
    /// runs of a mitred corner trimmed or extended to where they meet, those
    /// of a tangent join meeting end to start. Returned with each far run's fit.
    pub(super) fn far_side(&self, scene: &SceneMap, fits: &[Fit], exclude: &str, legs: [f64; 2]) -> Result<Result<(Chain, Vec<Fit>), NoFit>, String> {
        let mut fars: Vec<FarRun> = Vec::new();
        for (k, run) in self.runs.iter().enumerate() {
            match far_run(scene, run, &fits[k], legs)? {
                Ok(far) => fars.push(far),
                Err(reason) => return Ok(Err(format!("{}{reason}", self.label(k)))),
            }
        }
        let runs: Vec<Seam> = fars.iter().map(|far| far.seam.clone()).collect();
        let runs = match self.rejoined(runs) {
            Some(runs) => runs,
            None => return Ok(Err("the far side's segments do not meet again at the member's corners".into())),
        };
        let mut far_fits = Vec::new();
        for (k, (far, run)) in fars.iter_mut().zip(runs.iter()).enumerate() {
            far.seam = run.clone();
            match fit_far(scene, far, &fits[k], exclude, legs)? {
                Ok(joint) => far_fits.push(joint),
                Err(reason) => return Ok(Err(format!("{}no far-side corner: {reason}", self.label(k)))),
            }
        }
        Ok(Chain::new(runs).map(|chain| (chain, far_fits)))
    }

    /// Runs moved off this chain's (one per run, each straight or circular
    /// as before) joined again at this chain's joins: the straight runs of a
    /// mitred corner trimmed or extended to where their lines meet (every
    /// corner's point found first, so a short run between two corners is
    /// measured between both), and tangent joins checked to run on. `None`
    /// where moved lines no longer meet or a run is left with no length.
    fn rejoined(&self, mut runs: Vec<Seam>) -> Option<Vec<Seam>> {
        let count = runs.len();
        let (mut starts, mut ends): (Vec<Option<Vec3>>, Vec<Option<Vec3>>) = (vec![None; count], vec![None; count]);
        for (a, b, corner) in &self.corners {
            let tolerance = runs[*a].tolerance().max(runs[*b].tolerance()) * 10.0;
            match corner {
                None => {
                    if runs[*a].at(1.0).sub(runs[*b].start).length() > tolerance {
                        return None;
                    }
                }
                Some(_) => {
                    let point = meet(runs[*a].start, runs[*a].tangent, runs[*b].start, runs[*b].tangent, tolerance)?;
                    ends[*a] = Some(point);
                    starts[*b] = Some(point);
                }
            }
        }
        for (k, run) in runs.iter_mut().enumerate() {
            if starts[k].is_none() && ends[k].is_none() {
                continue;
            }
            let start = starts[k].unwrap_or(run.start);
            let end = ends[k].unwrap_or_else(|| run.at(1.0));
            let length = end.sub(start).dot(run.tangent);
            if length <= run.tolerance() * 10.0 {
                return None;
            }
            *run = Seam::line(start, run.tangent, length, run.owner.clone());
        }
        Some(runs)
    }

    /// The chain moved `distance` across itself in the plane square to
    /// `normal` (to the left of each run seen down `normal`'s tip; a negative
    /// distance moves it right): each straight run shifted, each arc made the
    /// concentric arc, the straight runs of a mitred corner trimmed or
    /// extended to where they meet. `None` where a run vanishes (an arc
    /// moved onto its centre, a run shorter than the move at a corner) or the
    /// moved runs no longer meet.
    pub(super) fn offset(&self, normal: Vec3, distance: f64) -> Result<Option<Chain>, String> {
        let mut runs = Vec::new();
        for run in &self.runs {
            let left = normal.cross(run.tangent).normalized()?.scale(distance);
            let start = run.start.add(left);
            runs.push(match run.run {
                Run::Line => Seam::line(start, run.tangent, run.length, None),
                Run::Arc { centre, axis, angle } => {
                    // The move is radial: towards the centre it shrinks the
                    // arc, and at or past the centre the arc is gone.
                    let radial = run.start.sub(centre);
                    let radial = radial.sub(axis.scale(radial.dot(axis)));
                    let radius = radial.length();
                    let moved = radius + left.dot(radial.scale(1.0 / radius));
                    if moved <= run.tolerance() {
                        return Ok(None);
                    }
                    Seam { start, tangent: run.tangent, length: moved * angle, run: run.run, owner: None }
                }
            });
        }
        let Some(runs) = self.rejoined(runs) else { return Ok(None) };
        Ok(Chain::new(runs).ok())
    }

    /// The seam's length along all its runs.
    pub(super) fn length(&self) -> f64 {
        self.runs.iter().map(|run| run.length).sum()
    }

    /// Whether the last run ends where the first starts.
    pub(super) fn is_closed(&self) -> bool {
        self.corners.iter().any(|(a, b, _)| *b == 0 && *a + 1 == self.runs.len() && self.runs.len() > 1)
    }

    /// The pieces of the bead along the stretch `from..to` of the seam (by
    /// length from its start): the part of every run the stretch overlaps,
    /// with that run's section carried to where the part starts. A mitre cut
    /// is kept where the stretch runs on through its corner (and, for the
    /// whole of a closed seam, at the corner where it closes); the stretch's
    /// own ends are square to the seam, at a corner too.
    pub(super) fn pieces(&self, sections: &[[Vec3; 3]], trims: &[Trim], from: f64, to: f64) -> Vec<Piece> {
        let mut pieces = Vec::new();
        let mut start = 0.0;
        let total = self.length();
        let last = self.runs.len().saturating_sub(1);
        let closing = self.is_closed() && from <= self.runs[0].tolerance() && to >= total - self.runs[last].tolerance();
        for (k, run) in self.runs.iter().enumerate() {
            let end = start + run.length;
            let (low, high) = (from.max(start), to.min(end));
            let tolerance = run.tolerance();
            if high - low > tolerance {
                let f0 = if low - start <= tolerance { 0.0 } else { (low - start) / run.length };
                let f1 = if end - high <= tolerance { 1.0 } else { (high - start) / run.length };
                let [root, a, b] = sections[k];
                let through_start = from < start - tolerance || (closing && k == 0);
                let through_end = to > end + tolerance || (closing && k == last);
                let trim = Trim { ends: [
                    if f0 == 0.0 && through_start { trims[k].ends[0] } else { None },
                    if f1 == 1.0 && through_end { trims[k].ends[1] } else { None },
                ] };
                pieces.push(Piece {
                    bridge: [0.0, 0.0],
                    run: run.part(f0, f1),
                    section: [run.carry(f0, root), run.carry(f0, a), run.carry(f0, b)],
                    trim,
                    index: k,
                    from: f0,
                });
            }
            start = end;
        }
        pieces
    }

    /// The exact checks on one body of pieces of a fitted bead: clear of
    /// every body, and each piece's legs backed along it.
    pub(super) fn verify_pieces(&self, scene: &SceneMap, fits: &[Fit], legs: [f64; 2], bead: &crate::BrepSolid, pieces: &[Piece], exclude: &str) -> Result<Result<(), NoFit>, String> {
        let tolerance = self.runs.iter().map(Seam::tolerance).fold(0.0, f64::max);
        if let Err(reason) = clear(scene, bead, exclude, tolerance)? {
            return Ok(Err(reason));
        }
        for piece in pieces {
            let joint = fits[piece.index].carried(&self.runs[piece.index], piece.from);
            if let Err(reason) = supported(&piece.run, &joint, legs, &piece.trim)? {
                return Ok(Err(format!("{}{reason}", self.label(piece.index))));
            }
        }
        Ok(Ok(()))
    }
}

/// Where the straight lines through `a` along `da` and through `b` along
/// `db` (unit directions) meet, within `tolerance`: `None` when they pass
/// apart or run parallel.
fn meet(a: Vec3, da: Vec3, b: Vec3, db: Vec3, tolerance: f64) -> Option<Vec3> {
    let cos = da.dot(db);
    let denominator = 1.0 - cos * cos;
    if denominator <= 1e-12 {
        return (a.sub(b).cross(da).length() <= tolerance).then_some(b);
    }
    let w = a.sub(b);
    let (d, e) = (da.dot(w), db.dot(w));
    let s = (cos * e - d) / denominator;
    let t = (e - cos * d) / denominator;
    let (p, q) = (a.add(da.scale(s)), b.add(db.scale(t)));
    (p.sub(q).length() <= tolerance).then(|| p.add(q).scale(0.5))
}

/// One piece of a bead: a run (or a stretch of one), the section at its
/// start (the root's offset from the start, then the two toe offsets from
/// the root), its cuts, and which seam run it comes from and where on it.
#[derive(Clone, Debug)]
pub(super) struct Piece {
    pub run: Seam,
    pub section: [Vec3; 3],
    pub trim: Trim,
    pub index: usize,
    pub from: f64,
    /// [`Fit::bridge`] of its run's fit: where along each leg the section
    /// begins (zero: at the root).
    pub bridge: [f64; 2],
}

/// The pieces swept and united into one body, its faces named
/// `{id}:BeadFace{n}`; each face between the toes is the circular arc of
/// `contour` height when one is given.
pub(super) fn build_bead(id: &str, pieces: &[Piece], contour: Option<f64>) -> Result<crate::BrepSolid, String> {
    let mut bead: Option<crate::BrepSolid> = None;
    for Piece { run, section: [root, a, b], trim, bridge, .. } in pieces {
        // Keep the section counter-clockwise about the seam.
        let ((a, b), [skip_a, skip_b]) = if a.cross(*b).dot(run.tangent) >= 0.0 { ((*a, *b), *bridge) } else { ((*b, *a), [bridge[1], bridge[0]]) };
        let start = run.start.add(*root);
        let piece = if skip_a > 0.0 && skip_b > 0.0 {
            // Across a root opening: from one face's first point, through the
            // toes, to the other's (the contour stays between the toes).
            let first = |leg: Vec3, skip: f64| start.add(leg.scale(skip / leg.length()));
            sweep_bridged(run, start, [first(a, skip_a), start.add(a), start.add(b), first(b, skip_b)], contour, trim)?
        } else {
            sweep_section(run, &[start, start.add(a), start.add(b)], contour, trim)?
        };
        bead = Some(match bead {
            None => piece,
            Some(sum) => crate::boolean_operation(&sum, &piece, crate::BooleanOperation::Union, &crate::BooleanOptions::default())
                .map_err(|refusal| format!("could not join the bead's segments: {refusal}"))?,
        });
    }
    let mut bead = bead.ok_or("the seam is empty")?;
    for (i, face) in bead.shells.iter_mut().flat_map(|shell| &mut shell.faces).enumerate() {
        face.name = Some(format!("{id}:BeadFace{}", i + 1));
    }
    Ok(bead)
}

impl Chain {
    /// The normal of the plane every run lies in (an arc's axis), for placing
    /// a section by Orientation; `None` when the runs do not share one.
    pub(super) fn plane(&self) -> Option<Vec3> {
        let mut up: Option<Vec3> = None;
        for run in &self.runs {
            if let Run::Arc { axis, .. } = run.run {
                up.get_or_insert(axis);
            }
        }
        if up.is_none() {
            for pair in self.runs.windows(2) {
                if let Ok(normal) = pair[0].tangent.cross(pair[1].tangent).normalized() {
                    up = Some(normal);
                    break;
                }
            }
        }
        // Every run along one line: any normal of it will do.
        let up = match up {
            Some(up) => up,
            None => self.runs[0].tangent.perpendicular().ok()?,
        };
        let origin = self.runs[0].start;
        let flat = self.runs.iter().all(|run| {
            let tolerance = run.tolerance() * 10.0;
            let axis_ok = match run.run {
                Run::Line => run.tangent.dot(up).abs() <= 1e-9,
                Run::Arc { axis, .. } => axis.cross(up).length() <= 1e-9,
            };
            axis_ok && run.start.sub(origin).dot(up).abs() <= tolerance && run.at(1.0).sub(origin).dot(up).abs() <= tolerance
        });
        flat.then_some(up)
    }
}

/// The volume (cubic model units) a clearance or support boolean may leave
/// and still read as empty: fixed, so a large bead never hides a small defect.
const LEFTOVER_VOLUME: f64 = 1e-9;

/// A yes/no boolean: the result is only measured, so coplanar fragments are
/// left unmerged.
fn boolean(a: &crate::BrepSolid, b: &crate::BrepSolid, operation: crate::BooleanOperation) -> Result<crate::BrepSolid, crate::KernelRefusal> {
    let options = crate::BooleanOptions { merge_coplanar_faces: false, ..Default::default() };
    crate::boolean_operation(a, b, operation, &options)
}

/// An empty result where the operands only touch: the boolean refuses it as a
/// conservative empty overlap rather than returning no body.
fn empty(refusal: &crate::KernelRefusal) -> bool {
    matches!(refusal.class, crate::RefusalClass::ConservativeEmptyOverlap)
}

/// The volume two bodies share; a touching-only pair shares none.
pub(super) fn common_volume(a: &crate::BrepSolid, b: &crate::BrepSolid) -> Result<f64, NoFit> {
    match boolean(a, b, crate::BooleanOperation::Intersect) {
        Ok(common) => crate::solid_mass_properties(&common).map(|m| m.volume.abs())
            .map_err(|error| format!("could not measure the common part: {error}")),
        Err(refusal) if empty(&refusal) => Ok(0.0),
        Err(refusal) => Err(format!("could not check the bead against the base metal: {refusal}")),
    }
}

/// Check the built bead exactly: it shares no volume with any resident body.
pub(super) fn clear(scene: &SceneMap, bead: &crate::BrepSolid, exclude: &str, tolerance: f64) -> Result<Result<(), NoFit>, String> {
    let (low, high) = bounds(bead);
    let mut names: Vec<(&String, &u32)> = scene.solids.iter().filter(|(name, _)| !owned_by(name, exclude)).collect();
    names.sort();
    for (name, &handle) in names {
        let body = crate::registered_solid_clone(handle)?;
        let (body_low, body_high) = bounds(&body);
        let apart = body_low.x > high.x + tolerance || body_low.y > high.y + tolerance || body_low.z > high.z + tolerance
            || body_high.x < low.x - tolerance || body_high.y < low.y - tolerance || body_high.z < low.z - tolerance;
        if apart {
            continue;
        }
        match common_volume(bead, &body) {
            Ok(shared) if shared > LEFTOVER_VOLUME => return Ok(Err(format!("the bead would overlap {name}"))),
            Ok(_) => {}
            Err(reason) => return Ok(Err(reason)),
        }
    }
    Ok(Ok(()))
}

/// [`clear`] with some bodies as the weld leaves them: each `(name, body)`
/// in `replaced` stands for the resident body of that name (a part the weld
/// prepares), and the weld's own beads are skipped.
pub(super) fn clear_of(scene: &SceneMap, bead: &crate::BrepSolid, exclude: &str, replaced: &[(&str, &crate::BrepSolid)], tolerance: f64) -> Result<Result<(), NoFit>, String> {
    let (low, high) = bounds(bead);
    let mut names: Vec<(&String, &u32)> = scene.solids.iter().filter(|(name, _)| !owned_by(name, exclude)).collect();
    names.sort();
    for (name, &handle) in names {
        let body = match replaced.iter().find(|(replaced, _)| *replaced == name.as_str()) {
            Some((_, body)) => (*body).clone(),
            None => crate::registered_solid_clone(handle)?,
        };
        let (body_low, body_high) = bounds(&body);
        let apart = body_low.x > high.x + tolerance || body_low.y > high.y + tolerance || body_low.z > high.z + tolerance
            || body_high.x < low.x - tolerance || body_high.y < low.y - tolerance || body_high.z < low.z - tolerance;
        if apart {
            continue;
        }
        match common_volume(bead, &body) {
            Ok(shared) if shared > LEFTOVER_VOLUME => return Ok(Err(format!("the bead would overlap {name}"))),
            Ok(_) => {}
            Err(reason) => return Ok(Err(reason)),
        }
    }
    Ok(Ok(()))
}

/// Whether `body` backs the thin `slab` under a contact: nothing of the slab
/// is left once the body is removed.
pub(super) fn backed(slab: &crate::BrepSolid, body: &crate::BrepSolid) -> Result<Result<(), NoFit>, String> {
    match boolean(slab, body, crate::BooleanOperation::Subtract) {
        Err(refusal) if empty(&refusal) => Ok(Ok(())),
        Ok(rest) => {
            let left = crate::solid_mass_properties(&rest).map(|m| m.volume.abs()).unwrap_or(f64::INFINITY);
            Ok(if left > LEFTOVER_VOLUME { Err(format!("{left} of the support slab lies outside the part")) } else { Ok(()) })
        }
        Err(refusal) => Ok(Err(format!("could not check the support: {refusal}"))),
    }
}

/// Check each leg's whole strip on its joint face is backed by that face's
/// body (a thin slab under the strip, carried along the seam as the bead is
/// and trimmed as it is, lies entirely inside the body), so a bead never
/// bridges a hole, an edge or a gap in the face.
pub(super) fn supported(seam: &Seam, joint: &Fit, legs: [f64; 2], trim: &Trim) -> Result<Result<(), NoFit>, String> {
    for (i, (face, (direction, size))) in joint.faces.iter().zip(joint.legs.iter().zip(legs)).enumerate() {
        // Shallow enough for sheet-thin joint faces: the support check needs
        // only this much material under the leg.
        let depth = support_depth(seam);
        let start = seam.start.add(joint.root);
        let toe = start.add(direction.scale(size));
        // A leg across a root gap is backed from where its face begins.
        let start = start.add(direction.scale(joint.skip[i]));
        let inward = face.normal.scale(-depth);
        // Where the faces meet at other than a right angle, the slab's inner
        // corner at the seam would reach past the other joint face's plane (out
        // of this body, a cone on a plate); it is moved along the leg onto that
        // plane.
        let other = joint.faces[1 - i].normal;
        let shift = (depth * face.normal.dot(other) / direction.dot(other)).max(0.0);
        let slab = sweep(seam, &[start, toe, toe.add(inward), start.add(direction.scale(shift)).add(inward)], trim)?;
        let body = crate::registered_solid_clone(face.handle)?;
        // Backed means nothing of the slab is left once the body is removed:
        // any hole, edge or gap under the leg leaves a piece.
        match boolean(&slab, &body, crate::BooleanOperation::Subtract) {
            Err(refusal) if empty(&refusal) => {}
            Ok(rest) => {
                let left = crate::solid_mass_properties(&rest).map(|m| m.volume.abs()).unwrap_or(f64::INFINITY);
                if left > LEFTOVER_VOLUME {
                    return Ok(Err(format!("leg {size} is not supported along its whole length by joint face {}", face.name)));
                }
            }
            Err(refusal) => return Ok(Err(format!("could not check the support under leg {size}: {refusal}"))),
        }
    }
    Ok(Ok(()))
}

/// The material depth the support check reads under each leg: a hundred weld
/// floors (0.001 model units), ten times the band under which the boolean
/// reads two parallel planes as coincident, so the slab's floor is always
/// resolvable. Only a joint body thinner than this is refused as unsupported.
pub(super) fn support_depth(_seam: &Seam) -> f64 {
    100.0 * crate::tolerance::WELD_FLOOR
}

/// The seam two picked faces meet along: the one straight or circular edge of either face
/// that the other face carries (a concave edge both faces bound, or a plate's
/// edge standing on the other plate's face). Returned by its scene edge name.
///
/// Where no such edge exists, a straight edge of either face that the other
/// face stands a root gap off (parallel to it, nearer than the widest of
/// `legs`) is the seam where the two faces fit a bead's corner across the
/// gap: a closed sheet-metal corner, a plate standing a gap above another.
/// Edges whose beads share one root line (the edge of either face at the
/// same corner, or collinear pieces of one edge) are one seam: the longest.
pub(super) fn seam_between(scene: &SceneMap, faces: [&str; 2], exclude: &str, legs: [f64; 2]) -> Result<Result<String, String>, String> {
    let mut found = edges_between(scene, faces, None)?;
    if found.is_empty() {
        let mut roots: Vec<(Vec3, Vec3)> = Vec::new();
        for candidate in edges_between(scene, faces, Some(legs[0].max(legs[1])))? {
            let seam = &candidate.4;
            let picks = [faces[0].to_string(), faces[1].to_string()];
            let Ok(joint) = fit(scene, seam, &picks, exclude, legs, None)? else { continue };
            let (point, tolerance) = (seam.start.add(joint.root), seam.tolerance() * 10.0);
            let shared = roots.iter().position(|(other, along)| along.cross(seam.tangent).length() <= 1e-9
                && point.sub(*other).cross(*along).length() <= tolerance);
            match shared {
                None => {
                    roots.push((point, seam.tangent));
                    found.push(candidate);
                }
                Some(k) if seam.length > found[k].4.length => found[k] = candidate,
                Some(_) => {}
            }
        }
    }
    Ok(match found.as_slice() {
        [(name, _, _, _, _)] => Ok(name.clone()),
        [] => Err(format!("faces '{}' and '{}' do not meet along a straight or circular edge, nor stand a root gap narrower than the legs off one; select the seam edge", faces[0], faces[1])),
        _ => Err(format!("faces '{}' and '{}' meet along several edges; select the seam edge", faces[0], faces[1])),
    })
}

/// The scene edges of either face the other carries (`gap` None), or stands
/// a root gap narrower than `gap` off: name, ends and middle.
fn edges_between(scene: &SceneMap, faces: [&str; 2], gap: Option<f64>) -> Result<Vec<(String, Vec3, Vec3, Vec3, Seam)>, String> {
    let mut found: Vec<(String, Vec3, Vec3, Vec3, Seam)> = Vec::new();
    for (own, other) in [(faces[0], faces[1]), (faces[1], faces[0])] {
        for face in scene.resolve_face_group(own) {
            let runs: Vec<(u64, NurbsCurve)> = crate::with_registered_solid_str(face.handle, |solid| {
                let record = solid.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == face.face_id)
                    .ok_or_else(|| format!("face '{own}' is no longer resident"))?;
                let mut runs = Vec::new();
                for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
                    let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
                    if edge.degenerate { continue; }
                    runs.push((edge.id, crate::feature_pipeline::features::common::trimmed_curve(&edge.curve, edge.t0, edge.t1)?));
                }
                Ok(runs)
            })?;
            for (edge_id, curve) in runs {
                let Ok(Some(seam)) = Seam::from_curve(&curve, None) else { continue };
                if seam.length <= seam.tolerance() { continue; }
                let (start, end, middle) = (seam.at(0.0), seam.at(1.0), seam.at(0.5));
                let meets = match gap {
                    None => carries(scene, &seam, other)?,
                    Some(widest) => across_gap(scene, &seam, other, widest)?.is_some(),
                };
                if !meets { continue; }
                let mut names: Vec<&String> = scene.edges.iter()
                    .filter(|(_, edge)| edge.handle == face.handle && edge.edge_id == edge_id)
                    .map(|(name, _)| name).collect();
                names.sort();
                let Some(name) = names.first() else { continue };
                let tolerance = seam.tolerance();
                // The same edge seen from both faces: same ends and middle (two
                // half circles share their ends, not their middles).
                let same = |(_, a, b, m, _): &(String, Vec3, Vec3, Vec3, Seam)| m.sub(middle).length() < tolerance
                    && ((a.sub(start).length() < tolerance && b.sub(end).length() < tolerance)
                        || (a.sub(end).length() < tolerance && b.sub(start).length() < tolerance));
                if !found.iter().any(same) {
                    found.push(((*name).clone(), start, end, middle, seam));
                }
            }
        }
    }
    Ok(found)
}