threers 0.1.0

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
//! Fillets and chamfers: an edge replaced by a face.
//!
//! The operation a mesh cannot do. Rounding an edge of a triangle soup means
//! guessing which triangles were the two faces and where the edge was; here the
//! edge is an [`Edge`], it names the two surfaces it joins, and the blend is the
//! surface tangent to both — a cylinder under a rolling ball, a torus around a
//! rim, a sphere in a corner — stated exactly rather than sampled.
//!
//! ```ignore
//! let body = Body::cuboid([4.0, 4.0, 4.0]);
//! let all: Vec<usize> = (0..body.edges().len()).collect();
//! let rounded = body.fillet(&all, 0.5, 1e-3)?;
//! let bevelled = body.chamfer(&[0, 2], 0.25, 1e-3)?;
//! ```
//!
//! # What it blends
//!
//! * **A straight edge between two planes**, convex or concave, whose ends are
//!   corners where exactly three planar faces meet. Any number of the three
//!   edges at a corner may be selected: one ends the blend on the third face,
//!   two mitre into each other, three meet in a point or, with
//!   [`ChamferCorner::Facet`](super::ChamferCorner), a triangular facet
//!   (chamfer), or a spherical patch (fillet).
//! * **A circular rim** where a plane caps a cylinder square to its axis: the
//!   end of a shaft, the mouth of a hole, the foot of a boss, the floor of a
//!   blind bore. A chamfer there is a cone and a fillet a torus.
//!
//! # What it declines
//!
//! Everything else, by name — see [`BlendDeclined`]. The contract is the
//! boolean's: a result is a closed solid, or there is no result and a reason.
//! In particular an edge that ends on a curved face, or on an edge that is not
//! straight, is declined, so a box whose vertical edges were rounded cannot yet
//! have its top edges rounded as well.
//!
//! # Tolerance
//!
//! Curved boundaries are sampled here, once, to `tolerance`, and both faces on
//! a boundary share the samples. [`Body::refine_edges`] can still add to the
//! ones that cross — a fillet's end on a flat face, a mitre — but not to the
//! ones along which two surfaces *touch*: a torus meets its cap in a tangent
//! circle, and the alternating projection that refines an edge has no slope to
//! follow there. So blend at the tolerance the result will be tessellated at.

use std::collections::{HashMap, HashSet};
use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI, TAU};

use crate::nurbs::construct::perpendicular;
use crate::nurbs::{v3, V3};

use super::body::{Body, Edge, Face, TrimLoop};
use super::Surface;

/// Why a fillet or chamfer was not attempted, or was abandoned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BlendDeclined {
    /// A body that is not a closed solid has no inside to round towards.
    NotASolid,
    /// A radius, distance or tolerance that is not a positive finite number.
    BadSize,
    /// An edge index past the end of [`Body::edges`].
    NoSuchEdge { edge: usize },
    /// An edge that is neither a straight line between two planes nor a
    /// circular rim between a plane and a cylinder square to it.
    UnsupportedEdge { edge: usize },
    /// A selected edge ends at a vertex that is not the meeting of exactly
    /// three planar faces along three straight edges.
    UnsupportedVertex { vertex: usize },
    /// The selected edges meeting at a vertex are not all convex or all
    /// concave. One blend there removes material and the other adds it, and the
    /// patch that joins them is not a sphere.
    MixedConvexity { vertex: usize },
    /// Two blends reach the unselected edge at a vertex at different depths, so
    /// they do not mitre: one would have to be cut by the other's neighbour.
    UnequalSetback { vertex: usize },
    /// The blend is too large for this edge: it would consume the edge, or a
    /// neighbouring one, or the face beside it.
    TooLarge { edge: usize },
    /// A face the blend would have to re-trim carries a boundary that could not
    /// be restated.
    TrimmedFace { face: usize },
    /// The blend was built and is not a closed solid. Returned instead of the
    /// body, because a caller cannot tell a result with a hole in it is wrong.
    NotWatertight { defects: usize },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    Chamfer,
    Fillet,
}

impl Body {
    /// Round the given edges with a rolling ball of `radius`.
    ///
    /// `edges` index [`Body::edges`]. The blend faces are exact — cylinders,
    /// tori and spheres tangent to the faces they join — and their boundaries
    /// are sampled to `tolerance`. Indices of edges that were not selected are
    /// unchanged in the result.
    pub fn fillet(
        &self,
        edges: &[usize],
        radius: f64,
        tolerance: f64,
    ) -> Result<Body, BlendDeclined> {
        blend(self, edges, radius, Kind::Fillet, tolerance)
    }

    /// Bevel the given edges, cutting each face back by `distance` from the
    /// edge.
    ///
    /// The setback is measured along each face, so the bevel on a right-angled
    /// edge is at 45° and `distance·√2` wide.
    pub fn chamfer(
        &self,
        edges: &[usize],
        distance: f64,
        tolerance: f64,
    ) -> Result<Body, BlendDeclined> {
        blend(self, edges, distance, Kind::Chamfer, tolerance)
    }
}

/// A body taken apart, so it can be edited and put back.
struct Parts {
    surfaces: Vec<Surface>,
    vertices: Vec<V3>,
    edges: Vec<Edge>,
    faces: Vec<Face>,
}

impl Parts {
    fn of(body: &Body) -> Parts {
        Parts {
            surfaces: body.surfaces().to_vec(),
            vertices: body.vertices().to_vec(),
            edges: body.edges().to_vec(),
            faces: body.faces().to_vec(),
        }
    }

    fn body(&self) -> Body {
        Body::from_parts(
            self.surfaces.clone(),
            self.vertices.clone(),
            self.edges.clone(),
            self.faces.clone(),
        )
    }

    fn vertex(&mut self, p: V3) -> usize {
        self.vertices.push(p);
        self.vertices.len() - 1
    }

