BREP_offset 0.23.0

Solid offsets, shells and thickening of the BREP kernel.
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
//! `BREP_OFFSET_REVOLVED_PARALLEL` (default on; `=0` restores the refusal): the
//! rounded GROWTH of a solid of revolution, built from its half-section.
//!
//! A solid of revolution's distance to a point is read in that point's
//! meridian plane, so its parallel body `K ⊕ B_d` is the revolution of its full
//! meridian section grown by the disk of radius `d`. Where every edge of the
//! section is convex, that grown section is bounded by each boundary piece
//! moved out by `d` (a line to the parallel line, an arc to the concentric arc
//! of radius `R ± d`) and, at each corner, the arc of radius `d` about the
//! corner from the one piece's normal to the next's: the rolling ball's torus
//! about a circular rim. The lane reads the half-section off the body (every
//! edge a circle about one axis, every face a plane square to it, a cylinder or
//! cone about it, a sphere centred on it, or a torus about it), offsets it, and
//! revolves it.
//!
//! Cause: a hemisphere, a ball cut by a plane
//! and the lens two balls share, each grown by 1, refused ("completion produced
//! non-integral genus", "unwelded rim leaves a non-watertight shell"). The
//! sharp body the pipeline rounds needs each face's carrier to run past its
//! own rim to meet its neighbour's offset; a plane's net slides out under its
//! trims, but a sphere's trim stays on the source rim, so the moved plane and
//! the moved sphere never meet and their imprint is empty.
//!
//! It runs only where the pipeline's own growth refused, and declines (the
//! pipeline's refusal stands) on anything else: a concave corner, a face of
//! another kind or about another axis, an edge that is not a circle about the
//! axis, a piece whose offset would pass through the axis, or a revolved body
//! that does not validate.
use super::*;
use crate::{make_arc, make_line, parameter_point_in_face, project_point_to_surface, revolve_profile_brep};
use crate::{AnalyticSurface, KernelRefusal, KernelStage, NurbsCurve, OrRefuse, PolygonClass, Vec2};

/// The switch, default on (`=0` restores the pipeline's refusal).
fn revolved_parallel_on() -> bool {
    switch!("BREP_OFFSET_REVOLVED_PARALLEL", true)
}


/// A point of the meridian half-plane: distance from the axis, height along it.
#[derive(Clone, Copy, Debug)]
struct P2 {
    rho: f64,
    z: f64,
}

impl P2 {
    fn sub(self, other: P2) -> P2 {
        P2 { rho: self.rho - other.rho, z: self.z - other.z }
    }
    fn add(self, other: P2) -> P2 {
        P2 { rho: self.rho + other.rho, z: self.z + other.z }
    }
    fn scale(self, k: f64) -> P2 {
        P2 { rho: self.rho * k, z: self.z * k }
    }
    fn length(self) -> f64 {
        self.rho.hypot(self.z)
    }
    fn cross(self, other: P2) -> f64 {
        self.rho * other.z - self.z * other.rho
    }
}

/// One piece of the half-section's boundary, from `start` to `end`.
#[derive(Clone, Copy, Debug)]
enum Piece {
    Line { start: P2, end: P2 },
    /// About `center`, anticlockwise (in (ρ, z)) when `ccw`.
    Arc { center: P2, radius: f64, start: P2, end: P2, ccw: bool },
}