    /// Drop the vertices nothing names any more — the corners a blend replaced.
    fn compact(&mut self) {
        let mut used = vec![false; self.vertices.len()];
        for e in &self.edges {
            for &v in &e.vertices {
                used[v] = true;
            }
        }
        for l in self.faces.iter().filter_map(|f| f.loops.as_ref()).flatten() {
            for &v in &l.vertices {
                used[v] = true;
            }
        }
        let mut renamed = vec![usize::MAX; self.vertices.len()];
        let mut kept = Vec::with_capacity(self.vertices.len());
        for (old, p) in self.vertices.iter().enumerate() {
            if used[old] {
                renamed[old] = kept.len();
                kept.push(*p);
            }
        }
        self.vertices = kept;
        for e in &mut self.edges {
            for v in &mut e.vertices {
                *v = renamed[*v];
            }
        }
        for l in self
            .faces
            .iter_mut()
            .filter_map(|f| f.loops.as_mut())
            .flatten()
        {
            for v in &mut l.vertices {
                *v = renamed[*v];
            }
        }
    }
}

fn blend(
    body: &Body,
    selection: &[usize],
    size: f64,
    kind: Kind,
    tolerance: f64,
) -> Result<Body, BlendDeclined> {
    if !(size > 0.0 && size.is_finite() && tolerance > 0.0 && tolerance.is_finite()) {
        return Err(BlendDeclined::BadSize);
    }
    let mut selection = selection.to_vec();
    selection.sort_unstable();
    selection.dedup();
    if let Some(&edge) = selection.iter().find(|&&e| e >= body.edges().len()) {
        return Err(BlendDeclined::NoSuchEdge { edge });
    }
    if !body.is_valid_solid(tolerance) {
        return Err(BlendDeclined::NotASolid);
    }
    if selection.is_empty() {
        return Ok(body.clone());
    }

    let (rims, straight): (Vec<usize>, Vec<usize>) =
        selection.iter().partition(|&&e| body.edges()[e].closed);

    // The straight edges go together, because the ones that share a corner have
    // to agree about it. A rim has no corners and is its own problem; it is
    // done afterwards, on indices the first pass leaves where they were.
    let mut parts = if straight.is_empty() {
        Parts::of(body)
    } else {
        blend_straight(body, &straight, size, kind, tolerance)?
    };
    for &rim in &rims {
        blend_rim(&mut parts, rim, size, kind, tolerance)?;
    }
    parts.compact();

    let out = parts.body();
    let defects = out.defects(tolerance);
    if !defects.is_empty() || !out.shells().iter().all(|s| s.closed) {
        return Err(BlendDeclined::NotWatertight {
            defects: defects.len(),
        });
    }
    Ok(out)
}

fn extent(vertices: &[V3]) -> f64 {
    let (mut lo, mut hi) = ([f64::MAX; 3], [f64::MIN; 3]);
    for p in vertices {
        for k in 0..3 {
            lo[k] = lo[k].min(p[k]);
            hi[k] = hi[k].max(p[k]);
        }
    }
    if vertices.is_empty() {
        1.0
    } else {
        v3::dist(lo, hi).max(1e-12)
    }
}

fn pair(a: usize, b: usize) -> (usize, usize) {
    (a.min(b), a.max(b))
}

/// A plane's normal as the surface states it, and as the solid sees it.
fn plane_normals(body: &Body, face: usize) -> Option<(V3, V3)> {
    let f = &body.faces()[face];
    match &body.surfaces()[f.surface] {
        Surface::Plane { normal, .. } => Some((
            *normal,
            if f.flipped {
                v3::scale(*normal, -1.0)
            } else {
                *normal
            },
        )),
        _ => None,
    }
}

/// An open edge whose points all lie on the line between its ends: the ends,
/// the unit direction from the first to the last, and the length.
fn straight_edge(body: &Body, edge: usize, eps: f64) -> Option<(usize, usize, V3, f64)> {
    let e = &body.edges()[edge];
    if e.closed || e.vertices.len() < 2 {
        return None;
    }
    let (first, last) = (e.vertices[0], *e.vertices.last()?);
    let (p, q) = (body.vertices()[first], body.vertices()[last]);
    let length = v3::dist(p, q);
    let dir = v3::normalize(v3::sub(q, p))?;
    if first == last || length <= eps {
        return None;
    }
    for &v in &e.vertices[1..e.vertices.len() - 1] {
        let d = v3::sub(body.vertices()[v], p);
        let off = v3::sub(d, v3::scale(dir, v3::dot(d, dir)));
        if v3::norm(off) > eps {
            return None;
        }
    }
    Some((first, last, dir, length))
}

/// Which way a planar face lies from one of its edges.
///
/// Read off the face's boundary rather than off its other edges. The obvious
/// shortcut — the face lies towards its *next* edge at the corner — is wrong at
/// a reflex corner, where the next edge leads out of the face rather than
/// across it, and an L-shaped cap has one. A ring runs anticlockwise about the
/// surface normal with the face on its left, holes included, so the answer is
/// the normal crossed with the direction the ring walks the edge in.
struct Sides<'a> {
    body: &'a Body,
    loops: HashMap<usize, Vec<TrimLoop>>,
}

impl Sides<'_> {
    fn inward(&mut self, face: usize, edge: usize) -> Option<V3> {
        let body = self.body;
        let (normal, _) = plane_normals(body, face)?;
        let e = &body.edges()[edge];
        let (p, q) = (*e.vertices.first()?, *e.vertices.get(1)?);
        let loops = self
            .loops
            .entry(face)
            .or_insert_with(|| body.face_loops(face));
        let mut sign = 0.0;
        'rings: for l in loops.iter() {
            let n = l.vertices.len();
            for i in 0..n {
                let step = (l.vertices[i], l.vertices[(i + 1) % n]);
                if step == (p, q) {
                    sign = 1.0;
                    break 'rings;
                }
                if step == (q, p) {
                    sign = -1.0;
                    break 'rings;
                }
            }
        }
        if sign == 0.0 {
            return None;
        }
        let along = v3::sub(body.vertices()[q], body.vertices()[p]);
        v3::normalize(v3::scale(v3::cross(normal, along), sign))
    }
}

/// A selected straight edge and the face that replaces it.
struct Chosen {
    edge: usize,
    /// Its two ends, and the unit direction from the first to the second.
    ends: [usize; 2],
    dir: V3,
    /// The two faces it joins, and their outward normals.
    faces: [usize; 2],
    normals: [V3; 2],
    /// `+1` where the solid is convex across the edge, `-1` where it is
    /// concave. A convex blend removes material and a concave one adds it; the
    /// geometry is the same construction on the other side.
    convex: f64,
    /// How far each face is cut back from the edge.
    setback: f64,
    /// The blend surface, and the edges bounding the blend face.
    surface: usize,
    boundary: Vec<usize>,
}

/// A vertex a selected edge ends at: three edges, three faces.
struct Corner {
    vertex: usize,
    edges: [usize; 3],
    /// Unit directions along each edge, away from the vertex.
    dirs: [V3; 3],
    /// `faces[i]` is the face *opposite* `edges[i]` — the one bounded by the
    /// other two.
    faces: [usize; 3],
    selected: [bool; 3],
    /// Where an unselected edge now ends, having been cut back by its
    /// neighbours' blends.
    ends: [Option<usize>; 3],
    /// The point that replaces the vertex in `faces[i]`, for a face bounded by
    /// at least one selected edge.
    points: [Option<usize>; 3],
}

impl Corner {
    fn point_on(&self, face: usize) -> Option<usize> {
        (0..3)
            .find(|&i| self.faces[i] == face)
            .and_then(|i| self.points[i])
    }
}

/// Does the segment `p`–`q` touch the axis-aligned box `lo`..`hi`?
fn segment_meets_box(p: [f64; 2], q: [f64; 2], lo: [f64; 2], hi: [f64; 2]) -> bool {
    let (mut enter, mut leave) = (0.0f64, 1.0f64);
    for k in 0..2 {
        let d = q[k] - p[k];
        if d.abs() < 1e-300 {
            if p[k] < lo[k] || p[k] > hi[k] {
                return false;
            }
            continue;
        }
        let (a, b) = ((lo[k] - p[k]) / d, (hi[k] - p[k]) / d);
        enter = enter.max(a.min(b));
        leave = leave.min(a.max(b));
        if enter > leave {
            return false;
        }
    }
    true
}

fn solve3(rows: [V3; 3], rhs: V3) -> Option<V3> {
    let det = v3::dot(rows[0], v3::cross(rows[1], rows[2]));
    if det.abs() < 1e-12 {
        return None;
    }
    let x = v3::add(
        v3::add(
            v3::scale(v3::cross(rows[1], rows[2]), rhs[0]),
            v3::scale(v3::cross(rows[2], rows[0]), rhs[1]),
        ),
        v3::scale(v3::cross(rows[0], rows[1]), rhs[2]),
    );
    Some(v3::scale(x, 1.0 / det))
}

/// The curve where a fillet's cylinder is cut by a plane, between two points
/// already on it: the new vertices strictly between them.
///
/// Every end of a fillet is one of these. Cut by the face the edge ran into, it
/// is the arc that face gains; cut by the plane bisecting two fillets' axes, it
/// is the mitre they share — two cylinders of one radius whose axes cross meet
/// in a pair of ellipses, each of them planar; cut square to the axis, it is
/// the circle a corner's sphere touches the cylinder along.
///
/// Sampled by the cylinder's own angle and slid along the axis onto the plane,
/// so every point is on the cylinder exactly and on the plane exactly.
fn section(
    cylinder: &Surface,
    origin: V3,
    normal: V3,
    from: V3,
    to: V3,
    tolerance: f64,
    parts: &mut Parts,
) -> Option<Vec<usize>> {
    let Surface::Cylinder { axis, radius, .. } = cylinder else {
        return None;
    };
    let lean = v3::dot(*axis, normal);
    if lean.abs() < 1e-9 {
        return None;
    }
    let (ua, _) = cylinder.invert(from)?;
    let (ub, _) = cylinder.invert(to)?;
    let at = |u: f64| {
        let p = cylinder.point(u, 0.0);
        v3::add(
            p,
            v3::scale(*axis, v3::dot(v3::sub(origin, p), normal) / lean),
        )
    };
    // The two ends were worked out from the faces; the curve was worked out
    // from the surfaces. If they disagree the construction does not apply here.
    let slack = 1e-7 * (1.0 + radius + v3::dist(from, to));
    if v3::dist(at(ua), from) > slack || v3::dist(at(ub), to) > slack {
        return None;
    }
    let u = |k: f64, n: usize| ua + (ub - ua) * k / n as f64;
    let mut n = 2usize;
    while n < 2048 {
        let worst = (0..n)
            .map(|s| {
                let (a, b) = (at(u(s as f64, n)), at(u(s as f64 + 1.0, n)));
                v3::dist(at(u(s as f64 + 0.5, n)), v3::scale(v3::add(a, b), 0.5))
            })
            .fold(0.0, f64::max);
        if worst <= tolerance {
            break;
        }
        n *= 2;
    }
    Some((1..n).map(|s| parts.vertex(at(u(s as f64, n)))).collect())
}