impl Piece {
    fn start(&self) -> P2 {
        match *self {
            Piece::Line { start, .. } | Piece::Arc { start, .. } => start,
        }
    }
    fn end(&self) -> P2 {
        match *self {
            Piece::Line { end, .. } | Piece::Arc { end, .. } => end,
        }
    }
    fn reversed(&self) -> Piece {
        match *self {
            Piece::Line { start, end } => Piece::Line { start: end, end: start },
            Piece::Arc { center, radius, start, end, ccw } => Piece::Arc { center, radius, start: end, end: start, ccw: !ccw },
        }
    }
    /// Signed sweep (anticlockwise positive) of an arc from start to end.
    fn sweep(center: P2, start: P2, end: P2, ccw: bool) -> f64 {
        let a0 = (start.z - center.z).atan2(start.rho - center.rho);
        let a1 = (end.z - center.z).atan2(end.rho - center.rho);
        let mut sweep = a1 - a0;
        if ccw {
            while sweep <= 0.0 {
                sweep += std::f64::consts::TAU;
            }
        } else {
            while sweep >= 0.0 {
                sweep -= std::f64::consts::TAU;
            }
        }
        sweep
    }
    /// The point at `fraction` of the way along.
    fn at(&self, fraction: f64) -> P2 {
        match *self {
            Piece::Line { start, end } => start.add(end.sub(start).scale(fraction)),
            Piece::Arc { center, radius, start, end, ccw } => {
                let a0 = (start.z - center.z).atan2(start.rho - center.rho);
                let a = a0 + fraction * Piece::sweep(center, start, end, ccw);
                P2 { rho: center.rho + radius * a.cos(), z: center.z + radius * a.sin() }
            }
        }
    }
    /// The distance from `p` to this piece.
    fn distance(&self, p: P2) -> f64 {
        let ends = p.sub(self.start()).length().min(p.sub(self.end()).length());
        match *self {
            Piece::Line { start, end } => {
                let along = end.sub(start);
                let length2 = along.rho * along.rho + along.z * along.z;
                if !(length2 > 0.0) {
                    return ends;
                }
                let w = p.sub(start);
                let t = (w.rho * along.rho + w.z * along.z) / length2;
                if (0.0..=1.0).contains(&t) { p.sub(start.add(along.scale(t))).length() } else { ends }
            }
            Piece::Arc { center, radius, start, end, ccw } => {
                let a0 = (start.z - center.z).atan2(start.rho - center.rho);
                let sweep = Piece::sweep(center, start, end, ccw);
                let mut delta = (p.z - center.z).atan2(p.rho - center.rho) - a0;
                if ccw {
                    delta = delta.rem_euclid(std::f64::consts::TAU);
                } else {
                    delta = -(-delta).rem_euclid(std::f64::consts::TAU);
                }
                if delta.abs() <= sweep.abs() { (p.sub(center).length() - radius).abs() } else { ends }
            }
        }
    }
    /// The point halfway along.
    fn middle(&self) -> P2 {
        match *self {
            Piece::Line { start, end } => start.add(end).scale(0.5),
            Piece::Arc { center, radius, start, end, ccw } => {
                let a0 = (start.z - center.z).atan2(start.rho - center.rho);
                let a = a0 + 0.5 * Piece::sweep(center, start, end, ccw);
                P2 { rho: center.rho + radius * a.cos(), z: center.z + radius * a.sin() }
            }
        }
    }
    /// The unit tangent at the start (`at_end` false) or the end.
    fn tangent(&self, at_end: bool) -> Option<P2> {
        let t = match *self {
            Piece::Line { start, end } => end.sub(start),
            Piece::Arc { center, start, end, ccw, .. } => {
                let p = if at_end { end } else { start };
                let r = p.sub(center);
                if ccw { P2 { rho: -r.z, z: r.rho } } else { P2 { rho: r.z, z: -r.rho } }
            }
        };
        let length = t.length();
        (length > 0.0).then(|| t.scale(1.0 / length))
    }
    /// Twice the signed area this piece sweeps with the origin of (ρ, z)
    /// (exact for an arc: the chord's triangle plus the segment).
    fn area2(&self) -> f64 {
        let (start, end) = (self.start(), self.end());
        let chord = start.cross(end);
        match *self {
            Piece::Line { .. } => chord,
            Piece::Arc { center, radius, start, end, ccw } => {
                let sweep = Piece::sweep(center, start, end, ccw);
                chord + radius * radius * (sweep - sweep.sin())
            }
        }
    }
}

/// The lane's answer, or `None` when it declines or the switch is off.
pub(super) fn revolved_parallel(source: &BrepSolid, distance: f64) -> Option<OffsetShellResultRecord> {
    if !revolved_parallel_on() || !(distance > 0.0) {
        return None;
    }
    match revolved_parallel_impl(source, distance) {
        Ok(Some(solid)) => {
            let face_images = solid
                .shells
                .iter()
                .flat_map(|shell| &shell.faces)
                .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
                .collect();
            Some(OffsetShellResultRecord { solid, face_images })
        }
        Ok(None) => None,
        Err(error) => {
            os_debug!("revolved parallel lane declined: {error}");
            None
        }
    }
}

/// The axis (a point and a unit direction) and the body's frame across it.
struct Axis {
    origin: Vec3,
    axis: Vec3,
    x: Vec3,
}

impl Axis {
    fn to_2d(&self, p: Vec3) -> P2 {
        let w = p.sub(self.origin);
        let z = w.dot(self.axis);
        P2 { rho: w.sub(self.axis.scale(z)).length(), z }
    }
    /// The point of the meridian half-plane at azimuth `phi` from `x`.
    fn to_3d(&self, p: P2, phi: f64) -> Vec3 {
        let y = self.axis.cross(self.x);
        let radial = self.x.scale(phi.cos()).add(y.scale(phi.sin()));
        self.origin.add(radial.scale(p.rho)).add(self.axis.scale(p.z))
    }
    fn on_axis(&self, p: Vec3, tolerance: f64) -> bool {
        let w = p.sub(self.origin);
        w.sub(self.axis.scale(w.dot(self.axis))).length() <= tolerance
    }
    fn parallel(&self, direction: Vec3) -> bool {
        direction.normalized().is_ok_and(|d| d.cross(self.axis).length() <= 1e-9)
    }
}

/// Whether the half-section point `p` (at an azimuth off any seam) lies on `face`.
fn on_face(face: &FaceRecord, axis: &Axis, p: P2, tolerance: f64) -> bool {
    let point = axis.to_3d(p, 1.0);
    let Ok(hit) = project_point_to_surface(&face.surface, point) else { return false };
    if hit.distance > tolerance {
        return false;
    }
    parameter_point_in_face(face, Vec2 { x: hit.u, y: hit.v }, 1e-9).is_ok_and(|class| class == PolygonClass::Inside)
}

/// `BREP_OFFSET_REVOLVED_COLLAPSED_ARC` (default on; `=0` restores the
/// refusal): a concave section arc grown by exactly its radius.
fn collapsed_arc_enabled() -> bool {
    switch!("BREP_OFFSET_REVOLVED_COLLAPSED_ARC", true)
}

/// `BREP_OFFSET_REVOLVED_FITTED_TORUS` (default on; `=0` restores): see
/// [`fitted_meridian_circle`].
fn fitted_meridian_circle_enabled() -> bool {
    switch!("BREP_OFFSET_REVOLVED_FITTED_TORUS", true)
}

/// The meridian circle (centre, radius) a face with no analytic reading lies
/// on, or `None`: its surface sampled over the face's parameter box (and its
/// boundary), every sample read in the meridian half-plane, a circle fitted
/// to them, and every sample within `tolerance` of it. A filleted ball's root
/// (a ball on a plate, its tangent fillet rolled round the circle where they
/// meet) is such a patch: the lane declined the body ("not read") and its
/// rounded growth refused.
fn fitted_meridian_circle(face: &FaceRecord, axis: &Axis, tolerance: f64) -> Result<Option<(P2, f64)>, KernelRefusal> {
    // Stations that SETTLE the question, not a sample of it: on one knot
    // span the surface is (X, Y, Z) / W with polynomials of degree p in u and
    // q in v, so the torus's implicit quartic times W^4 is a polynomial of
    // degree 4p by 4q there. It vanishes on the whole span (the patch lies on
    // the torus) when it is small at 4p + 1 by 4q + 1 Chebyshev stations, up
    // to their Lebesgue constant (about 3 at these counts), which the
    // tolerance below keeps a factor 4 of. A bump of any shape on the span
    // (degree-elevated or not) is a non-zero polynomial of that degree, and
    // shows at its stations.
    let stations = |knots: &[f64], degree: usize| -> Vec<f64> {
        let mut distinct: Vec<f64> = Vec::new();
        for &knot in knots {
            if distinct.last().is_none_or(|last| knot > *last) {
                distinct.push(knot);
            }
        }
        let count = 4 * degree.max(1) + 1;
        let mut out = Vec::new();
        for pair in distinct.windows(2) {
            out.push(pair[0]);
            for k in 0..count {
                let node = 0.5 - 0.5 * (std::f64::consts::PI * (2 * k + 1) as f64 / (2 * count) as f64).cos();
                out.push(pair[0] + (pair[1] - pair[0]) * node);
            }
        }
        if let Some(last) = distinct.last() {
            out.push(*last);
        }
        out
    };
    let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Classify, "domain_u")?;
    let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Classify, "domain_v")?;
    let in_domain = |t: f64, lo: f64, hi: f64| t >= lo && t <= hi;
    let us: Vec<f64> = stations(&face.surface.knots_u, face.surface.degree_u).into_iter().filter(|t| in_domain(*t, u0, u1)).collect();
    let vs: Vec<f64> = stations(&face.surface.knots_v, face.surface.degree_v).into_iter().filter(|t| in_domain(*t, v0, v1)).collect();
    if us.len() < 2 || vs.len() < 2 || us.len() * vs.len() > 40_000 {
        return Ok(None);
    }
    let mut points = Vec::new();
    for &u in &us {
        for &v in &vs {
            let p = face.surface.evaluate(u, v).or_refuse(KernelStage::Classify, "evaluate")?;
            points.push(axis.to_2d(p));
        }
    }
    // Algebraic (Kasa) fit: rho^2 + z^2 + D rho + E z + F = 0, centred on the
    // mean for conditioning.
    let n = points.len() as f64;
    let (mr, mz) = (points.iter().map(|p| p.rho).sum::<f64>() / n, points.iter().map(|p| p.z).sum::<f64>() / n);
    let mut m = [[0.0f64; 3]; 3];
    let mut rhs = [0.0f64; 3];
    for p in &points {
        let (x, y) = (p.rho - mr, p.z - mz);
        let row = [x, y, 1.0];
        let target = -(x * x + y * y);
        for r in 0..3 {
            for c in 0..3 {
                m[r][c] += row[r] * row[c];
            }
            rhs[r] += row[r] * target;
        }
    }
    let det = |m: &[[f64; 3]; 3]| {
        m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
            + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
    };
    let whole = det(&m);
    if !(whole.abs() > 1e-300) {
        return Ok(None);
    }
    let mut solution = [0.0f64; 3];
    for k in 0..3 {
        let mut replaced = m;
        for r in 0..3 {
            replaced[r][k] = rhs[r];
        }
        solution[k] = det(&replaced) / whole;
    }
    let [d, e, f] = solution;
    let center = P2 { rho: mr - d * 0.5, z: mz - e * 0.5 };
    let squared = d * d * 0.25 + e * e * 0.25 - f;
    if !(squared > 0.0) {
        return Ok(None);
    }
    let radius = squared.sqrt();
    let worst = points
        .iter()
        .map(|p| ((p.rho - center.rho).hypot(p.z - center.z) - radius).abs())
        .fold(0.0f64, f64::max);
    if worst > tolerance * 0.25 {
        os_debug!("revolved parallel lane: face {} leaves its meridian circle by {worst:.3e}", face.id);
        return Ok(None);
    }
    Ok(Some((center, radius)))
}