fn blend_straight(
    body: &Body,
    selection: &[usize],
    size: f64,
    kind: Kind,
    tolerance: f64,
) -> Result<Parts, BlendDeclined> {
    let eps = 1e-9 * extent(body.vertices());
    let mut parts = Parts::of(body);
    let mut sides = Sides {
        body,
        loops: HashMap::new(),
    };

    // Who uses what.
    let mut edge_faces: Vec<Vec<usize>> = vec![Vec::new(); body.edges().len()];
    for (fi, f) in body.faces().iter().enumerate() {
        for &e in &f.edges {
            edge_faces[e].push(fi);
        }
    }
    let mut ending_at: HashMap<usize, Vec<usize>> = HashMap::new();
    let mut passed_through: HashSet<usize> = HashSet::new();
    for (ei, e) in body.edges().iter().enumerate() {
        let n = e.vertices.len();
        if e.closed || n < 2 {
            passed_through.extend(e.vertices.iter().copied());
            continue;
        }
        ending_at.entry(e.vertices[0]).or_default().push(ei);
        ending_at.entry(e.vertices[n - 1]).or_default().push(ei);
        passed_through.extend(e.vertices[1..n - 1].iter().copied());
    }

    // The selected edges: what they join, which way they turn, how far back
    // each face is cut.
    let mut chosen: Vec<Chosen> = Vec::with_capacity(selection.len());
    let mut chosen_at: HashMap<usize, usize> = HashMap::new();
    for &edge in selection {
        let unsupported = BlendDeclined::UnsupportedEdge { edge };
        let (first, last, dir, _) = straight_edge(body, edge, eps).ok_or(unsupported.clone())?;
        let &[a, b] = edge_faces[edge].as_slice() else {
            return Err(unsupported);
        };
        if a == b {
            return Err(unsupported);
        }
        let (Some((_, na)), Some((_, nb))) = (plane_normals(body, a), plane_normals(body, b))
        else {
            return Err(unsupported);
        };
        let cos = v3::dot(na, nb);
        if cos.abs() > 1.0 - 1e-9 {
            return Err(unsupported);
        }
        // Face A falls away behind face B across a convex edge, and rises in
        // front of it across a concave one.
        let side = v3::dot(sides.inward(a, edge).ok_or(unsupported.clone())?, nb);
        if side.abs() < 1e-9 {
            return Err(unsupported);
        }
        let setback = match kind {
            Kind::Chamfer => size,
            // The ball touches each face `r·tan(φ/2)` from the edge, `φ` being
            // the angle between the normals: `r` itself at a right angle.
            Kind::Fillet => size * ((1.0 - cos) / (1.0 + cos)).sqrt(),
        };
        chosen_at.insert(edge, chosen.len());
        chosen.push(Chosen {
            edge,
            ends: [first, last],
            dir,
            faces: [a, b],
            normals: [na, nb],
            convex: if side < 0.0 { 1.0 } else { -1.0 },
            setback,
            surface: usize::MAX,
            boundary: Vec::new(),
        });
    }

    // The corners they end at.
    let mut touched: Vec<usize> = chosen.iter().flat_map(|c| c.ends).collect();
    touched.sort_unstable();
    touched.dedup();

    let mut corners: Vec<Corner> = Vec::with_capacity(touched.len());
    let mut corner_at: HashMap<usize, usize> = HashMap::new();
    let mut cut_back: HashMap<usize, f64> = HashMap::new();
    for &vertex in &touched {
        let unsupported = BlendDeclined::UnsupportedVertex { vertex };
        let at = body.vertices()[vertex];
        let Some(&[e0, e1, e2]) = ending_at.get(&vertex).map(Vec::as_slice) else {
            return Err(unsupported);
        };
        if passed_through.contains(&vertex) {
            return Err(unsupported);
        }
        let edges = [e0, e1, e2];
        let mut dirs = [[0.0; 3]; 3];
        for i in 0..3 {
            let (first, _, dir, _) =
                straight_edge(body, edges[i], eps).ok_or(unsupported.clone())?;
            dirs[i] = if first == vertex {
                dir
            } else {
                v3::scale(dir, -1.0)
            };
        }
        let mut faces = [0usize; 3];
        for (i, face) in faces.iter_mut().enumerate() {
            let (j, k) = ((i + 1) % 3, (i + 2) % 3);
            let mut common = edge_faces[edges[j]]
                .iter()
                .filter(|f| edge_faces[edges[k]].contains(f));
            let (Some(&f), None) = (common.next(), common.next()) else {
                return Err(unsupported);
            };
            if plane_normals(body, f).is_none() {
                return Err(unsupported);
            }
            *face = f;
        }
        if faces[0] == faces[1] || faces[1] == faces[2] || faces[2] == faces[0] {
            return Err(unsupported);
        }
        let selected = [0, 1, 2].map(|i| chosen_at.contains_key(&edges[i]));
        let of = |i: usize| &chosen[chosen_at[&edges[i]]];
        let mut turn = (0..3).filter(|&i| selected[i]).map(|i| of(i).convex);
        let first_turn = turn.next().unwrap_or(1.0);
        if turn.any(|t| t != first_turn) {
            return Err(BlendDeclined::MixedConvexity { vertex });
        }

        // An unselected edge is cut back to where its neighbour's blend leaves
        // the face they share. With both neighbours selected the two blends
        // have to reach it at the same depth, or they do not meet in a mitre.
        let mut ends = [None; 3];
        for k in 0..3 {
            if selected[k] {
                continue;
            }
            let (i, j) = ((k + 1) % 3, (k + 2) % 3);
            let mut depth: Option<f64> = None;
            for (face, other) in [(faces[i], j), (faces[j], i)] {
                if !selected[other] {
                    continue;
                }
                let into = sides
                    .inward(face, edges[other])
                    .ok_or(unsupported.clone())?;
                let reach = v3::dot(dirs[k], into);
                // Not positive at a reflex corner: the blend runs past the
                // vertex and into the face beyond, which is another shape.
                if reach < 1e-6 {
                    return Err(unsupported);
                }
                let d = of(other).setback / reach;
                if depth.is_some_and(|prev| (prev - d).abs() > 1e-7 * (1.0 + d.abs())) {
                    return Err(BlendDeclined::UnequalSetback { vertex });
                }
                depth = Some(d);
            }
            if let Some(d) = depth {
                *cut_back.entry(edges[k]).or_insert(0.0) += d;
                ends[k] = Some(parts.vertex(v3::add(at, v3::scale(dirs[k], d))));
            }
        }

        // And the vertex itself becomes one point per face: where the face's
        // two setback lines cross, or where its one setback line meets the
        // edge that was cut back.
        let mut points = [None; 3];
        for i in 0..3 {
            let (j, k) = ((i + 1) % 3, (i + 2) % 3);
            points[i] = match (selected[j], selected[k]) {
                (true, true) => {
                    let into_j = sides
                        .inward(faces[i], edges[j])
                        .ok_or(unsupported.clone())?;
                    let into_k = sides
                        .inward(faces[i], edges[k])
                        .ok_or(unsupported.clone())?;
                    let (along_j, along_k) = (v3::dot(dirs[j], into_k), v3::dot(dirs[k], into_j));
                    if along_j.abs() < 1e-6 || along_k.abs() < 1e-6 {
                        return Err(unsupported);
                    }
                    let p = v3::add(
                        at,
                        v3::add(
                            v3::scale(dirs[j], of(k).setback / along_j),
                            v3::scale(dirs[k], of(j).setback / along_k),
                        ),
                    );
                    Some(parts.vertex(p))
                }
                (true, false) => ends[k],
                (false, true) => ends[j],
                (false, false) => None,
            };
        }

        corner_at.insert(vertex, corners.len());
        corners.push(Corner {
            vertex,
            edges,
            dirs,
            faces,
            selected,
            ends,
            points,
        });
    }

    // Is there room? An edge cut back from both ends has to have something
    // left, and so does each side of a blend.
    for (&edge, &cut) in &cut_back {
        let (_, _, _, length) =
            straight_edge(body, edge, eps).ok_or(BlendDeclined::UnsupportedEdge { edge })?;
        if cut >= length - eps {
            return Err(BlendDeclined::TooLarge { edge });
        }
    }
    let rail = |c: &Chosen, side: usize| -> Option<[usize; 2]> {
        Some([
            corners[corner_at[&c.ends[0]]].point_on(c.faces[side])?,
            corners[corner_at[&c.ends[1]]].point_on(c.faces[side])?,
        ])
    };
    for c in &chosen {
        for side in 0..2 {
            let [p, q] = rail(c, side).ok_or(BlendDeclined::UnsupportedEdge { edge: c.edge })?;
            let run = v3::dot(v3::sub(parts.vertices[q], parts.vertices[p]), c.dir);
            if run <= eps {
                return Err(BlendDeclined::TooLarge { edge: c.edge });
            }
        }
    }

    // And the strip of each face a blend takes has to be the face's to give:
    // nothing else that bounds the face — a hole, a notch, the far side — may
    // reach into it. The edges at the blend's own two corners are the strip's
    // ends and are judged above.
    for c in &chosen {
        let declined = BlendDeclined::TooLarge { edge: c.edge };
        let from = body.vertices()[c.ends[0]];
        let length = v3::dist(from, body.vertices()[c.ends[1]]);
        let mut own: Vec<usize> = c
            .ends
            .iter()
            .flat_map(|v| corners[corner_at[v]].edges)
            .collect();
        own.push(c.edge);
        for &face in &c.faces {
            let into = sides
                .inward(face, c.edge)
                .ok_or(BlendDeclined::UnsupportedEdge { edge: c.edge })?;
            let flat = |v: usize| {
                let d = v3::sub(body.vertices()[v], from);
                [v3::dot(d, c.dir), v3::dot(d, into)]
            };
            for &e in &body.faces()[face].edges {
                if own.contains(&e) {
                    continue;
                }
                for w in body.edges()[e].vertices.windows(2) {
                    if segment_meets_box(
                        flat(w[0]),
                        flat(w[1]),
                        [eps, -eps],
                        [length - eps, c.setback + eps],
                    ) {
                        return Err(declined);
                    }
                }
            }
        }
    }

    // The blend surfaces.
    for c in &mut chosen {
        let unsupported = BlendDeclined::UnsupportedEdge { edge: c.edge };
        let [na, nb] = c.normals;
        let between = v3::add(na, nb);
        let surface = match kind {
            Kind::Chamfer => {
                let [pa, _] = rail(c, 0).ok_or(unsupported.clone())?;
                let [pb, _] = rail(c, 1).ok_or(unsupported.clone())?;
                let (pa, pb) = (parts.vertices[pa], parts.vertices[pb]);
                let n = v3::normalize(v3::cross(c.dir, v3::sub(pb, pa))).ok_or(unsupported)?;
                let n = if v3::dot(n, between) < 0.0 {
                    v3::scale(n, -1.0)
                } else {
                    n
                };
                Surface::plane(pa, n)
            }
            Kind::Fillet => {
                // The axis is where the two faces, each moved `r` towards the
                // ball, intersect. `u = 0` is pointed at the edge, so the patch
                // straddles it and stays clear of the branch cut.
                let cos = v3::dot(na, nb);
                let origin = v3::sub(
                    body.vertices()[c.ends[0]],
                    v3::scale(between, c.convex * size / (1.0 + cos)),
                );
                Surface::cylinder(origin, c.dir, size).with_x_dir(v3::scale(between, c.convex))
            }
        };
        parts.surfaces.push(surface);
        c.surface = parts.surfaces.len() - 1;
    }

    // Edges. An unselected edge keeps its index and moves an end; a selected
    // one becomes the rail along its first face, and the rail along its second
    // is new.
    for corner in &corners {
        for k in 0..3 {
            let Some(end) = corner.ends[k] else { continue };
            let e = &mut parts.edges[corner.edges[k]];
            let (first, last) = (e.vertices[0], e.vertices[e.vertices.len() - 1]);
            e.vertices = if first == corner.vertex {
                vec![end, last]
            } else {
                vec![first, end]
            };
        }
    }
    for c in &mut chosen {
        let unsupported = BlendDeclined::UnsupportedEdge { edge: c.edge };
        let [a, b] = c.faces;
        let (sa, sb) = (body.faces()[a].surface, body.faces()[b].surface);
        let (ra, rb) = (
            rail(c, 0).ok_or(unsupported.clone())?,
            rail(c, 1).ok_or(unsupported)?,
        );
        parts.edges[c.edge] = Edge {
            surfaces: pair(sa, c.surface),
            vertices: ra.to_vec(),
            closed: false,
        };
        parts.edges.push(Edge {
            surfaces: pair(sb, c.surface),
            vertices: rb.to_vec(),
            closed: false,
        });
        let rail_b = parts.edges.len() - 1;
        for slot in parts.faces[b].edges.iter_mut() {
            if *slot == c.edge {
                *slot = rail_b;
            }
        }
        c.boundary = vec![c.edge, rail_b];
    }

    // The ends of each blend, corner by corner.
    let mut fresh: Vec<usize> = Vec::new();
    for corner in &corners {
        let vertex = corner.vertex;
        let unsupported = BlendDeclined::UnsupportedVertex { vertex };
        let at = body.vertices()[vertex];
        let which = |i: usize| chosen_at[&corner.edges[i]];
        let count = corner.selected.iter().filter(|s| **s).count();
        let convex = (0..3)
            .find(|&i| corner.selected[i])
            .map_or(1.0, |i| chosen[which(i)].convex);
        // Where the three faces, each moved `r` towards the ball, meet: the
        // point every fillet axis at this corner passes through.
        let centre = || -> Option<V3> {
            let n = [0, 1, 2].map(|i| plane_normals(body, corner.faces[i]).map(|(_, out)| out));
            let w = solve3([n[0]?, n[1]?, n[2]?], [1.0; 3])?;
            Some(v3::sub(at, v3::scale(w, convex * size)))
        };

        match count {
            // One blend, ending on the third face.
            1 => {
                let i = (0..3).find(|&i| corner.selected[i]).unwrap_or(0);
                let (j, k) = ((i + 1) % 3, (i + 2) % 3);
                let ci = which(i);
                let (Some(from), Some(to)) = (corner.points[j], corner.points[k]) else {
                    return Err(unsupported);
                };
                let third = corner.faces[i];
                let (normal, _) = plane_normals(body, third).ok_or(unsupported.clone())?;
                let between = match kind {
                    Kind::Chamfer => Vec::new(),
                    Kind::Fillet => section(
                        &parts.surfaces[chosen[ci].surface].clone(),
                        at,
                        normal,
                        parts.vertices[from],
                        parts.vertices[to],
                        tolerance,
                        &mut parts,
                    )
                    .ok_or(unsupported)?,
                };
                let mut vertices = vec![from];
                vertices.extend(between);
                vertices.push(to);
                parts.edges.push(Edge {
                    surfaces: pair(chosen[ci].surface, body.faces()[third].surface),
                    vertices,
                    closed: false,
                });
                let e = parts.edges.len() - 1;
                parts.faces[third].edges.push(e);
                chosen[ci].boundary.push(e);
            }
            // Two blends, mitred into each other.
            2 => {
                let k = (0..3).find(|&k| !corner.selected[k]).unwrap_or(0);
                let (i, j) = ((k + 1) % 3, (k + 2) % 3);
                let (ci, cj) = (which(i), which(j));
                let (Some(from), Some(to)) = (corner.points[k], corner.ends[k]) else {
                    return Err(unsupported);
                };
                let between = match kind {
                    Kind::Chamfer => Vec::new(),
                    Kind::Fillet => {
                        let unequal = BlendDeclined::UnequalSetback { vertex };
                        let o = centre().ok_or(unsupported)?;
                        let (p, q) = (parts.vertices[from], parts.vertices[to]);
                        // Two planes bisect a pair of crossing axes. The mitre
                        // is in the one both its ends are on.
                        let off = |m: V3| {
                            v3::normalize(m).map_or(f64::MAX, |m| {
                                v3::dot(v3::sub(p, o), m).abs() + v3::dot(v3::sub(q, o), m).abs()
                            })
                        };
                        let (plus, minus) = (
                            v3::add(corner.dirs[i], corner.dirs[j]),
                            v3::sub(corner.dirs[i], corner.dirs[j]),
                        );
                        let normal = if off(plus) < off(minus) { plus } else { minus };
                        let normal = v3::normalize(normal).ok_or(unequal.clone())?;
                        section(
                            &parts.surfaces[chosen[ci].surface].clone(),
                            o,
                            normal,
                            p,
                            q,
                            tolerance,
                            &mut parts,
                        )
                        .ok_or(unequal)?
                    }
                };
                let mut vertices = vec![from];
                vertices.extend(between);
                vertices.push(to);
                parts.edges.push(Edge {
                    surfaces: pair(chosen[ci].surface, chosen[cj].surface),
                    vertices,
                    closed: false,
                });
                let e = parts.edges.len() - 1;
                chosen[ci].boundary.push(e);
                chosen[cj].boundary.push(e);
            }
            // Three: bevels meet in a point, fillets around a sphere.
            _ => match kind {
                Kind::Chamfer
                    if super::settings::settings().chamfer_corner
                        == super::settings::ChamferCorner::Facet =>
                {
                    // A facet through the three points that replace the
                    // vertex, one on each original face. The bevel of edge
                    // `k` contains the two on the faces that edge lies
                    // between, so it meets the facet along the line joining
                    // them.
                    let mut at = [0usize; 3];
                    for (k, slot) in at.iter_mut().enumerate() {
                        *slot = corner.points[k].ok_or(unsupported.clone())?;
                    }
                    let p = at.map(|v| parts.vertices[v]);
                    let normal = v3::normalize(v3::cross(v3::sub(p[1], p[0]), v3::sub(p[2], p[0])))
                        .ok_or(unsupported.clone())?;
                    // Outward: towards the vertex that was cut off at a
                    // convex corner, away from it at a concave one.
                    let gone = v3::sub(parts.vertices[vertex], p[0]);
                    let outward = if v3::dot(normal, gone) * convex >= 0.0 {
                        normal
                    } else {
                        v3::scale(normal, -1.0)
                    };
                    parts.surfaces.push(Surface::plane(p[0], outward));
                    let facet = parts.surfaces.len() - 1;
                    let mut around = Vec::with_capacity(3);
                    for k in 0..3 {
                        let (i, j) = ((k + 1) % 3, (k + 2) % 3);
                        let ck = which(k);
                        parts.edges.push(Edge {
                            surfaces: pair(chosen[ck].surface, facet),
                            vertices: vec![at[i], at[j]],
                            closed: false,
                        });
                        let e = parts.edges.len() - 1;
                        chosen[ck].boundary.push(e);
                        around.push(e);
                    }
                    fresh.push(parts.faces.len());
                    parts.faces.push(Face {
                        surface: facet,
                        edges: around,
                        flipped: false,
                        u_range: (0.0, 0.0),
                        v_range: (0.0, 0.0),
                        u_wraps: false,
                        v_wraps: false,
                        loops: None,
                    });
                }
                Kind::Chamfer => {
                    let mut rows = [[0.0; 3]; 3];
                    let mut rhs = [0.0; 3];
                    for i in 0..3 {
                        let Surface::Plane { origin, normal, .. } =
                            &parts.surfaces[chosen[which(i)].surface]
                        else {
                            return Err(unsupported);
                        };
                        rows[i] = *normal;
                        rhs[i] = v3::dot(*normal, *origin);
                    }
                    let apex = solve3(rows, rhs).ok_or(unsupported.clone())?;
                    let apex = parts.vertex(apex);
                    for k in 0..3 {
                        let (i, j) = ((k + 1) % 3, (k + 2) % 3);
                        let (ci, cj) = (which(i), which(j));
                        let to = corner.points[k].ok_or(unsupported.clone())?;
                        parts.edges.push(Edge {
                            surfaces: pair(chosen[ci].surface, chosen[cj].surface),
                            vertices: vec![apex, to],
                            closed: false,
                        });
                        let e = parts.edges.len() - 1;
                        chosen[ci].boundary.push(e);
                        chosen[cj].boundary.push(e);
                    }
                }
                Kind::Fillet => {
                    let o = centre().ok_or(unsupported.clone())?;
                    // Aimed so the patch sits on the equator at `u = 0`, as far
                    // from the poles and the branch cut as a sphere allows.
                    let mut towards = [0.0; 3];
                    for i in 0..3 {
                        let (_, out) =
                            plane_normals(body, corner.faces[i]).ok_or(unsupported.clone())?;
                        towards = v3::add(towards, v3::scale(out, convex));
                    }
                    let towards = v3::normalize(towards).ok_or(unsupported.clone())?;
                    for i in 0..3 {
                        let (_, out) =
                            plane_normals(body, corner.faces[i]).ok_or(unsupported.clone())?;
                        if v3::dot(towards, out) * convex < 0.2 {
                            return Err(unsupported);
                        }
                    }
                    parts.surfaces.push(
                        Surface::sphere(o, size)
                            .with_axis(perpendicular(towards))
                            .with_x_dir(towards),
                    );
                    let sphere = parts.surfaces.len() - 1;
                    let mut around = Vec::with_capacity(3);
                    for i in 0..3 {
                        let (j, k) = ((i + 1) % 3, (i + 2) % 3);
                        let ci = which(i);
                        let (Some(from), Some(to)) = (corner.points[j], corner.points[k]) else {
                            return Err(unsupported);
                        };
                        let cylinder = parts.surfaces[chosen[ci].surface].clone();
                        let Surface::Cylinder { axis, .. } = &cylinder else {
                            return Err(unsupported);
                        };
                        let between = section(
                            &cylinder,
                            o,
                            *axis,
                            parts.vertices[from],
                            parts.vertices[to],
                            tolerance,
                            &mut parts,
                        )
                        .ok_or(unsupported.clone())?;
                        let mut vertices = vec![from];
                        vertices.extend(between);
                        vertices.push(to);
                        parts.edges.push(Edge {
                            surfaces: pair(chosen[ci].surface, sphere),
                            vertices,
                            closed: false,
                        });
                        let e = parts.edges.len() - 1;
                        chosen[ci].boundary.push(e);
                        around.push(e);
                    }
                    fresh.push(parts.faces.len());
                    parts.faces.push(Face {
                        surface: sphere,
                        edges: around,
                        flipped: convex < 0.0,
                        u_range: (0.0, 0.0),
                        v_range: (0.0, 0.0),
                        u_wraps: false,
                        v_wraps: false,
                        loops: None,
                    });
                }
            },
        }
    }

    for c in &chosen {
        fresh.push(parts.faces.len());
        parts.faces.push(Face {
            surface: c.surface,
            edges: c.boundary.clone(),
            // A concave fillet is the inside of its cylinder.
            flipped: kind == Kind::Fillet && c.convex < 0.0,
            u_range: (0.0, 0.0),
            v_range: (0.0, 0.0),
            u_wraps: false,
            v_wraps: false,
            loops: None,
        });
    }

    // A flat face that was re-trimmed goes back to being bounded by its edges:
    // they are all it is bounded by, and a ring stated before the blend names
    // the corner that is no longer there.
    let mut retrimmed: Vec<usize> = corners.iter().flat_map(|c| c.faces).collect();
    retrimmed.sort_unstable();
    retrimmed.dedup();
    for &f in &retrimmed {
        parts.faces[f].loops = None;
    }

    // The new faces' rings, read off the edges just built. A curved one keeps
    // its ring: a fillet between two mitres is not a parameter rectangle.
    let probe = parts.body();
    for &f in &retrimmed {
        if !probe.face_loops(f).iter().any(|l| l.is_outer()) {
            return Err(BlendDeclined::TrimmedFace { face: f });
        }
    }
    for &f in &fresh {
        let loops = probe.face_loops(f);
        let [ring] = loops.as_slice() else {
            return Err(BlendDeclined::NotWatertight { defects: 0 });
        };
        if !ring.is_outer() {
            return Err(BlendDeclined::NotWatertight { defects: 0 });
        }
        let (mut lo, mut hi) = ([f64::MAX; 2], [f64::MIN; 2]);
        for c in &ring.uv {
            for k in 0..2 {
                lo[k] = lo[k].min(c[k]);
                hi[k] = hi[k].max(c[k]);
            }
        }
        let face = &mut parts.faces[f];
        face.u_range = (lo[0], hi[0]);
        face.v_range = (lo[1], hi[1]);
        if !matches!(parts.surfaces[face.surface], Surface::Plane { .. }) {
            face.loops = Some(loops);
        }
    }
    Ok(parts)
}