fn revolved_parallel_impl(source: &BrepSolid, distance: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
    let [shell] = source.shells.as_slice() else { return Ok(None) };
    let scale = crate::solid_scale(source).max(1.0);
    let tolerance = 1e-9 * scale;

    // Each edge: its faces, by how many coedges of each face walk it.
    let mut uses: std::collections::HashMap<u64, Vec<usize>> = std::collections::HashMap::new();
    for (index, face) in shell.faces.iter().enumerate() {
        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
            uses.entry(coedge.edge_id).or_default().push(index);
        }
    }
    // The rims: edges between two different faces. Each must be a circle,
    // all about one axis.
    let mut axis: Option<Axis> = None;
    let mut rims: Vec<(u64, P2, [usize; 2])> = Vec::new();
    for edge in &source.edges {
        let Some(faces) = uses.get(&edge.id) else { continue };
        if edge.degenerate {
            continue;
        }
        if faces.len() == 2 && faces[0] == faces[1] {
            continue; // a seam
        }
        let [a, b] = faces.as_slice() else { return Ok(None) };
        let Some(circle) = super::rim_welds::fit_rim_circle(edge, tolerance)? else { return Ok(None) };
        if axis.is_none() {
            let x = circle.axis.perpendicular().or_refuse(KernelStage::Classify, "perpendicular")?;
            axis = Some(Axis { origin: circle.center, axis: circle.axis, x });
        }
        let frame = axis.as_ref().expect("set above");
        if !frame.parallel(circle.axis) || !frame.on_axis(circle.center, tolerance) {
            return Ok(None);
        }
        rims.push((edge.id, frame.to_2d(edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Classify, "evaluate")?), [*a, *b]));
    }
    let Some(axis) = axis else { return Ok(None) };

    // Each face's piece of the half-section.
    let mut pieces: Vec<(usize, Piece, [Option<usize>; 2])> = Vec::new();
    for (index, face) in shell.faces.iter().enumerate() {
        let ends: Vec<usize> = rims.iter().enumerate().filter(|(_, rim)| rim.2.contains(&index)).map(|(k, _)| k).collect();
        let generatrix = match face.surface.analytic() {
            Some(AnalyticSurface::Plane { u_dir, v_dir, .. }) => {
                if !axis.parallel(u_dir.cross(*v_dir)) {
                    return Ok(None);
                }
                None
            }
            Some(AnalyticSurface::RuledRevolution { frame, .. }) => {
                if !axis.parallel(frame.axis) || !axis.on_axis(frame.origin, tolerance) {
                    return Ok(None);
                }
                None
            }
            Some(AnalyticSurface::Sphere { frame, radius }) => {
                if !axis.on_axis(frame.origin, tolerance) {
                    return Ok(None);
                }
                Some((axis.to_2d(frame.origin), *radius))
            }
            Some(AnalyticSurface::Torus { frame, major_radius, minor_radius }) => {
                if !axis.parallel(frame.axis) || !axis.on_axis(frame.origin, tolerance) {
                    return Ok(None);
                }
                let h = frame.origin.sub(axis.origin).dot(axis.axis);
                Some((P2 { rho: *major_radius, z: h }, *minor_radius))
            }
            // A face with no analytic reading (a fillet rolled round a
            // rim is a fitted NURBS patch): it lies on a torus about the axis
            // when every point of it lies on one circle of the meridian plane.
            None if fitted_meridian_circle_enabled() => match fitted_meridian_circle(face, &axis, 1e-7 * scale)? {
                Some(circle) => Some(circle),
                None => return Ok(None),
            },
            _ => return Ok(None),
        };
        let piece = match (ends.as_slice(), generatrix) {
            // Between two rims: a segment, or the arc of the generatrix circle
            // through the face.
            ([a, b], None) => Piece::Line { start: rims[*a].1, end: rims[*b].1 },
            ([a, b], Some((center, radius))) => {
                let (start, end) = (rims[*a].1, rims[*b].1);
                let ccw = Piece::Arc { center, radius, start, end, ccw: true };
                let cw = Piece::Arc { center, radius, start, end, ccw: false };
                // The arc that stays in the half-plane and runs through the face.
                let holds = |piece: &Piece| piece.middle().rho > tolerance && on_face(face, &axis, piece.middle(), 1e-7 * scale);
                match (holds(&ccw), holds(&cw)) {
                    (true, false) => ccw,
                    (false, true) => cw,
                    _ => return Ok(None),
                }
            }
            // From one rim to the axis: a disk, a cone to its apex, a sphere to
            // the pole on the face.
            ([a], None) => {
                let start = rims[*a].1;
                let axis_end = match face.surface.analytic() {
                    Some(AnalyticSurface::Plane { origin, .. }) => P2 { rho: 0.0, z: axis.to_2d(*origin).z },
                    _ => return Ok(None),
                };
                Piece::Line { start, end: axis_end }
            }
            ([a], Some((center, radius))) => {
                if center.rho.abs() > tolerance {
                    return Ok(None);
                }
                let start = rims[*a].1;
                let mut found = None;
                for pole in [P2 { rho: 0.0, z: center.z + radius }, P2 { rho: 0.0, z: center.z - radius }] {
                    let ccw = Piece::sweep(center, start, pole, true).abs() <= std::f64::consts::PI + 1e-12;
                    let piece = Piece::Arc { center, radius, start, end: pole, ccw };
                    if on_face(face, &axis, piece.middle(), 1e-7 * scale) {
                        if found.is_some() {
                            return Ok(None);
                        }
                        found = Some(piece);
                    }
                }
                match found {
                    Some(piece) => piece,
                    None => return Ok(None),
                }
            }
            _ => return Ok(None),
        };
        let ends: Vec<Option<usize>> = ends.iter().map(|k| Some(*k)).collect();
        pieces.push((index, piece, [ends.first().copied().flatten(), ends.get(1).copied().flatten()]));
    }

    // Order the pieces into one chain from the axis back to the axis, or one
    // loop clear of it, joined at the rims.
    let chain = order_pieces(&pieces, &rims, tolerance)?;
    let Some(mut chain) = chain else { return Ok(None) };
    let touches_axis = chain.first().is_some_and(|p| p.start().rho.abs() <= tolerance);
    // A closed loop has no first piece: start it on a piece that does not
    // collapse (a concave arc grown by its radius is dropped between its two
    // neighbours, so it must not sit at either end of the walk).
    if !touches_axis {
        let collapses = |piece: &Piece| {
            matches!(*piece, Piece::Arc { radius, ccw: false, .. } if (radius - distance).abs() <= 1e-7 * scale)
        };
        let count = chain.len();
        if let Some(start) = (0..count).find(|&k| !collapses(&chain[k]) && !collapses(&chain[(k + count - 1) % count])) {
            chain.rotate_left(start);
        }
    }
    // The closing run along the axis (ρ = 0) sweeps no area about the origin
    // of (ρ, z), so the pieces alone give the orientation.
    let area2: f64 = chain.iter().map(Piece::area2).sum();
    if area2 < 0.0 {
        chain = chain.iter().rev().map(Piece::reversed).collect();
    }

    // Offset every piece outward; round every corner; decline a concave one.
    let outward = |piece: &Piece, at_end: bool| -> Option<P2> {
        piece.tangent(at_end).map(|t| P2 { rho: t.z, z: -t.rho })
    };
    let mut grown: Vec<Piece> = Vec::new();
    // A concave arc grown by exactly its radius (a fillet's root grown by the
    // fillet's radius) shrinks to its centre: it is dropped, and its two
    // neighbours' offsets meet there in a sharp edge, with no corner arc.
    let collapse = 1e-7 * scale;
    let mut after_collapse = false;
    for (k, piece) in chain.iter().enumerate() {
        let moved = match *piece {
            Piece::Line { start, end } => {
                let Some(n) = outward(piece, false) else { return Ok(None) };
                Piece::Line { start: start.add(n.scale(distance)), end: end.add(n.scale(distance)) }
            }
            Piece::Arc { center, radius, start, end, ccw } => {
                let r = if ccw { radius + distance } else { radius - distance };
                if !ccw && r.abs() <= collapse && collapsed_arc_enabled() && k > 0 && k + 1 < chain.len() {
                    after_collapse = true;
                    continue;
                }
                if !(r > tolerance) {
                    return Ok(None);
                }
                let k = r / radius;
                Piece::Arc { center, radius: r, start: center.add(start.sub(center).scale(k)), end: center.add(end.sub(center).scale(k)), ccw }
            }
        };
        if after_collapse {
            after_collapse = false;
            let Some(last) = grown.last() else { return Ok(None) };
            if last.end().sub(moved.start()).length() > collapse {
                os_debug!("revolved parallel lane: the offsets beside a collapsed arc miss by {:.3e}", last.end().sub(moved.start()).length());
                return Ok(None);
            }
            grown.push(moved);
            continue;
        }
        if k > 0 {
            let previous = &chain[k - 1];
            let corner = piece.start();
            let (Some(n1), Some(n2)) = (outward(previous, true), outward(piece, false)) else { return Ok(None) };
            let turn = n1.cross(n2);
            if turn < -1e-12 {
                os_debug!("revolved parallel lane: concave corner at ({:.6}, {:.6}), turn {turn:.3e}", corner.rho, corner.z);
                return Ok(None); // concave
            }
            if turn > 1e-12 || n1.rho * n2.rho + n1.z * n2.z < 0.0 {
                grown.push(Piece::Arc {
                    center: corner,
                    radius: distance,
                    start: corner.add(n1.scale(distance)),
                    end: corner.add(n2.scale(distance)),
                    ccw: true,
                });
            }
        }
        grown.push(moved);
    }
    if touches_axis {
        let (first, last) = (grown[0].start(), grown[grown.len() - 1].end());
        if first.rho.abs() > tolerance || last.rho.abs() > tolerance {
            return Ok(None); // an end leaves the axis: an apex, not built here
        }
        grown.push(Piece::Line { start: last, end: first });
    } else {
        let (last, first) = (&chain[chain.len() - 1], &chain[0]);
        let corner = first.start();
        let (Some(n1), Some(n2)) = (outward(last, true), outward(first, false)) else { return Ok(None) };
        let turn = n1.cross(n2);
        if turn < -1e-12 {
            return Ok(None);
        }
        if turn > 1e-12 || n1.rho * n2.rho + n1.z * n2.z < 0.0 {
            grown.push(Piece::Arc {
                center: corner,
                radius: distance,
                start: corner.add(n1.scale(distance)),
                end: corner.add(n2.scale(distance)),
                ccw: true,
            });
        }
    }
    // A loop clear of the axis whose growth crosses it (a bore grown shut):
    // the grown half-section is the loop's own growth cut at ρ = 0, since a
    // point with ρ ≥ 0 is never nearer the section's mirror half than its own
    // ((ρ + a)² ≥ (ρ − a)² for a ≥ 0). The part kept must be one run, closed
    // up the axis.
    if !touches_axis && grown.iter().any(|piece| piece.start().rho < -tolerance || piece.middle().rho < -tolerance) {
        let split: Vec<Piece> = grown.iter().flat_map(|piece| split_at_axis(piece, tolerance)).collect();
        let kept: Vec<bool> = split.iter().map(|piece| piece.middle().rho >= -tolerance).collect();
        let count = split.len();
        let starts: Vec<usize> = (0..count).filter(|&k| kept[k] && !kept[(k + count - 1) % count]).collect();
        let [first] = starts.as_slice() else { return Ok(None) };
        let mut run: Vec<Piece> = Vec::new();
        for offset in 0..count {
            let k = (first + offset) % count;
            if !kept[k] {
                break;
            }
            run.push(split[k]);
        }
        let (head, tail) = (run[0].start(), run[run.len() - 1].end());
        if head.rho.abs() > 1e-7 * scale || tail.rho.abs() > 1e-7 * scale {
            return Ok(None);
        }
        let snap = |p: P2| P2 { rho: 0.0, z: p.z };
        let last = run.len() - 1;
        run[0] = with_start(&run[0], snap(head));
        run[last] = with_end(&run[last], snap(tail));
        run.push(Piece::Line { start: snap(tail), end: snap(head) });
        grown = run;
    }
    // Every grown piece stays in the half-plane.
    for piece in &grown {
        for p in [piece.start(), piece.end(), piece.middle()] {
            if p.rho < -tolerance {
                return Ok(None);
            }
        }
    }

    // The corners were read one at a time, so growths that meet across a gap
    // (the two rims of a narrow groove) are not seen there. Every point of the
    // true boundary lies exactly the distance from the section: a grown piece
    // with a point nearer than that to any source piece is not the boundary,
    // and the lane declines.
    for piece in &grown {
        if matches!(piece, Piece::Line { start, end } if start.rho.abs() <= tolerance && end.rho.abs() <= tolerance) {
            continue; // the closing run along the axis
        }
        for step in 1..16 {
            let p = piece.at(step as f64 / 16.0);
            let nearest = chain.iter().map(|source| source.distance(p)).fold(f64::INFINITY, f64::min);
            if nearest < distance - 1e-7 * scale {
                os_debug!("revolved parallel lane declined: a grown piece passes {nearest:.6} from the section, under {distance:.6}");
                return Ok(None);
            }
        }
    }

    // The grown half-section as curves in the plane of `x` and the axis, revolved.
    let mut curves: Vec<NurbsCurve> = Vec::with_capacity(grown.len());
    for piece in &grown {
        let curve = match *piece {
            Piece::Line { start, end } => {
                if start.sub(end).length() <= tolerance {
                    continue;
                }
                make_line(axis.to_3d(start, 0.0), axis.to_3d(end, 0.0)).or_refuse(KernelStage::Sew, "make_line")?
            }
            Piece::Arc { center, radius, start, end, ccw } => {
                let a0 = (start.z - center.z).atan2(start.rho - center.rho);
                let sweep = Piece::sweep(center, start, end, ccw);
                // A corner arc at a join the fitted faces leave a hair off
                // tangent (a fillet's rims) sweeps nothing: the pieces meet.
                if sweep.abs() * radius <= tolerance.max(1e-7 * radius) {
                    continue;
                }
                let c = axis.to_3d(center, 0.0);
                if ccw {
                    make_arc(c, axis.x, axis.axis, radius, a0, a0 + sweep).or_refuse(KernelStage::Sew, "make_arc")?
                } else {
                    make_arc(c, axis.x, axis.axis, radius, a0 + sweep, a0)
                        .and_then(|arc| arc.reversed())
                        .or_refuse(KernelStage::Sew, "make_arc")?
                }
            }
        };
        curves.push(curve);
    }
    let solid = revolve_profile_brep(&curves, axis.origin, axis.axis, std::f64::consts::TAU).or_refuse(KernelStage::Sew, "revolve")?;
    if !solid.validate().is_empty() {
        return Ok(None);
    }
    os_debug!("revolved parallel lane built {} faces from {} section pieces", solid.shells.iter().map(|s| s.faces.len()).sum::<usize>(), grown.len());
    Ok(Some(solid))
}