/// Blend the circular rim where a plane caps a cylinder.
///
/// There are four of these and they are one construction. The cylinder is a
/// shaft or a bore; the plane closes it from the material side (a shaft's end,
/// a hole's mouth — convex) or from the open side (a boss's foot, a blind
/// hole's floor — concave). In every case the plane's rim moves radially *into
/// the plane's face* and the cylinder's rim moves axially *into the cylinder's
/// face*, by the same amount, and the blend is the cone or the torus through
/// the two circles that result.
fn blend_rim(
    parts: &mut Parts,
    edge: usize,
    size: f64,
    kind: Kind,
    tolerance: f64,
) -> Result<(), BlendDeclined> {
    let unsupported = BlendDeclined::UnsupportedEdge { edge };
    let too_large = BlendDeclined::TooLarge { edge };
    let eps = 1e-9 * extent(&parts.vertices);

    let users: Vec<usize> = (0..parts.faces.len())
        .filter(|&f| parts.faces[f].edges.contains(&edge))
        .collect();
    let &[f0, f1] = users.as_slice() else {
        return Err(unsupported);
    };
    let is_plane = |f: usize| {
        matches!(
            parts.surfaces[parts.faces[f].surface],
            Surface::Plane { .. }
        )
    };
    let (cap, wall) = if is_plane(f0) { (f0, f1) } else { (f1, f0) };
    let (
        Surface::Plane {
            origin: cap_origin,
            normal: cap_normal,
            ..
        },
        Surface::Cylinder {
            origin,
            axis,
            x_dir,
            radius,
        },
    ) = (
        parts.surfaces[parts.faces[cap].surface].clone(),
        parts.surfaces[parts.faces[wall].surface].clone(),
    )
    else {
        return Err(unsupported);
    };
    if v3::dot(cap_normal, axis).abs() < 1.0 - 1e-9 {
        return Err(unsupported);
    }
    // The wall has to be the plain band between two rims; one a boolean has
    // trimmed states rings this does not know how to move.
    if parts.faces[wall].loops.is_some() {
        return Err(BlendDeclined::TrimmedFace { face: wall });
    }
    if !parts.faces[wall].u_wraps {
        return Err(unsupported);
    }

    // Heights along the axis, which is the wall's `v`.
    let height = v3::dot(v3::sub(cap_origin, origin), axis);
    let (v0, v1) = parts.faces[wall].v_range;
    let near_end = if (v0 - height).abs() <= (v1 - height).abs() {
        0
    } else {
        1
    };
    let far = if near_end == 0 { v1 } else { v0 };
    let into_wall = if far > height { 1.0 } else { -1.0 };
    if (far - height).abs() <= size + eps {
        return Err(too_large);
    }

    let cap_out = if parts.faces[cap].flipped {
        v3::scale(cap_normal, -1.0)
    } else {
        cap_normal
    };
    // Convex when the wall leaves the cap on the cap's material side.
    let convex = if v3::dot(axis, cap_out) * into_wall < 0.0 {
        1.0
    } else {
        -1.0
    };
    // A shaft is solid inside its cylinder, a bore solid outside it.
    let shaft = if parts.faces[wall].flipped { -1.0 } else { 1.0 };
    let grows = -shaft * convex;
    let cap_radius = radius + grows * size;
    let wall_height = height + into_wall * size;
    if cap_radius <= eps {
        return Err(too_large);
    }
    // Whatever else bounds the cap must be clear of the ring the rim sweeps.
    // Judged by segment: a square plate's sides come nearest the hole between
    // their ends, not at them.
    let on_axis = |h: f64| v3::add(origin, v3::scale(axis, h));
    let (inner, outer) = (radius.min(cap_radius), radius.max(cap_radius));
    let hub = on_axis(height);
    for &e in &parts.faces[cap].edges {
        if e == edge {
            continue;
        }
        for w in parts.edges[e].vertices.windows(2) {
            let (p, q) = (parts.vertices[w[0]], parts.vertices[w[1]]);
            let pq = v3::sub(q, p);
            let t = (v3::dot(v3::sub(hub, p), pq) / v3::dot(pq, pq).max(1e-300)).clamp(0.0, 1.0);
            let nearest = v3::dist(hub, v3::add(p, v3::scale(pq, t)));
            let farthest = v3::dist(hub, p).max(v3::dist(hub, q));
            if nearest < outer + eps && farthest > inner - eps {
                return Err(too_large);
            }
        }
    }
    let (surface, v_range, flipped) = match kind {
        Kind::Chamfer => {
            // A 45° cone opening from the smaller circle to the larger.
            let widens = if cap_radius > radius {
                -into_wall
            } else {
                into_wall
            };
            let apex = on_axis(wall_height - widens * radius);
            (
                Surface::cone(apex, v3::scale(axis, widens), FRAC_PI_4).with_x_dir(x_dir),
                (radius.min(cap_radius), radius.max(cap_radius)),
                shaft < 0.0,
            )
        }
        Kind::Fillet => {
            // The tube's centre is under the cap's new rim and beside the
            // wall's: `size` from each.
            let at_cap = -into_wall * FRAC_PI_2;
            let at_wall = if grows < 0.0 { 0.0 } else { -into_wall * PI };
            (
                Surface::torus(on_axis(wall_height), axis, cap_radius, size).with_x_dir(x_dir),
                (at_cap.min(at_wall), at_cap.max(at_wall)),
                convex < 0.0,
            )
        }
    };

    // Both rims at the same angles, fine enough for the larger.
    let widest = radius.max(cap_radius);
    let n = if tolerance < widest {
        ((PI / (1.0 - tolerance / widest).acos()).ceil() as usize).clamp(16, 4096)
    } else {
        16
    };
    let y_dir = v3::cross(axis, x_dir);
    let ring = |h: f64, r: f64, parts: &mut Parts| -> Vec<usize> {
        let mut ids: Vec<usize> = (0..n)
            .map(|i| {
                let (s, c) = (-PI + TAU * i as f64 / n as f64).sin_cos();
                let radial = v3::add(v3::scale(x_dir, c), v3::scale(y_dir, s));
                parts.vertex(v3::add(on_axis(h), v3::scale(radial, r)))
            })
            .collect();
        ids.push(ids[0]);
        ids
    };
    let cap_rim = ring(height, cap_radius, parts);
    let wall_rim = ring(wall_height, radius, parts);

    parts.surfaces.push(surface);
    let blend = parts.surfaces.len() - 1;
    let (cap_surface, wall_surface) = (parts.faces[cap].surface, parts.faces[wall].surface);
    parts.edges[edge] = Edge {
        surfaces: pair(cap_surface, blend),
        vertices: cap_rim,
        closed: true,
    };
    parts.edges.push(Edge {
        surfaces: pair(wall_surface, blend),
        vertices: wall_rim,
        closed: true,
    });
    let wall_edge = parts.edges.len() - 1;

    let face = &mut parts.faces[wall];
    for slot in face.edges.iter_mut() {
        if *slot == edge {
            *slot = wall_edge;
        }
    }
    if near_end == 0 {
        face.v_range.0 = wall_height;
    } else {
        face.v_range.1 = wall_height;
    }
    // The cap is flat, so its edges are all that bound it.
    parts.faces[cap].loops = None;
    parts.faces.push(Face {
        surface: blend,
        edges: vec![edge, wall_edge],
        flipped,
        u_range: (-PI, PI),
        v_range,
        u_wraps: true,
        v_wraps: false,
        loops: None,
    });
    if !parts.body().face_loops(cap).iter().any(|l| l.is_outer()) {
        return Err(BlendDeclined::TrimmedFace { face: cap });
    }
    Ok(())
}