/// The pieces in boundary order: from an axis end round to the other, or
/// round a loop, consecutive pieces sharing a rim. `None` where they do not
/// form one such run.
fn order_pieces(
    pieces: &[(usize, Piece, [Option<usize>; 2])],
    rims: &[(u64, P2, [usize; 2])],
    tolerance: f64,
) -> Result<Option<Vec<Piece>>, KernelRefusal> {
    let _ = rims;
    if pieces.is_empty() {
        return Ok(None);
    }
    let close = |a: P2, b: P2| a.sub(b).length() <= 1e-7 * (1.0 + a.length()).max(tolerance);
    let mut used = vec![false; pieces.len()];
    // Start at a piece with an axis end, if any, oriented to leave the axis.
    let start_index = pieces.iter().position(|(_, piece, _)| piece.start().rho.abs() <= tolerance || piece.end().rho.abs() <= tolerance);
    let (first_index, first_piece) = match start_index {
        Some(index) => {
            let piece = pieces[index].1;
            (index, if piece.start().rho.abs() <= tolerance { piece } else { piece.reversed() })
        }
        None => (0, pieces[0].1),
    };
    used[first_index] = true;
    let mut chain = vec![first_piece];
    loop {
        let tail = chain[chain.len() - 1].end();
        if start_index.is_some() && tail.rho.abs() <= tolerance {
            break;
        }
        let next = pieces.iter().enumerate().find_map(|(index, (_, piece, _))| {
            if used[index] {
                return None;
            }
            if close(piece.start(), tail) {
                Some((index, *piece))
            } else if close(piece.end(), tail) {
                Some((index, piece.reversed()))
            } else {
                None
            }
        });
        match next {
            Some((index, piece)) => {
                used[index] = true;
                chain.push(piece);
            }
            None => break,
        }
    }
    if used.iter().any(|u| !u) {
        return Ok(None);
    }
    if start_index.is_none() && !close(chain[chain.len() - 1].end(), chain[0].start()) {
        return Ok(None);
    }
    Ok(Some(chain))
}

/// `piece` with its start moved to `start` (a point already on it).
fn with_start(piece: &Piece, start: P2) -> Piece {
    match *piece {
        Piece::Line { end, .. } => Piece::Line { start, end },
        Piece::Arc { center, radius, end, ccw, .. } => Piece::Arc { center, radius, start, end, ccw },
    }
}

/// `piece` with its end moved to `end` (a point already on it).
fn with_end(piece: &Piece, end: P2) -> Piece {
    match *piece {
        Piece::Line { start, .. } => Piece::Line { start, end },
        Piece::Arc { center, radius, start, ccw, .. } => Piece::Arc { center, radius, start, end, ccw },
    }
}

/// `piece` split where it crosses the axis ρ = 0, in order along it.
fn split_at_axis(piece: &Piece, tolerance: f64) -> Vec<Piece> {
    match *piece {
        Piece::Line { start, end } => {
            if (start.rho < -tolerance && end.rho > tolerance) || (start.rho > tolerance && end.rho < -tolerance) {
                let t = start.rho / (start.rho - end.rho);
                let cut = start.add(end.sub(start).scale(t));
                vec![Piece::Line { start, end: cut }, Piece::Line { start: cut, end }]
            } else {
                vec![*piece]
            }
        }
        Piece::Arc { center, radius, start, end, ccw } => {
            let cosine = -center.rho / radius;
            if !(cosine.abs() < 1.0) {
                return vec![*piece];
            }
            let a0 = (start.z - center.z).atan2(start.rho - center.rho);
            let sweep = Piece::sweep(center, start, end, ccw);
            let mut fractions: Vec<f64> = Vec::new();
            for crossing in [cosine.acos(), -cosine.acos()] {
                let mut delta = crossing - a0;
                if ccw {
                    delta = delta.rem_euclid(std::f64::consts::TAU);
                } else {
                    delta = -(-delta).rem_euclid(std::f64::consts::TAU);
                }
                let fraction = delta / sweep;
                if fraction > 1e-12 && fraction < 1.0 - 1e-12 {
                    fractions.push(fraction);
                }
            }
            fractions.sort_by(f64::total_cmp);
            let at = |fraction: f64| {
                let a = a0 + sweep * fraction;
                P2 { rho: center.rho + radius * a.cos(), z: center.z + radius * a.sin() }
            };
            let mut pieces = Vec::new();
            let mut from = start;
            for fraction in fractions {
                let cut = at(fraction);
                pieces.push(Piece::Arc { center, radius, start: from, end: cut, ccw });
                from = cut;
            }
            pieces.push(Piece::Arc { center, radius, start: from, end, ccw });
            pieces
        }
    }
}