Skip to main content

brep_construction/construction/
solid_sweep_caps.rs

1//! The WHOLE sweep of a solid along a one-parameter motion, ends included:
2//! caps and wall.
3//!
4//! Along a screw (a turn is a screw of zero advance, a slide one of zero turn)
5//! the velocity field, read in the tool's own frame, does not change with time:
6//! at a boundary point x with outward normal n it is
7//! `g(x, n) = (ω e × (x − a) + c e) · n`. So the tool's boundary splits once
8//! and for all into FRONT (g > 0) and BACK (g < 0) parts, and the GRAZING LOOP
9//! K between them (g = 0 inside a face, or a sharp edge whose two faces have
10//! opposite signs) is fixed on the tool. Where every point of space is inside
11//! the moving tool for ONE interval of time, the sweep over [t0, t1] is bounded
12//! by exactly
13//!
14//! - the back of the tool at t0 (where points start to be covered),
15//! - the front of the tool at t1 (where they stop),
16//! - the WALL: K carried by the motion from t0 to t1.
17//!
18//! The body is assembled directly from those faces with shared edges, never as
19//! a boolean of the tool with a tube (the two meet tangentially along K).
20//!
21//! The one-interval condition is CHECKED, not assumed: points just outside
22//! every built face are walked through the whole motion, and a sweep that
23//! covers any of them (a fold, a buried cap, a turn running into itself) is
24//! refused by name.
25//!
26//! Tools: a convex polyhedron (K a polygon of edges and face chords); a solid
27//! of revolution whose faces are cylinders or cones (split along standing
28//! generators, or along two grazing curves moving round them, fitted), flat
29//! ends wholly front or back, a hemisphere from a pole to an equator or a whole
30//! ball (split along a great circle), or a ring (torus, split along its two
31//! grazing curves round it). Caps keep the tool's exact surfaces; walls are
32//! the K curves carried by quintic splines through the exact motion and its
33//! first two derivatives (error h⁶, 48 spans a turn), a row per quarter turn.
34//!
35//! Moving grazing loops: [`sweep_solid_along`] (a solid of revolution carried
36//! by a frame along a planar curve) and [`sweep_solid_tumbled`] (two turns
37//! about skew axes) split the tool at sample times, sample each piece of K
38//! exactly and loft the walls through time; a tumble that passes over a point
39//! twice is built from one-pass spans of its time, joined.
40//! [`sweep_prism_along`] sweeps a prism along a frame by the plane region the
41//! moving outline covers (an arrangement of its corners', grazing points' and
42//! end positions' paths), extruded. [`sweep_solid_parts`] returns a folding
43//! polyhedron's sweep as the sweeps of its halves through the motion's axis.
44//!
45//! [`sweep_solid_clipped`] adds the case the caller only needs inside a
46//! region: a polyhedron TURNED about the region's axis with both end positions
47//! outside the region's wedge fills the wedge with its (ρ, z) shadow turned,
48//! bounded by exact conic arcs (edges) and segments (face chords).
49use crate::solid_sweep::outline_signed_distance;
50use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
51pub use crate::{make_line, make_revolution, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, OrRefuse, OutlinePiece, SolidMotion, Vec3, Vec4};
52use std::collections::HashMap;
53use std::f64::consts::{FRAC_PI_2, PI, TAU};
54
55/// A tool the whole sweep takes.
56#[derive(Clone, Debug)]
57pub enum SolidTool {
58    /// A convex polyhedron: its corners, and its faces as loops of corner
59    /// indices (either winding; outward is found from the centroid).
60    Polyhedron { vertices: Vec<Vec3>, faces: Vec<Vec<usize>> },
61    /// A solid of revolution: the region `meridian` bounds in the
62    /// half-plane spanned by `radial` (first coordinate, the distance from the
63    /// axis, ≥ 0) and `axis_direction` (second coordinate), turned about the
64    /// axis through `axis_origin` (as [`crate::SweptTool::Revolved`]).
65    Revolved { axis_origin: Vec3, axis_direction: Vec3, radial: Vec3, meridian: Vec<OutlinePiece> },
66}
67
68/// Samples of a fitted pcurve: the image of its edge through the surface's
69/// exact inverse, interpolated (quintic). A rational chart's parameter has a
70/// second-derivative jump at its span joints, so the interpolant errs there
71/// as h³; at 576 that is below 1e-10 of a face's area.
72const PCURVE_SAMPLES: usize = 576;
73
74/// The prefix of every refusal of this operation.
75pub const SOLID_SWEEP_WHOLE_REFUSAL: &str = "sweepSolid";
76
77fn refuse(what: &'static str, message: String) -> KernelRefusal {
78    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
79}
80
81/// The stable slug of an unsupported-geometry refusal of this module.
82fn refused_as(error: &KernelRefusal) -> Option<&str> {
83    match &error.class {
84        crate::RefusalClass::UnsupportedGeometry { what } => Some(what.as_str()),
85        _ => None,
86    }
87}
88
89fn input(what: &'static str, message: String) -> KernelRefusal {
90    KernelRefusal::input(KernelStage::Collect, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
91}
92
93fn frag<T>(result: Result<T, String>, what: &'static str) -> Result<T, KernelRefusal> {
94    result.or_refuse(KernelStage::Fragment, what)
95}
96
97/// The motion `x ↦ a + R(ω t)(x − a) + (c t + c₂ t²) e`: a screw (c₂ = 0;
98/// a turn has c = 0, a slide ω = 0), or a turn whose rise grows as it turns.
99#[derive(Clone, Copy, Debug)]
100pub struct Screw {
101    pub a: Vec3,
102    pub e: Vec3,
103    pub omega: f64,
104    pub c: f64,
105    pub c2: f64,
106    pub t0: f64,
107    pub t1: f64,
108    /// A frame riding a curve instead (then `a` is the curve's start, `e` the
109    /// frame's fixed up direction, `omega` a bound on its turning rate and `c`
110    /// on its speed).
111    pub frame: Option<Frame>,
112    /// Two turns about fixed axes instead (then `a` is the first axis' point).
113    pub turns: Option<Turns>,
114    /// The time whose velocity field splits the tool (default: the middle).
115    pub frozen: Option<f64>,
116    /// How many spans a ring's grazing loop is sampled over, per half of the
117    /// ring (`LOFT_SAMPLES` unless a loft found its rows too coarse).
118    pub loop_samples: usize,
119    /// How far the frame's origin travels from `a` (for speed bounds).
120    pub extent: f64,
121}
122
123/// Two turns driven by one parameter: first `rates[0]·t` about the first
124/// axis, then `rates[1]·t` about the second; both axes fixed in the world.
125#[derive(Clone, Copy, Debug)]
126pub struct Turns {
127    points: [Vec3; 2],
128    directions: [Vec3; 2],
129    rates: [f64; 2],
130}
131
132impl Turns {
133    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
134        let y = self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t));
135        self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t))
136    }
137    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
138        let x = self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], -self.rates[1] * t));
139        self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], -self.rates[0] * t))
140    }
141    /// Velocity of the tool point x at t, read back in the tool's frame.
142    fn velocity(&self, t: f64, x: Vec3) -> Vec3 {
143        let first = x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t);
144        let y = self.points[0].add(first);
145        let moved = y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t);
146        let inner = self.directions[0].cross(first).scale(self.rates[0]);
147        let world = self.directions[1].cross(moved).scale(self.rates[1]).add(inner.rotate_about(self.directions[1], self.rates[1] * t));
148        world.rotate_about(self.directions[1], -self.rates[1] * t).rotate_about(self.directions[0], -self.rates[0] * t)
149    }
150}
151
152/// A frame riding a planar cubic Bézier curve: origin on the curve, first
153/// axis along its tangent, a fixed up direction square to its plane.
154#[derive(Clone, Copy, Debug)]
155pub struct Frame {
156    pub control: [Vec3; 4],
157    pub up: Vec3,
158    /// The tangent's direction at the start.
159    pub start_tangent: Vec3,
160}
161
162impl Frame {
163    fn point(&self, s: f64) -> Vec3 {
164        let [p0, p1, p2, p3] = self.control;
165        let r = 1.0 - s;
166        p0.scale(r * r * r).add(p1.scale(3.0 * r * r * s)).add(p2.scale(3.0 * r * s * s)).add(p3.scale(s * s * s))
167    }
168    fn first(&self, s: f64) -> Vec3 {
169        let [p0, p1, p2, p3] = self.control;
170        let r = 1.0 - s;
171        p1.sub(p0).scale(3.0 * r * r).add(p2.sub(p1).scale(6.0 * r * s)).add(p3.sub(p2).scale(3.0 * s * s))
172    }
173    fn second(&self, s: f64) -> Vec3 {
174        let [p0, p1, p2, p3] = self.control;
175        p2.sub(p1.scale(2.0)).add(p0).scale(6.0 * (1.0 - s)).add(p3.sub(p2.scale(2.0)).add(p1).scale(6.0 * s))
176    }
177    /// The frame's turn from its start, about `up`.
178    fn angle(&self, s: f64) -> f64 {
179        let t = self.first(s);
180        self.up.dot(self.start_tangent.cross(t)).atan2(self.start_tangent.dot(t))
181    }
182    fn angle_rate(&self, s: f64) -> f64 {
183        let (d1, d2) = (self.first(s), self.second(s));
184        self.up.dot(d1.cross(d2)) / d1.dot(d1)
185    }
186}
187
188/// A turn about an axis whose rise along it grows as it turns: turned by t
189/// (radians, right-handed about `axis_direction`) the tool has risen
190/// `rise[0] t + rise[1] t²`, for t from `from` to `to` (a variable-lead
191/// screw).
192#[derive(Clone, Copy, Debug)]
193pub struct RisingTurn {
194    pub axis_origin: Vec3,
195    pub axis_direction: Vec3,
196    pub rise: [f64; 2],
197    pub from: f64,
198    pub to: f64,
199}
200
201impl Screw {
202    pub fn from_motion(motion: &SolidMotion) -> Result<Self, KernelRefusal> {
203        let [step] = motion.steps.as_slice() else {
204            return Err(refuse("motion_steps", "only a single screw, turn or slide is swept whole here".into()));
205        };
206        let e = step
207            .axis_direction
208            .normalized()
209            .map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
210        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
211            return Err(input("range", "the motion's range must run forward".into()));
212        }
213        if step.turn == 0.0 && step.advance == 0.0 {
214            return Err(input("still", "the motion does not move".into()));
215        }
216        Ok(Self { a: step.axis_origin, e, omega: step.turn, c: step.advance, c2: 0.0, t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
217        loop_samples: LOFT_SAMPLES, extent: 0.0 })
218    }
219
220    fn from_rising(motion: &RisingTurn) -> Result<Self, KernelRefusal> {
221        let e = motion.axis_direction.normalized().map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
222        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
223            return Err(input("range", "the motion's range must run forward".into()));
224        }
225        // The rise's rate must keep one sign, or the tool's front and back swap.
226        let rate = |t: f64| motion.rise[0] + 2.0 * motion.rise[1] * t;
227        if rate(motion.from) * rate(motion.to) <= 0.0 {
228            return Err(refuse("rise_turns", "the rise stops or turns back within the motion".into()));
229        }
230        Ok(Self { a: motion.axis_origin, e, omega: 1.0, c: motion.rise[0], c2: motion.rise[1], t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
231        loop_samples: LOFT_SAMPLES, extent: 0.0 })
232    }
233
234    fn advance(&self, t: f64) -> f64 {
235        self.c * t + self.c2 * t * t
236    }
237
238    /// The fastest the motion advances along its axis.
239    fn rate_bound(&self) -> f64 {
240        (self.c + 2.0 * self.c2 * self.t0).abs().max((self.c + 2.0 * self.c2 * self.t1).abs())
241    }
242
243    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
244        if let Some(turns) = &self.turns {
245            return turns.apply(t, x);
246        }
247        if let Some(frame) = &self.frame {
248            return frame.point(t).add(x.sub(self.a).rotate_about(frame.up, frame.angle(t)));
249        }
250        self.a.add(x.sub(self.a).rotate_about(self.e, self.omega * t)).add(self.e.scale(self.advance(t)))
251    }
252
253    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
254        if let Some(turns) = &self.turns {
255            return turns.invert(t, y);
256        }
257        if let Some(frame) = &self.frame {
258            return self.a.add(y.sub(frame.point(t)).rotate_about(frame.up, -frame.angle(t)));
259        }
260        self.a.add(y.sub(self.e.scale(self.advance(t))).sub(self.a).rotate_about(self.e, -self.omega * t))
261    }
262
263    /// Velocity, in the tool's frame, of the tool point x (the same at every t
264    /// for a screw; for a growing rise, at the middle of the motion; the split
265    /// it gives is checked against both ends).
266    pub fn velocity(&self, x: Vec3) -> Vec3 {
267        self.velocity_at(self.frozen.unwrap_or(0.5 * (self.t0 + self.t1)), x)
268    }
269
270    fn velocity_at(&self, t: f64, x: Vec3) -> Vec3 {
271        if let Some(turns) = &self.turns {
272            return turns.velocity(t, x);
273        }
274        if let Some(frame) = &self.frame {
275            // In the riding frame: the speed along the start tangent and the
276            // turn about up through the frame's origin.
277            return frame.start_tangent.scale(frame.first(t).length()).add(frame.up.cross(x.sub(self.a)).scale(frame.angle_rate(t)));
278        }
279        self.e.cross(x.sub(self.a)).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t))
280    }
281
282    /// Value, first and second t-derivative of the path of the tool point x.
283    fn jet(&self, t: f64, x: Vec3) -> (Vec3, Vec3, Vec3) {
284        let r = x.sub(self.a).rotate_about(self.e, self.omega * t);
285        let axial = self.e.scale(r.dot(self.e));
286        let radial = r.sub(axial);
287        let value = self.a.add(r).add(self.e.scale(self.advance(t)));
288        let first = self.e.cross(radial).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t));
289        let second = radial.scale(-self.omega * self.omega).add(self.e.scale(2.0 * self.c2));
290        (value, first, second)
291    }
292
293    fn move_point(&self, t: f64, p: &Vec4) -> Result<Vec4, KernelRefusal> {
294        let x = frag(p.point(), "control_point")?;
295        Ok(Vec4::from_point(self.apply(t, x), p.w))
296    }
297
298    fn move_curve(&self, t: f64, curve: &NurbsCurve) -> Result<NurbsCurve, KernelRefusal> {
299        let points = curve.control_points.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?;
300        frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "moved_curve")
301    }
302
303    fn move_surface(&self, t: f64, surface: &NurbsSurface) -> Result<NurbsSurface, KernelRefusal> {
304        let mut rows = Vec::with_capacity(surface.control_points.len());
305        for row in &surface.control_points {
306            rows.push(row.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?);
307        }
308        frag(
309            NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), rows),
310            "moved_surface",
311        )
312    }
313}
314
315/// The motion's times at the ends of its rows: each row of wall turns at most
316/// a quarter turn (long thin faces cost every later reading, and the cut).
317fn row_times(screw: &Screw) -> Vec<f64> {
318    let turned = (screw.omega * (screw.t1 - screw.t0)).abs();
319    let rows = ((turned / (0.5 * PI)).ceil() as usize).max(1);
320    // Breaks off the round fractions of the range, where a caller's workpiece
321    // faces tend to lie (a precaution: an edge lying in a face makes a
322    // degenerate cut).
323    let at = |k: usize| match k {
324        0 => screw.t0,
325        k if k == rows => screw.t1,
326        k => screw.t0 + (screw.t1 - screw.t0) * (k as f64 - 0.381966011250105) / rows as f64,
327    };
328    (0..=rows).map(at).collect()
329}
330
331/// Spans of the quintic carry over [ta, tb]: 48 per turn (error ≈ r·h⁶/46080
332/// ≈ 1e-10·r), at least 4.
333fn carry_segments(screw: &Screw, ta: f64, tb: f64) -> usize {
334    let turned = (screw.omega * (tb - ta)).abs();
335    ((turned / TAU * 48.0).ceil() as usize).max(4)
336}
337
338/// Knots of the C² quintic carry on [0, 1].
339fn carry_knots(segments: usize) -> Vec<f64> {
340    let mut knots = vec![0.0; 6];
341    for k in 1..segments {
342        knots.extend([k as f64 / segments as f64; 3]);
343    }
344    knots.extend([1.0; 6]);
345    knots
346}
347
348/// Control points of the C² quintic spline through the exact path of the tool
349/// point x, its first and second derivatives at `segments + 1` times. Affine
350/// in x, so carrying a rational curve's control points carries the curve.
351fn carry_points(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Vec<Vec3> {
352    let h = (tb - ta) / segments as f64;
353    let at = |k: usize| screw.jet(ta + h * k as f64, x);
354    let piece = |k: usize| {
355        let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
356        [
357            f0,
358            f0.add(d0.scale(h / 5.0)),
359            f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
360            f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
361            f1.sub(d1.scale(h / 5.0)),
362            f1,
363        ]
364    };
365    let mut points = Vec::with_capacity(3 * segments + 3);
366    let first = piece(0);
367    points.extend_from_slice(&first[..3]);
368    for k in 0..segments - 1 {
369        let (here, next) = (piece(k), piece(k + 1));
370        points.push(here[3]);
371        points.push(here[4].scale(2.0).sub(here[3]));
372        points.push(next[2]);
373    }
374    let last = piece(segments - 1);
375    points.extend_from_slice(&last[3..]);
376    points
377}
378
379fn carry_curve(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Result<NurbsCurve, KernelRefusal> {
380    frag(
381        NurbsCurve::new(5, carry_knots(segments), carry_points(screw, x, ta, tb, segments).into_iter().map(|p| Vec4::from_point(p, 1.0)).collect()),
382        "carry_curve",
383    )
384}
385
386/// A boundary curve of the tool (in its own frame), from point `start` to
387/// point `end` along its parameter.
388struct ToolCurve {
389    curve: NurbsCurve,
390    start: usize,
391    end: usize,
392    degenerate: bool,
393    /// Exact points at `LOFT_SAMPLES + 1` even steps of a natural parameter
394    /// from start to end (meridian place, angle), where a grazing curve
395    /// moves on the tool and its wall is lofted through time.
396    samples: Option<Vec<Vec3>>,
397}
398
399/// Steps of a grazing curve's exact samples for a lofted wall.
400pub const LOFT_SAMPLES: usize = 128;
401
402/// How near a lofted wall keeps to its exact grazing loop, as a fraction of
403/// the sweep's size: every exact sample of the loop, in the middle of every
404/// time span, is within this of the wall.
405///
406/// It was 5e-10. A wall that tight is heavy (a quintic's miss falls as the
407/// sixth power of its span, so each tenfold costs half again as many spans
408/// each way), and whoever reads the solid pays for every span. The measures
409/// do not need it: an interpolant's miss changes sign from span to span and
410/// all but cancels in a volume or an area. Over this hundredfold the lofted
411/// cases' volumes and areas moved by 2e-10 or less.
412const LOFT_TARGET: f64 = 5e-8;
413
414/// A face of the tool after the split along K: its exact surface (normal
415/// outward), its side, and its loop (curve, traversed forward?, pcurve in the
416/// direction of traversal).
417struct Cap {
418    surface: NurbsSurface,
419    front: bool,
420    coedges: Vec<(usize, bool, NurbsCurve)>,
421    /// The surface's exact parameters of a point (in the tool's frame), where
422    /// known: a lofted edge's pcurve is then its exact image.
423    chart: Option<Chart>,
424}
425
426/// How a cap's surface is parameterized, to invert it exactly.
427#[derive(Clone, Copy, Debug)]
428enum Chart {
429    /// `plane_patch(origin, u, v, …)`: (x − origin)·u, (x − origin)·v.
430    Plane { origin: Vec3, u: Vec3, v: Vec3 },
431    /// `make_revolution(origin, w, generatrix, theta)` with the generatrix in the
432    /// meridian half-plane at angle `alpha` (from u1 towards u2).
433    Revolution { origin: Vec3, w: Vec3, u1: Vec3, u2: Vec3, alpha: f64, theta: f64, spans_u: usize, meridian: MeridianChart },
434}
435
436#[derive(Clone, Copy, Debug)]
437enum MeridianChart {
438    /// A segment from m0 to m1 in (ρ, z), parameter 0 -> 1.
439    Line { m0: [f64; 2], m1: [f64; 2] },
440    /// An arc about `centre` in (ρ, z) from angle `start` through `sweep`, as
441    /// `make_revolution` of a point makes it (`spans` arcs).
442    Arc { centre: [f64; 2], start: f64, sweep: f64, spans: usize },
443}
444
445impl Chart {
446    /// Is `x` on the chart's own axis, where its first parameter (the angle
447    /// about the axis) is not defined? A ball's pole.
448    fn at_pole(&self, x: Vec3) -> bool {
449        match *self {
450            Chart::Plane { .. } => false,
451            Chart::Revolution { origin, w, .. } => {
452                let r = x.sub(origin);
453                r.sub(w.scale(r.dot(w))).length() <= 1e-6 * r.length()
454            }
455        }
456    }
457
458    /// The chart's span joints in each parameter (`make_revolution`'s arcs
459    /// in equal spans of [0, 1]), where its parameter's second derivative
460    /// jumps along the surface.
461    fn joints(&self) -> (Vec<f64>, Vec<f64>) {
462        let inner = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
463        match *self {
464            Chart::Plane { .. } => (Vec::new(), Vec::new()),
465            Chart::Revolution { spans_u, meridian, .. } => (
466                inner(spans_u),
467                match meridian {
468                    MeridianChart::Arc { spans, .. } => inner(spans),
469                    MeridianChart::Line { .. } => Vec::new(),
470                },
471            ),
472        }
473    }
474
475    fn invert(&self, x: Vec3) -> [f64; 2] {
476        match *self {
477            Chart::Plane { origin, u, v } => {
478                let d = x.sub(origin);
479                [d.dot(u), d.dot(v)]
480            }
481            Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u, meridian } => {
482                let r = x.sub(origin);
483                let z = r.dot(w);
484                let rho = r.sub(w.scale(z)).length();
485                let mid = alpha + 0.5 * theta;
486                let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
487                let u = crate::circle_angle_to_parameter(spans_u, theta, psi - alpha);
488                let v = match meridian {
489                    MeridianChart::Line { m0, m1 } => {
490                        let (a, b) = (m1[0] - m0[0], m1[1] - m0[1]);
491                        ((rho - m0[0]) * a + (z - m0[1]) * b) / (a * a + b * b)
492                    }
493                    MeridianChart::Arc { centre, start, sweep, spans } => {
494                        let mid = start + 0.5 * sweep;
495                        let angle = mid + ((z - centre[1]).atan2(rho - centre[0]) - mid + PI).rem_euclid(TAU) - PI;
496                        crate::circle_angle_to_parameter(spans, sweep, angle - start)
497                    }
498                };
499                [u, v]
500            }
501        }
502    }
503}
504
505/// The spans `make_revolution` gives a sweep of `theta`.
506fn spans_of(surface_knots_u: &[f64]) -> usize {
507    (surface_knots_u.len() - 6) / 2 + 1
508}
509
510/// The tool's boundary split along K, in the tool's own frame.
511struct Split {
512    points: Vec<Vec3>,
513    curves: Vec<ToolCurve>,
514    caps: Vec<Cap>,
515    /// Flat ends that slide within their own plane all through the motion.
516    slides: Vec<SlideDisc>,
517    /// Cylinders that slide along their own generators all through it.
518    slide_sides: Vec<SlideSide>,
519    scale: f64,
520    shape: Shape,
521}
522
523/// A flat end about the tool's axis whose every point moves within the
524/// end's own plane (a turn about a parallel axis, a slide across the tool's
525/// axis): neither front nor back. What it sweeps is one face of the sweep in
526/// that plane, bounded by the rim's arcs beside back faces where the motion
527/// starts, its arcs beside front faces where it stops, and the paths of the
528/// points between them. `rim`: the rim's arcs counter-clockwise about the
529/// outward normal `u × v`, each with its direction of traversal.
530struct SlideDisc {
531    centre: Vec3,
532    u: Vec3,
533    v: Vec3,
534    rim: Vec<(usize, bool)>,
535}
536
537/// A cylinder about the tool's axis slid along that axis: every point moves
538/// along its own generator. What it sweeps is the cylinder from one rim where
539/// that rim's neighbour sits (back at the start, front at the end) to the
540/// other rim where its neighbour sits. `patches`: per stretch between two
541/// seam angles, (the angle it starts at, its sweep, the start rim's arc, the
542/// end rim's arc, the rim points at the start angle: start rim, end rim).
543struct SlideSide {
544    origin: Vec3,
545    w: Vec3,
546    patches: Vec<(f64, f64, usize, usize, [usize; 2])>,
547}
548
549/// What the membership oracle measures.
550enum Shape {
551    Planes(Vec<(Vec3, f64)>),
552    Revolved { origin: Vec3, axis: Vec3, meridian: Vec<OutlinePiece> },
553}
554
555impl Split {
556    /// Signed distance to the tool in its own frame (negative inside).
557    fn distance(&self, x: Vec3) -> f64 {
558        match &self.shape {
559            Shape::Planes(planes) => planes.iter().map(|(n, d)| n.dot(x) - d).fold(f64::NEG_INFINITY, f64::max),
560            Shape::Revolved { origin, axis, meridian } => {
561                let r = x.sub(*origin);
562                let z = r.dot(*axis);
563                let rho = r.sub(axis.scale(z)).length();
564                outline_signed_distance(meridian, [rho, z])
565            }
566        }
567    }
568
569    /// K: each curve with a front cap on one side and a back cap on the
570    /// other, with the direction in which the back cap runs along it (the back
571    /// on its left seen from outside).
572    fn grazing(&self) -> Result<Vec<(usize, bool)>, KernelRefusal> {
573        let mut uses: HashMap<usize, Vec<(bool, bool)>> = HashMap::new();
574        for cap in &self.caps {
575            for &(curve, forward, _) in &cap.coedges {
576                uses.entry(curve).or_default().push((forward, cap.front));
577            }
578        }
579        let mut grazing = Vec::new();
580        for (curve, list) in uses {
581            if self.curves[curve].degenerate {
582                continue;
583            }
584            // A sliding end's rim carries no wall: it moves within the end's plane.
585            if list.len() == 1
586                && (self.slides.iter().any(|slide| slide.rim.iter().any(|&(c, _)| c == curve))
587                    || self.slide_sides.iter().any(|side| side.patches.iter().any(|patch| patch.2 == curve || patch.3 == curve)))
588            {
589                continue;
590            }
591            match list.as_slice() {
592                [(fa, front_a), (fb, front_b)] => {
593                    if fa == fb {
594                        return Err(refuse("split_topology", "two caps run one boundary curve the same way".into()));
595                    }
596                    if front_a != front_b {
597                        grazing.push((curve, if *front_a { *fb } else { *fa }));
598                    }
599                }
600                _ => return Err(refuse("split_topology", format!("a boundary curve is used {} times", list.len()))),
601            }
602        }
603        grazing.sort_unstable();
604        Ok(grazing)
605    }
606}
607
608fn uv_line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
609    frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "pcurve")
610}
611
612/// The plane through `origin` with in-plane axes u, v (u × v outward), as a
613/// patch covering `points`; and the map to its parameters.
614fn plane_patch(origin: Vec3, u: Vec3, v: Vec3, points: &[Vec3]) -> Result<NurbsSurface, KernelRefusal> {
615    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
616    for p in points {
617        let q = [p.sub(origin).dot(u), p.sub(origin).dot(v)];
618        for k in 0..2 {
619            lo[k] = lo[k].min(q[k]);
620            hi[k] = hi[k].max(q[k]);
621        }
622    }
623    let at = |s: f64, t: f64| Vec4::from_point(origin.add(u.scale(s)).add(v.scale(t)), 1.0);
624    frag(
625        NurbsSurface::new(
626            1,
627            1,
628            vec![lo[0], lo[0], hi[0], hi[0]],
629            vec![lo[1], lo[1], hi[1], hi[1]],
630            vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]],
631        ),
632        "plane_surface",
633    )
634}
635
636/// A curve lying in the plane (origin, u, v), as a pcurve of that plane:
637/// its control points projected, weights kept (exact, the map is affine).
638fn plane_pcurve(origin: Vec3, u: Vec3, v: Vec3, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
639    let mut points = Vec::with_capacity(curve.control_points.len());
640    for p in &curve.control_points {
641        let x = frag(p.point(), "control_point")?.sub(origin);
642        points.push(Vec4::from_point(Vec3::new(x.dot(u), x.dot(v), 0.0), p.w));
643    }
644    let pcurve = frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "plane_pcurve")?;
645    if forward { Ok(pcurve) } else { frag(pcurve.reversed(), "plane_pcurve") }
646}
647
648fn split_polyhedron(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<Split, KernelRefusal> {
649    if vertices.len() < 4 || faces.len() < 4 {
650        return Err(input("polyhedron", "a polyhedron needs at least four corners and four faces".into()));
651    }
652    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &p| s.add(p)).scale(1.0 / vertices.len() as f64);
653    let scale = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max).max(1e-300);
654    let tolerance = 1e-12 * scale.max(screw.a.sub(centroid).length());
655    let mut loops: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
656    let mut planes = Vec::with_capacity(faces.len());
657    for face in faces {
658        if face.len() < 3 || face.iter().any(|&i| i >= vertices.len()) {
659            return Err(input("face", "a face needs three or more existing corners".into()));
660        }
661        let mut normal = Vec3::new(0.0, 0.0, 0.0);
662        for k in 0..face.len() {
663            let (p, q) = (vertices[face[k]], vertices[face[(k + 1) % face.len()]]);
664            normal = normal.add(p.sub(centroid).cross(q.sub(centroid)));
665        }
666        let mut normal = normal.normalized().map_err(|_| input("face", "a face has no area".into()))?;
667        let mut face = face.clone();
668        if normal.dot(vertices[face[0]].sub(centroid)) < 0.0 {
669            normal = normal.scale(-1.0);
670            face.reverse();
671        }
672        let offset = normal.dot(vertices[face[0]]);
673        for p in vertices {
674            if normal.dot(*p) - offset > 1e-9 * scale {
675                return Err(refuse("not_convex", "the polyhedron is not convex".into()));
676            }
677        }
678        for &i in &face {
679            if (normal.dot(vertices[i]) - offset).abs() > 1e-9 * scale {
680                return Err(input("face", "a face's corners are not in one plane".into()));
681            }
682        }
683        loops.push(face);
684        planes.push((normal, offset));
685    }
686    // Each face's grazing value (affine along the face).
687    let g = |face: usize, x: Vec3| -> f64 {
688        let value = screw.velocity(x).dot(planes[face].0);
689        if value.abs() <= tolerance * screw.velocity(x).length().max(1.0) { 0.0 } else { value }
690    };
691    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
692    for (index, face) in loops.iter().enumerate() {
693        for k in 0..face.len() {
694            owner.insert((face[k], face[(k + 1) % face.len()]), index);
695        }
696    }
697    for &(i, j) in owner.keys() {
698        if !owner.contains_key(&(j, i)) {
699            return Err(input("closed", "the polyhedron's faces do not close".into()));
700        }
701    }
702    // Split points on edges: where either neighbour's grazing value crosses zero.
703    let mut points: Vec<Vec3> = vertices.to_vec();
704    let mut edge_splits: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
705    let mut keys: Vec<(usize, usize)> = owner.keys().copied().filter(|&(i, j)| i < j).collect();
706    keys.sort_unstable();
707    for (i, j) in keys {
708        let mut params: Vec<f64> = Vec::new();
709        for f in [owner[&(i, j)], owner[&(j, i)]] {
710            let (gi, gj) = (g(f, vertices[i]), g(f, vertices[j]));
711            if gi * gj < 0.0 {
712                params.push(gi / (gi - gj));
713            }
714        }
715        params.sort_by(|a, b| a.total_cmp(b));
716        params.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
717        let mut list = Vec::new();
718        for s in params {
719            points.push(vertices[i].add(vertices[j].sub(vertices[i]).scale(s)));
720            list.push(points.len() - 1);
721        }
722        edge_splits.insert((i, j), list);
723    }
724    let splits_along = |i: usize, j: usize| -> Vec<usize> {
725        if i < j {
726            edge_splits[&(i, j)].clone()
727        } else {
728            edge_splits[&(j, i)].iter().rev().copied().collect()
729        }
730    };
731    // Sub-faces as point rings, counter-clockwise from outside.
732    let mut rings: Vec<(Vec<usize>, usize, bool)> = Vec::new();
733    for (index, face) in loops.iter().enumerate() {
734        let mut ring: Vec<usize> = Vec::new();
735        for k in 0..face.len() {
736            ring.push(face[k]);
737            ring.extend(splits_along(face[k], face[(k + 1) % face.len()]));
738        }
739        let values: Vec<f64> = ring.iter().map(|&p| g(index, points[p])).collect();
740        let positive = values.iter().any(|&v| v > 0.0);
741        let negative = values.iter().any(|&v| v < 0.0);
742        if !positive && !negative {
743            return Err(refuse("face_in_own_plane", format!("face {index} moves in its own plane (its sweep is flat)")));
744        }
745        if !(positive && negative) {
746            rings.push((ring, index, positive));
747            continue;
748        }
749        let zeros: Vec<usize> = (0..ring.len()).filter(|&k| values[k] == 0.0).collect();
750        if zeros.len() != 2 {
751            return Err(refuse("grazing_split", format!("face {index} meets its grazing line {} times", zeros.len())));
752        }
753        let (za, zb) = (zeros[0], zeros[1]);
754        if za + 1 == zb || (zb + 1) % ring.len() == za {
755            return Err(refuse("grazing_split", format!("face {index} is split along one of its own edges")));
756        }
757        let first: Vec<usize> = (za..=zb).map(|k| ring[k]).collect();
758        let second: Vec<usize> = (zb..ring.len()).chain(0..=za).map(|k| ring[k]).collect();
759        let first_front = values[za + 1] > 0.0;
760        rings.push((first, index, first_front));
761        rings.push((second, index, !first_front));
762    }
763    // A growing rise moves the grazing lines: every sub-face must keep its side
764    // at both ends of the motion.
765    if screw.c2 != 0.0 {
766        for (ring, face, front) in &rings {
767            for &p in ring {
768                for t in [screw.t0, screw.t1] {
769                    let value = screw.velocity_at(t, points[p]).dot(planes[*face].0);
770                    let slack = tolerance * screw.velocity_at(t, points[p]).length().max(1.0);
771                    if (*front && value < -slack) || (!*front && value > slack) {
772                        return Err(refuse("rising_sides", format!("face {face} changes side as the rise grows")));
773                    }
774                }
775            }
776        }
777    }
778    // Curves: one straight segment per point pair.
779    let mut curves: Vec<ToolCurve> = Vec::new();
780    let mut by_pair: HashMap<(usize, usize), usize> = HashMap::new();
781    let mut caps = Vec::with_capacity(rings.len());
782    for (ring, face, front) in rings {
783        let normal = planes[face].0;
784        let origin = points[ring[0]];
785        let u = frag(points[ring[1]].sub(origin).normalized(), "plane_axis")?;
786        let v = normal.cross(u);
787        let corners: Vec<Vec3> = ring.iter().map(|&p| points[p]).collect();
788        let surface = plane_patch(origin, u, v, &corners)?;
789        let mut coedges = Vec::with_capacity(ring.len());
790        for k in 0..ring.len() {
791            let (p, q) = (ring[k], ring[(k + 1) % ring.len()]);
792            let key = (p.min(q), p.max(q));
793            let index = match by_pair.get(&key) {
794                Some(&index) => index,
795                None => {
796                    curves.push(ToolCurve {
797                        curve: frag(make_line(points[key.0], points[key.1]), "line")?,
798                        start: key.0,
799                        end: key.1,
800                        degenerate: false,
801                        samples: None,
802                    });
803                    by_pair.insert(key, curves.len() - 1);
804                    curves.len() - 1
805                }
806            };
807            let forward = p == key.0;
808            coedges.push((index, forward, plane_pcurve(origin, u, v, &curves[index].curve, forward)?));
809        }
810        caps.push(Cap { surface, front, coedges, chart: Some(Chart::Plane { origin, u, v }) });
811    }
812    Ok(Split { points, curves, caps, slides: Vec::new(), slide_sides: Vec::new(), scale, shape: Shape::Planes(planes) })
813}
814
815/// The grazing value `A cos ψ + B sin ψ + C` of a face of revolution at one
816/// meridian point, from three samples.
817pub fn harmonic(g: impl Fn(f64) -> f64) -> (f64, f64, f64) {
818    let (g0, g90, g180) = (g(0.0), g(0.5 * PI), g(PI));
819    let c = 0.5 * (g0 + g180);
820    (0.5 * (g0 - g180), g90 - c, c)
821}
822
823pub fn piece_point(piece: &OutlinePiece, s: f64) -> [f64; 2] {
824    match *piece {
825        OutlinePiece::Line { from, to } => [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s],
826        OutlinePiece::Arc { centre, radius, start, end } => {
827            let angle = start + (end - start) * s;
828            [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
829        }
830        OutlinePiece::Ellipse { centre, semi, rotation, start, end } => crate::solid_sweep::ellipse_point(centre, semi, rotation, start + (end - start) * s),
831    }
832}
833
834/// The whole sweep takes meridians of lines and circular arcs; an elliptic
835/// piece is swept only by [`crate::sweep_solid_within`]'s region engine.
836fn refuse_elliptic(meridian: &[OutlinePiece]) -> Result<(), KernelRefusal> {
837    if meridian.iter().any(|piece| matches!(piece, OutlinePiece::Ellipse { .. })) {
838        return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into()));
839    }
840    Ok(())
841}
842
843fn split_revolved(
844    screw: &Screw,
845    origin: Vec3,
846    axis: Vec3,
847    radial: Vec3,
848    meridian: &[OutlinePiece],
849) -> Result<Split, KernelRefusal> {
850    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
851    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
852    let u2 = w.cross(u1);
853    refuse_elliptic(meridian)?;
854    if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian {
855        if ((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius {
856            return split_torus(screw, origin, w, u1, u2, *centre, *radius, meridian);
857        }
858    }
859    let at = |rho: f64, z: f64, psi: f64| origin.add(w.scale(z)).add(u1.scale(rho * psi.cos())).add(u2.scale(rho * psi.sin()));
860    let scale = meridian
861        .iter()
862        .flat_map(|p| [piece_point(p, 0.0), piece_point(p, 1.0)])
863        .map(|q| q[0].abs().max(q[1].abs()))
864        .fold(0.0f64, f64::max)
865        .max(1e-300);
866    let on_axis = |q: [f64; 2]| q[0].abs() <= 1e-12 * scale;
867    // Orientation of the meridian outline (+1 counter-clockwise in (ρ, z)).
868    let mut area = 0.0;
869    for piece in meridian {
870        for k in 0..16 {
871            let (p, q) = (piece_point(piece, k as f64 / 16.0), piece_point(piece, (k + 1) as f64 / 16.0));
872            area += p[0] * q[1] - q[0] * p[1];
873        }
874    }
875    // Work counter-clockwise in (ρ, z): a revolved patch's u × v is then outward.
876    let reversed_meridian: Vec<OutlinePiece>;
877    let meridian: &[OutlinePiece] = if area > 0.0 {
878        meridian
879    } else {
880        reversed_meridian = meridian
881            .iter()
882            .rev()
883            .map(|piece| match *piece {
884                OutlinePiece::Line { from, to } => OutlinePiece::Line { from: to, to: from },
885                OutlinePiece::Arc { centre, radius, start, end } => OutlinePiece::Arc { centre, radius, start: end, end: start },
886                OutlinePiece::Ellipse { centre, semi, rotation, start, end } => OutlinePiece::Ellipse { centre, semi, rotation, start: end, end: start },
887            })
888            .collect();
889        &reversed_meridian
890    };
891    let ccw = true;
892    // Outward normal in (ρ, z) of a piece at s.
893    let normal = |piece: &OutlinePiece, s: f64| -> [f64; 2] {
894        let (p, q) = (piece_point(piece, (s - 1e-6).max(0.0)), piece_point(piece, (s + 1e-6).min(1.0)));
895        let (dx, dz) = (q[0] - p[0], q[1] - p[1]);
896        let length = dx.hypot(dz);
897        if ccw { [dz / length, -dx / length] } else { [-dz / length, dx / length] }
898    };
899    let g = |piece: &OutlinePiece, s: f64, psi: f64| -> f64 {
900        let m = piece_point(piece, s);
901        let n = normal(piece, s);
902        let x = at(m[0], m[1], psi);
903        let normal = w.scale(n[1]).add(u1.scale(n[0] * psi.cos())).add(u2.scale(n[0] * psi.sin()));
904        screw.velocity(x).dot(normal)
905    };
906    // The faces: pieces off the axis.
907    let faces: Vec<usize> = (0..meridian.len())
908        .filter(|&i| !(matches!(meridian[i], OutlinePiece::Line { .. }) && on_axis(piece_point(&meridian[i], 0.0)) && on_axis(piece_point(&meridian[i], 1.0))))
909        .collect();
910    // Each face's split angles (where K meets it, constant along it), or its
911    // great circle.
912    enum Kind {
913        /// A cylinder or cone (or a flat end) split along generators at these
914        /// angles (empty: one side).
915        Ruled(Vec<f64>),
916        /// A cylinder or cone whose two grazing curves move round it along
917        /// the meridian (`branches`), from rim to rim.
918        Moving,
919        /// A hemisphere from a pole to an equator rim, split by the great
920        /// circle square to its centre's velocity.
921        Sphere { centre: Vec3, pole_at_start: bool },
922        /// A whole ball (a half circle from pole to pole), split by that
923        /// great circle into two hemispheres.
924        Ball { centre: Vec3, radius: f64 },
925        /// A rounded corner (a zone of a torus: an arc whose centre is off the
926        /// axis), crossed by K as a graph v(ψ) of the tube angle for ψ from
927        /// `psi_a` to `psi_b`, entering and leaving at the same rim (the end
928        /// rim when `at_end`).
929        TorusZone { psi_a: f64, psi_b: f64, at_end: bool },
930        /// A flat end that slides within its own plane (`SlideDisc`).
931        Slide,
932        /// A cylinder slid along its own axis (`SlideSide`).
933        SlideSide,
934        /// A rounded corner split along meridian arcs at these angles (the
935        /// grazing curve keeps its angle about the axis: a turn about a
936        /// parallel axis, a slide across the tool's axis).
937        RuledArc(Vec<f64>),
938    }
939    // The two grazing angles of a cylinder or cone at s, the lower and the
940    // upper, unwrapped against s = 0: the front lies between them.
941    let branches = |piece: &OutlinePiece, s: f64| -> Option<(f64, f64)> {
942        let reference = {
943            let (a, b, _) = harmonic(|psi| g(piece, 0.0, psi));
944            b.atan2(a)
945        };
946        let (a, b, c) = harmonic(|psi| g(piece, s, psi));
947        let r = a.hypot(b);
948        if !(c.abs() < r * (1.0 - 1e-9)) {
949            return None;
950        }
951        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
952        let spread = (-c / r).acos();
953        Some((base - spread, base + spread))
954    };
955    let mut kinds: Vec<Kind> = Vec::with_capacity(faces.len());
956    for &i in &faces {
957        let piece = &meridian[i];
958        match *piece {
959            OutlinePiece::Ellipse { .. } => return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into())),
960            OutlinePiece::Line { .. } => {
961                let roots = |s: f64| -> Vec<f64> {
962                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
963                    let r = a.hypot(b);
964                    if c.abs() >= r * (1.0 - 1e-12) {
965                        return Vec::new();
966                    }
967                    let base = b.atan2(a);
968                    let spread = (-c / r).acos();
969                    let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
970                    list.sort_by(|x, y| x.total_cmp(y));
971                    list
972                };
973                // Where the grazing value vanishes all round (a rim through
974                // the motion's axis turning in its own plane) it names no
975                // angle; read the roots where it does not.
976                let alive = |s: f64| {
977                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
978                    a.hypot(b).max(c.abs()) > 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound())
979                };
980                let readings: Vec<Vec<f64>> = [0.0, 0.5, 1.0].into_iter().filter(|&t| alive(t)).map(roots).collect();
981                if readings.is_empty() {
982                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
983                    let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
984                    if flat && (on_axis(m0) || on_axis(m1)) {
985                        kinds.push(Kind::Slide);
986                        continue;
987                    }
988                    let upright = (m0[0] - m1[0]).abs() <= 1e-12 * scale;
989                    if upright && screw.omega == 0.0 && screw.turns.is_none() && screw.frame.is_none() {
990                        kinds.push(Kind::SlideSide);
991                        continue;
992                    }
993                    return Err(refuse("revolved_grazing", format!("meridian piece {i} grazes all over")));
994                }
995                let r0 = readings[0].clone();
996                let still = readings.iter().all(|r| r.len() == r0.len() && r.iter().zip(&r0).all(|(x, y)| (x - y).abs() < 1e-10));
997                if still {
998                    // A face wholly on one side that is not a disc about the
999                    // axis (a cone to its point, an annulus, a whole side):
1000                    // two halves of the same side, seamed at 0 and π.
1001                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1002                    let disc = (m0[1] - m1[1]).abs() <= 1e-12 * scale && (on_axis(m0) || on_axis(m1));
1003                    kinds.push(Kind::Ruled(if r0.is_empty() && !disc { vec![0.0, PI] } else { r0 }));
1004                    continue;
1005                }
1006                let mut previous: Option<(f64, f64)> = None;
1007                for k in 0..=64 {
1008                    let Some(pair) = branches(piece, k as f64 / 64.0) else {
1009                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} do not run rim to rim")));
1010                    };
1011                    if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
1012                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} turn too fast")));
1013                    }
1014                    previous = Some(pair);
1015                }
1016                kinds.push(Kind::Moving);
1017            }
1018            OutlinePiece::Arc { centre, radius, start, end } => {
1019                let (p0, p1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1020                let span = (end - start).abs();
1021                let centre_on_axis = on_axis(centre);
1022                let pole_at_start = on_axis(p0);
1023                let equator = |p: [f64; 2]| (p[1] - centre[1]).abs() <= 1e-12 * scale && (p[0] - radius).abs() <= 1e-12 * scale;
1024                if centre_on_axis && (span - PI).abs() < 1e-12 && pole_at_start && on_axis(p1) {
1025                    kinds.push(Kind::Ball { centre: origin.add(w.scale(centre[1])), radius });
1026                    continue;
1027                }
1028                if centre[0] > radius * (1.0 + 1e-9) && end > start && span <= PI + 1e-12 {
1029                    let at_rim = |v: f64| [centre[0] + radius * v.cos(), centre[1] + radius * v.sin()];
1030                    let g_tube = |psi: f64, v: f64| -> f64 {
1031                        let m = at_rim(v);
1032                        let x = at(m[0], m[1], psi);
1033                        let normal = w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1034                        screw.velocity(x).dot(normal)
1035                    };
1036                    // K at the same angles about the axis all along the arc?
1037                    {
1038                        let roots_at = |v: f64| -> Option<Vec<f64>> {
1039                            let (a, b, c) = harmonic(|psi| g_tube(psi, v));
1040                            let r = a.hypot(b);
1041                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1042                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1043                                return None;
1044                            }
1045                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1046                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1047                            list.sort_by(|x, y| x.total_cmp(y));
1048                            Some(list)
1049                        };
1050                        let readings: Vec<Option<Vec<f64>>> = [0.25, 0.5, 0.75].into_iter().map(|t| roots_at(start + (end - start) * t)).collect();
1051                        if let [Some(r0), Some(r1), Some(r2)] = readings.as_slice() {
1052                            if r0.iter().zip(r1).chain(r0.iter().zip(r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1053                                kinds.push(Kind::RuledArc(r0.clone()));
1054                                continue;
1055                            }
1056                        }
1057                    }
1058                    if span >= PI {
1059                        return Err(refuse("revolved_arc", format!("meridian piece {i}: a half-round rim is swept only where its grazing curves keep their angle")));
1060                    }
1061                    let in_zone = |psi: f64| -> Result<Option<f64>, KernelRefusal> {
1062                        let (a, b, c) = harmonic(|v| g_tube(psi, v));
1063                        let r = a.hypot(b);
1064                        if !(c.abs() < r) {
1065                            return Ok(None);
1066                        }
1067                        let base = b.atan2(a);
1068                        let spread = (-c / r).acos();
1069                        let inside: Vec<f64> = [base - spread, base + spread]
1070                            .into_iter()
1071                            .map(|v| start + (v - start).rem_euclid(TAU))
1072                            .filter(|&v| v <= end)
1073                            .collect();
1074                        match inside.as_slice() {
1075                            [] => Ok(None),
1076                            [v] => Ok(Some(*v)),
1077                            _ => Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner twice at one angle"))),
1078                        }
1079                    };
1080                    let count = 720;
1081                    let has: Vec<bool> = (0..count).map(|k| in_zone(TAU * k as f64 / count as f64).map(|r| r.is_some())).collect::<Result<_, _>>()?;
1082                    let rises: Vec<usize> = (0..count).filter(|&k| has[k] && !has[(k + count - 1) % count]).collect();
1083                    let falls: Vec<usize> = (0..count).filter(|&k| !has[k] && has[(k + count - 1) % count]).collect();
1084                    let ([rise], [fall]) = (rises.as_slice(), falls.as_slice()) else {
1085                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve does not cross the rounded corner once")));
1086                    };
1087                    // The crossing's ends: roots of the grazing value along the rim it meets.
1088                    let estimate = |k: usize| TAU * (k as f64 - 0.5) / count as f64;
1089                    let (ea, eb) = (estimate(*rise), estimate(*fall));
1090                    let sample = |k: usize| TAU * (k % count) as f64 / count as f64;
1091                    let probe_v = in_zone(sample(*rise))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1092                    let at_end = (probe_v - end).abs() < (probe_v - start).abs();
1093                    let rim_v = if at_end { end } else { start };
1094                    let (a, b, c) = harmonic(|psi| g_tube(psi, rim_v));
1095                    let r = a.hypot(b);
1096                    let base = b.atan2(a);
1097                    let spread = (-c / r).acos();
1098                    let roots = [base - spread, base + spread];
1099                    let nearest = |e: f64| roots.iter().copied().min_by(|x, y| ((x - e + PI).rem_euclid(TAU) - PI).abs().total_cmp(&((y - e + PI).rem_euclid(TAU) - PI).abs())).expect("two");
1100                    let (psi_a, psi_b) = (nearest(ea).rem_euclid(TAU), nearest(eb).rem_euclid(TAU));
1101                    let psi_b = if psi_b <= psi_a { psi_b + TAU } else { psi_b };
1102                    let leave_v = in_zone(sample(*fall + count - 1))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1103                    if ((leave_v - end).abs() < (leave_v - start).abs()) != at_end {
1104                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner from rim to rim")));
1105                    }
1106                    kinds.push(Kind::TorusZone { psi_a, psi_b, at_end });
1107                    continue;
1108                }
1109                if !(centre_on_axis && (span - 0.5 * PI).abs() < 1e-12 && (pole_at_start && equator(p1) || on_axis(p1) && equator(p0))) {
1110                    // A cap of a sphere about the axis, from its pole to a rim
1111                    // short of (or past) the equator: swept where its grazing
1112                    // curves keep their angle about the axis (meridian arcs
1113                    // through the pole).
1114                    if centre_on_axis && end > start && span < PI && (pole_at_start != on_axis(p1)) {
1115                        let roots_at = |s: f64| -> Option<Vec<f64>> {
1116                            let (a, b, c) = harmonic(|psi| g(piece, s, psi));
1117                            let r = a.hypot(b);
1118                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1119                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1120                                return None;
1121                            }
1122                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1123                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1124                            list.sort_by(|x, y| x.total_cmp(y));
1125                            Some(list)
1126                        };
1127                        if let [Some(r0), Some(r1), Some(r2)] = [0.25, 0.5, 0.75].map(roots_at) {
1128                            if r0.iter().zip(&r1).chain(r0.iter().zip(&r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1129                                kinds.push(Kind::RuledArc(r0));
1130                                continue;
1131                            }
1132                        }
1133                    }
1134                    return Err(refuse("revolved_arc", format!("meridian piece {i}: only a quarter circle from a pole to an equator is swept here")));
1135                }
1136                kinds.push(Kind::Sphere { centre: origin.add(w.scale(centre[1])), pole_at_start });
1137            }
1138        }
1139    }
1140    // Rims: junctions off the axis, with the angles they are split at.
1141    let count = meridian.len();
1142    let junction = |k: usize| piece_point(&meridian[k], 1.0); // between piece k and k + 1
1143    let face_of = |piece: usize| faces.iter().position(|&f| f == piece);
1144    let mut rim_angles: HashMap<usize, Vec<f64>> = HashMap::new();
1145    for k in 0..count {
1146        if on_axis(junction(k)) {
1147            continue;
1148        }
1149        let mut angles: Vec<f64> = Vec::new();
1150        for (piece, s_end) in [(k, 1.0), ((k + 1) % count, 0.0)] {
1151            let Some(f) = face_of(piece) else { continue };
1152            match &kinds[f] {
1153                Kind::Ruled(roots) | Kind::RuledArc(roots) => angles.extend(roots.iter().copied()),
1154                Kind::Ball { .. } | Kind::Slide => {}
1155                Kind::SlideSide => angles.extend([0.0, PI]),
1156                Kind::TorusZone { psi_a, psi_b, .. } => angles.extend([psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)]),
1157                Kind::Moving => {
1158                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1159                    angles.extend([lower.rem_euclid(TAU), upper.rem_euclid(TAU)]);
1160                }
1161                Kind::Sphere { centre, .. } => {
1162                    let d = screw.velocity(*centre).cross(w);
1163                    let base = d.dot(u2).atan2(d.dot(u1)).rem_euclid(TAU);
1164                    angles.extend([base, (base + PI).rem_euclid(TAU)]);
1165                }
1166            }
1167        }
1168        angles.sort_by(|a, b| a.total_cmp(b));
1169        let mut merged: Vec<f64> = Vec::new();
1170        for a in angles {
1171            if merged.last().is_some_and(|&b| (a - b).abs() < 1e-9) || merged.first().is_some_and(|&b| (b + TAU - a).abs() < 1e-9) {
1172                continue;
1173            }
1174            merged.push(a);
1175        }
1176        rim_angles.insert(k, merged);
1177    }
1178    // Every face's own split angles must be its rims' (one arc per patch side).
1179    for (f, &piece) in faces.iter().enumerate() {
1180        for (k, s_end) in [((piece + count - 1) % count, 0.0), (piece, 1.0)] {
1181            let own: Vec<f64> = match &kinds[f] {
1182                Kind::Ruled(roots) | Kind::RuledArc(roots) => roots.clone(),
1183                Kind::Moving => {
1184                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1185                    let mut list = vec![lower.rem_euclid(TAU), upper.rem_euclid(TAU)];
1186                    list.sort_by(|a, b| a.total_cmp(b));
1187                    list
1188                }
1189                Kind::TorusZone { psi_a, psi_b, .. } => {
1190                    let mut list = vec![psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)];
1191                    list.sort_by(|a, b| a.total_cmp(b));
1192                    list
1193                }
1194                Kind::Sphere { .. } | Kind::Ball { .. } | Kind::Slide => continue,
1195                Kind::SlideSide => vec![0.0, PI],
1196            };
1197            if let Some(angles) = rim_angles.get(&k) {
1198                if own.is_empty() {
1199                    continue;
1200                }
1201                if angles.len() != own.len() || angles.iter().zip(&own).any(|(a, b)| (a - b).abs() > 1e-9) {
1202                    return Err(refuse("revolved_rims", format!("meridian piece {piece} splits at other angles than its rim")));
1203                }
1204            }
1205        }
1206    }
1207    let mut points: Vec<Vec3> = Vec::new();
1208    let mut curves: Vec<ToolCurve> = Vec::new();
1209    let mut caps: Vec<Cap> = Vec::new();
1210    let mut slides: Vec<SlideDisc> = Vec::new();
1211    let mut slide_sides: Vec<SlideSide> = Vec::new();
1212    // Rim points and arcs: arc j of rim k runs from angle j to angle j + 1.
1213    let mut rim_points: HashMap<(usize, usize), usize> = HashMap::new();
1214    let mut rim_arcs: HashMap<(usize, usize), usize> = HashMap::new();
1215    let mut rim_keys: Vec<usize> = rim_angles.keys().copied().collect();
1216    rim_keys.sort_unstable();
1217    for &k in &rim_keys {
1218        let q = junction(k);
1219        let angles = rim_angles[&k].clone();
1220        let angles = if angles.is_empty() { vec![0.0] } else { angles };
1221        for (j, &a) in angles.iter().enumerate() {
1222            points.push(at(q[0], q[1], a));
1223            rim_points.insert((k, j), points.len() - 1);
1224        }
1225        for j in 0..angles.len() {
1226            let a = angles[j];
1227            let b = if j + 1 < angles.len() { angles[j + 1] } else { angles[0] + TAU };
1228            let base = at(q[0], q[1], a);
1229            let surface = frag(make_revolution(origin, w, &frag(make_line(base, base.add(w)), "line")?, b - a), "rim")?;
1230            curves.push(ToolCurve {
1231                curve: frag(surface.iso_curve_v(0.0), "rim_arc")?,
1232                start: rim_points[&(k, j)],
1233                end: rim_points[&(k, (j + 1) % angles.len())],
1234                degenerate: false,
1235                samples: Some((0..=LOFT_SAMPLES).map(|i| at(q[0], q[1], a + (b - a) * i as f64 / LOFT_SAMPLES as f64)).collect()),
1236            });
1237            rim_arcs.insert((k, j), curves.len() - 1);
1238        }
1239        rim_angles.insert(k, angles);
1240    }
1241    let arc_index = |k: usize, angle: f64| -> Result<usize, KernelRefusal> {
1242        rim_angles[&k]
1243            .iter()
1244            .position(|&a| ((a - angle).rem_euclid(TAU)).min((angle - a).rem_euclid(TAU)) < 1e-9)
1245            .ok_or_else(|| refuse("revolved_rims", "a patch corner is not on its rim's split".into()))
1246    };
1247    let sign_at = |piece: &OutlinePiece, psi: f64| g(piece, 0.5, psi) > 0.0;
1248    for (f, &piece_index) in faces.iter().enumerate() {
1249        let piece = &meridian[piece_index];
1250        let below = (piece_index + count - 1) % count; // rim at the piece's start
1251        let above = piece_index; // rim at its end
1252        let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1253        match &kinds[f] {
1254            Kind::SlideSide => {
1255                if on_axis(m0) || on_axis(m1) {
1256                    return Err(refuse("revolved_grazing", format!("meridian piece {piece_index} grazes all over")));
1257                }
1258                let seams = [0.0, PI];
1259                let mut patches = Vec::with_capacity(2);
1260                for j in 0..2 {
1261                    let (alpha, theta) = (seams[j], PI);
1262                    let (ib, ia) = (arc_index(below, alpha)?, arc_index(above, alpha)?);
1263                    patches.push((alpha, theta, rim_arcs[&(below, ib)], rim_arcs[&(above, ia)], [rim_points[&(below, ib)], rim_points[&(above, ia)]]));
1264                }
1265                slide_sides.push(SlideSide { origin, w, patches });
1266            }
1267            Kind::RuledArc(roots) => {
1268                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1269                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1270                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1271                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1272                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1273                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1274                    let from = tube_point(psi, start);
1275                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1276                    frag(surface.iso_curve_v(0.0), "tube")
1277                };
1278                // A cap to its pole: the meridian arcs start (or end) there,
1279                // and each patch has a pole in place of a rim arc.
1280                let apex = if on_axis(m0) || on_axis(m1) {
1281                    let m = if on_axis(m0) { m0 } else { m1 };
1282                    points.push(at(0.0, m[1], 0.0));
1283                    Some(points.len() - 1)
1284                } else {
1285                    None
1286                };
1287                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1288                    match (on, apex) {
1289                        (true, Some(p)) => Ok(p),
1290                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1291                    }
1292                };
1293                let mut generators = Vec::with_capacity(roots.len());
1294                for &root in roots {
1295                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1296                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| tube_point(root, start + (end - start) * i as f64 / LOFT_SAMPLES as f64)).collect();
1297                    exact[0] = points[a];
1298                    exact[LOFT_SAMPLES] = points[b];
1299                    curves.push(ToolCurve { curve: generatrix(root)?, start: a, end: b, degenerate: false, samples: Some(exact) });
1300                    generators.push(curves.len() - 1);
1301                }
1302                for j in 0..roots.len() {
1303                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1304                    let surface = frag(make_revolution(origin, w, &generatrix(alpha)?, beta - alpha), "patch")?;
1305                    let (mid_psi, mid_v) = (0.5 * (alpha + beta), 0.5 * (start + end));
1306                    let mid_normal = w.scale(mid_v.sin()).add(u1.scale(mid_v.cos() * mid_psi.cos())).add(u2.scale(mid_v.cos() * mid_psi.sin()));
1307                    let front = screw.velocity(tube_point(mid_psi, mid_v)).dot(mid_normal) > 0.0;
1308                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1309                        let p = apex.expect("apex");
1310                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1311                        curves.len() - 1
1312                    };
1313                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1314                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1315                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1316                    let coedges = vec![
1317                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1318                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1319                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1320                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1321                    ];
1322                    let chart = Chart::Revolution {
1323                        origin,
1324                        w,
1325                        u1,
1326                        u2,
1327                        alpha,
1328                        theta: beta - alpha,
1329                        spans_u: spans_of(&surface.knots_u),
1330                        meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_of(&surface.knots_v) },
1331                    };
1332                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1333                }
1334            }
1335            Kind::Slide => {
1336                let rim = if on_axis(m0) { above } else { below };
1337                let n = normal(piece, 0.5);
1338                let outward = w.scale(n[1].signum());
1339                let arcs = rim_angles[&rim].len();
1340                // Counter-clockwise about the outward normal: increasing ψ about +w.
1341                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1342                slides.push(SlideDisc {
1343                    centre: origin.add(w.scale(m0[1])),
1344                    u: u1,
1345                    v: outward.cross(u1),
1346                    rim: order.into_iter().map(|j| (rim_arcs[&(rim, j)], n[1] > 0.0)).collect(),
1347                });
1348            }
1349            Kind::Ruled(roots) if roots.is_empty() => {
1350                // A flat end wholly on one side: a disc about the axis.
1351                let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
1352                if !flat || !(on_axis(m0) || on_axis(m1)) {
1353                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a whole side or ring is not swept here")));
1354                }
1355                let rim = if on_axis(m0) { above } else { below };
1356                let front = sign_at(piece, 0.0);
1357                if (0..64).any(|k| sign_at(piece, TAU * k as f64 / 64.0) != front) {
1358                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a flat end meets its grazing line")));
1359                }
1360                let n = normal(piece, 0.5);
1361                let outward = w.scale(n[1].signum());
1362                let centre = origin.add(w.scale(m0[1]));
1363                let (u, v) = (u1, outward.cross(u1));
1364                let arcs = rim_angles[&rim].len();
1365                let mut coedges = Vec::with_capacity(arcs);
1366                let mut corners = Vec::new();
1367                // Counter-clockwise about the outward normal: increasing ψ about +w.
1368                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1369                for j in order {
1370                    let c = rim_arcs[&(rim, j)];
1371                    let forward = n[1] > 0.0;
1372                    coedges.push((c, forward, plane_pcurve(centre, u, v, &curves[c].curve, forward)?));
1373                    corners.push(points[curves[c].start]);
1374                }
1375                let r = junction(rim)[0];
1376                corners.extend([centre.add(u.scale(r)).add(v.scale(r)), centre.sub(u.scale(r)).sub(v.scale(r))]);
1377                caps.push(Cap { surface: plane_patch(centre, u, v, &corners)?, front, coedges, chart: Some(Chart::Plane { origin: centre, u, v }) });
1378            }
1379            Kind::Ruled(roots) => {
1380                // A cone to a point: its generators start (or end) at the
1381                // apex, and each patch has a pole there in place of a rim arc.
1382                let apex = if on_axis(m0) || on_axis(m1) {
1383                    let m = if on_axis(m0) { m0 } else { m1 };
1384                    points.push(at(0.0, m[1], 0.0));
1385                    Some(points.len() - 1)
1386                } else {
1387                    None
1388                };
1389                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1390                    match (on, apex) {
1391                        (true, Some(p)) => Ok(p),
1392                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1393                    }
1394                };
1395                // Generators at each root, from the start rim to the end rim.
1396                let mut generators = Vec::with_capacity(roots.len());
1397                for &root in roots {
1398                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1399                    let line_samples = (0..=LOFT_SAMPLES).map(|i| points[a].add(points[b].sub(points[a]).scale(i as f64 / LOFT_SAMPLES as f64))).collect();
1400                    curves.push(ToolCurve { curve: frag(make_line(points[a], points[b]), "generator")?, start: a, end: b, degenerate: false, samples: Some(line_samples) });
1401                    generators.push(curves.len() - 1);
1402                }
1403                for j in 0..roots.len() {
1404                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1405                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1406                    let surface = frag(make_revolution(origin, w, &generatrix, beta - alpha), "patch")?;
1407                    let front = sign_at(piece, 0.5 * (alpha + beta));
1408                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1409                        let p = apex.expect("apex");
1410                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1411                        curves.len() - 1
1412                    };
1413                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1414                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1415                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1416                    let coedges = vec![
1417                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1418                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1419                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1420                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1421                    ];
1422                    let chart = Chart::Revolution { origin, w, u1, u2, alpha, theta: beta - alpha, spans_u: spans_of(&surface.knots_u), meridian: MeridianChart::Line { m0, m1 } };
1423                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1424                }
1425            }
1426            Kind::Moving => {
1427                if on_axis(m0) || on_axis(m1) {
1428                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a split cone to a point is not swept here")));
1429                }
1430                let n = 128;
1431                let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1432                let pairs: Vec<(f64, f64)> = params.iter().map(|&t| branches(piece, t).expect("checked")).collect();
1433                let pick = |pair: (f64, f64), which: usize| if which == 0 { pair.0 } else { pair.1 };
1434                // K: the lower and upper branch, each from the start rim to the end rim.
1435                let mut branch_curves = [0usize; 2];
1436                for which in 0..2 {
1437                    let (psi0, psi1) = (pick(pairs[0], which), pick(pairs[n], which));
1438                    let start = rim_points[&(below, arc_index(below, psi0)?)];
1439                    let end = rim_points[&(above, arc_index(above, psi1)?)];
1440                    let mut samples: Vec<Vec3> = params
1441                        .iter()
1442                        .zip(&pairs)
1443                        .map(|(&t, &pair)| {
1444                            let m = piece_point(piece, t);
1445                            at(m[0], m[1], pick(pair, which))
1446                        })
1447                        .collect();
1448                    samples[0] = points[start];
1449                    samples[n] = points[end];
1450                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES)
1451                        .map(|i| {
1452                            let t = i as f64 / LOFT_SAMPLES as f64;
1453                            let m = piece_point(piece, t);
1454                            at(m[0], m[1], pick(branches(piece, t).expect("checked"), which))
1455                        })
1456                        .collect();
1457                    exact[0] = points[start];
1458                    exact[LOFT_SAMPLES] = points[end];
1459                    curves.push(ToolCurve { curve: frag(fit_tool_curve(&samples, &params), "branch")?, start, end, degenerate: false, samples: Some(exact) });
1460                    branch_curves[which] = curves.len() - 1;
1461                }
1462                // Front between lower and upper; back from upper to lower + 2π.
1463                for (lo_which, hi_which, hi_turn) in [(0usize, 1usize, 0.0), (1, 0, TAU)] {
1464                    let lo = |i: usize| pick(pairs[i], lo_which);
1465                    let hi = |i: usize| pick(pairs[i], hi_which) + hi_turn;
1466                    let alpha = (0..=n).map(lo).fold(f64::INFINITY, f64::min) - 1e-3;
1467                    let theta = (0..=n).map(hi).fold(f64::NEG_INFINITY, f64::max) + 1e-3 - alpha;
1468                    if theta >= TAU {
1469                        return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a side patch wraps all the way round")));
1470                    }
1471                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1472                    let surface = frag(make_revolution(origin, w, &generatrix, theta), "patch")?;
1473                    let spans = (surface.knots_u.len() - 6) / 2 + 1;
1474                    let u_of = |psi: f64| crate::circle_angle_to_parameter(spans, theta, psi - alpha);
1475                    let angle_near = |x: Vec3, guess: f64| -> f64 {
1476                        let r = x.sub(origin);
1477                        let a = r.dot(u2).atan2(r.dot(u1));
1478                        guess + (a - guess + PI).rem_euclid(TAU) - PI
1479                    };
1480                    let front = sign_at(piece, 0.5 * (lo(n / 2) + hi(n / 2)));
1481                    // A rim arc's pcurve on this patch, through its own parameter.
1482                    let rim_pcurve = |arc: usize, v: f64| -> Result<NurbsCurve, KernelRefusal> {
1483                        let curve = &curves[arc].curve;
1484                        let [d0, d1] = frag(curve.domain(), "domain")?;
1485                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1486                        let mut uv = Vec::with_capacity(ts.len());
1487                        for &t in &ts {
1488                            let x = frag(curve.evaluate(t), "rim")?;
1489                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), v, 0.0));
1490                        }
1491                        if pcurve_joints_on() {
1492                            let (ju, jv) = surface_joints(&surface);
1493                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok([u_of(angle_near(frag(curve.evaluate(t), "rim")?, alpha + 0.5 * theta)), v]) };
1494                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1495                                return Ok(fitted);
1496                            }
1497                        }
1498                        frag(fit_pcurve(&uv, &ts), "rim_pcurve")
1499                    };
1500                    // A grazing branch's pcurve: the image of the built edge,
1501                    // through its own parameter (angle about the axis; place
1502                    // along the meridian line).
1503                    let branch_pcurve = |which: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> {
1504                        let curve = &curves[branch_curves[which]].curve;
1505                        let [d0, d1] = frag(curve.domain(), "domain")?;
1506                        let (span_rho, span_z) = (m1[0] - m0[0], m1[1] - m0[1]);
1507                        let length2 = span_rho * span_rho + span_z * span_z;
1508                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1509                        let mut uv = Vec::with_capacity(ts.len());
1510                        let read = |x: Vec3| -> [f64; 2] {
1511                            let r = x.sub(origin);
1512                            let z = r.dot(w);
1513                            let rho = r.sub(w.scale(z)).length();
1514                            let along = ((rho - m0[0]) * span_rho + (z - m0[1]) * span_z) / length2;
1515                            [u_of(angle_near(x, alpha + 0.5 * theta)), along]
1516                        };
1517                        for &t in &ts {
1518                            let [u, along] = read(frag(curve.evaluate(t), "branch")?);
1519                            uv.push(Vec3::new(u, along, 0.0));
1520                        }
1521                        if pcurve_joints_on() {
1522                            let (ju, jv) = surface_joints(&surface);
1523                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "branch")?)) };
1524                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1525                                return Ok(fitted);
1526                            }
1527                        }
1528                        frag(fit_pcurve(&uv, &ts), "branch_pcurve")
1529                    };
1530                    let bottom = rim_arcs[&(below, arc_index(below, lo(0))?)];
1531                    let top = rim_arcs[&(above, arc_index(above, lo(n))?)];
1532                    let coedges = vec![
1533                        (bottom, true, rim_pcurve(bottom, 0.0)?),
1534                        (branch_curves[hi_which], true, branch_pcurve(hi_which, hi_turn)?),
1535                        (top, false, frag(rim_pcurve(top, 1.0)?.reversed(), "reversed")?),
1536                        (branch_curves[lo_which], false, frag(branch_pcurve(lo_which, 0.0)?.reversed(), "reversed")?),
1537                    ];
1538                    let chart_spans = spans_of(&surface.knots_u);
1539                    caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u: chart_spans, meridian: MeridianChart::Line { m0, m1 } }) });
1540                }
1541            }
1542            Kind::TorusZone { psi_a, psi_b, at_end } => {
1543                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1544                let (psi_a, psi_b, at_end) = (*psi_a, *psi_b, *at_end);
1545                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1546                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1547                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1548                let normal_at = |psi: f64, v: f64| w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1549                let root = |psi: f64| -> Option<f64> {
1550                    let (a, b, c) = harmonic(|v| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)));
1551                    let r = a.hypot(b);
1552                    if !(c.abs() < r) {
1553                        return None;
1554                    }
1555                    let base = b.atan2(a);
1556                    let spread = (-c / r).acos();
1557                    [base - spread, base + spread].into_iter().map(|v| start + (v - start).rem_euclid(TAU)).find(|&v| v <= end + 1e-12)
1558                };
1559                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1560                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1561                    let from = tube_point(psi, start);
1562                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1563                    frag(surface.iso_curve_v(0.0), "tube")
1564                };
1565                let (rim_k, other_k) = if at_end { (above, below) } else { (below, above) };
1566                let ka = rim_points[&(rim_k, arc_index(rim_k, psi_a)?)];
1567                let kb = rim_points[&(rim_k, arc_index(rim_k, psi_b)?)];
1568                // K: the graph over ψ ∈ [ψa, ψb].
1569                let n = 256;
1570                let params: Vec<f64> = (0..=n).map(|j| j as f64 / n as f64).collect();
1571                // Spaced as 1 − cos: where K meets its rim it runs along the
1572                // meridian, so its tube angle goes as √(ψ − ψa); in this
1573                // parameter it is regular.
1574                let psi_of = |t: f64| psi_a + (psi_b - psi_a) * 0.5 * (1.0 - (PI * t).cos());
1575                let mut xyz = Vec::with_capacity(n + 1);
1576                for j in 0..=n {
1577                    let psi = psi_of(params[j]);
1578                    let v = if j == 0 || j == n { if at_end { end } else { start } } else {
1579                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1580                    };
1581                    xyz.push(tube_point(psi, v));
1582                }
1583                xyz[0] = points[ka];
1584                xyz[n] = points[kb];
1585                let mut exact = Vec::with_capacity(LOFT_SAMPLES + 1);
1586                for i in 0..=LOFT_SAMPLES {
1587                    let psi = psi_of(i as f64 / LOFT_SAMPLES as f64);
1588                    let v = if i == 0 || i == LOFT_SAMPLES { if at_end { end } else { start } } else {
1589                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1590                    };
1591                    exact.push(tube_point(psi, v));
1592                }
1593                exact[0] = points[ka];
1594                exact[LOFT_SAMPLES] = points[kb];
1595                curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "torus_k")?, start: ka, end: kb, degenerate: false, samples: Some(exact) });
1596                let k_curve = curves.len() - 1;
1597                // Cut meridians at ψa and ψb, from the start rim to the end rim.
1598                let mut cut = [0usize; 2];
1599                for (slot, psi) in [(0, psi_a), (1, psi_b)] {
1600                    let (lo, hi) = (rim_points[&(below, arc_index(below, psi)?)], rim_points[&(above, arc_index(above, psi)?)]);
1601                    curves.push(ToolCurve { curve: generatrix(psi)?, start: lo, end: hi, degenerate: false, samples: None });
1602                    cut[slot] = curves.len() - 1;
1603                }
1604                let label = |psi: f64, v: f64| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)) > 0.0;
1605                // The patch over [α, β] and its exact inverse.
1606                let patch = |alpha: f64, beta: f64| -> Result<(NurbsSurface, usize, usize), KernelRefusal> {
1607                    let g = generatrix(alpha)?;
1608                    let surface = frag(make_revolution(origin, w, &g, beta - alpha), "torus_patch")?;
1609                    let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1610                    let spans_v = (g.knots.len() - 6) / 2 + 1;
1611                    Ok((surface, spans_u, spans_v))
1612                };
1613                let inverse_pcurve = |curve: &NurbsCurve, alpha: f64, beta: f64, spans_u: usize, spans_v: usize, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
1614                    let [d0, d1] = frag(curve.domain(), "domain")?;
1615                    let ts: Vec<f64> = pcurve_stations(d0, d1);
1616                    let mut uv = Vec::with_capacity(ts.len());
1617                    let read = |x: Vec3| -> [f64; 2] {
1618                        let r = x.sub(origin);
1619                        let mid = 0.5 * (alpha + beta);
1620                        let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
1621                        let q = x.sub(tube_centre(psi));
1622                        let radial = u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1623                        let vmid = 0.5 * (start + end);
1624                        let v = vmid + (q.dot(w).atan2(q.dot(radial)) - vmid + PI).rem_euclid(TAU) - PI;
1625                        [crate::circle_angle_to_parameter(spans_u, beta - alpha, psi - alpha), crate::circle_angle_to_parameter(spans_v, end - start, v - start)]
1626                    };
1627                    for &t in &ts {
1628                        let [u, v] = read(frag(curve.evaluate(t), "point")?);
1629                        uv.push(Vec3::new(u, v, 0.0));
1630                    }
1631                    if pcurve_joints_on() {
1632                        let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1633                        let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "point")?)) };
1634                        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1635                            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
1636                        }
1637                    }
1638                    let fitted = frag(fit_pcurve(&uv, &ts), "torus_pcurve")?;
1639                    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
1640                };
1641                // The band away from K: a natural patch over [ψb, ψa + 2π].
1642                {
1643                    let (surface, _, band_spans_v) = patch(psi_b, psi_a + TAU)?;
1644                    let (bottom, top) = (rim_arcs[&(below, arc_index(below, psi_b)?)], rim_arcs[&(above, arc_index(above, psi_b)?)]);
1645                    let coedges = vec![
1646                        (bottom, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1647                        (cut[0], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1648                        (top, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1649                        (cut[1], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1650                    ];
1651                    let mid = psi_b + 0.5 * (psi_a + TAU - psi_b);
1652                    let chart_spans = spans_of(&surface.knots_u);
1653                    caps.push(Cap { surface, front: label(mid, 0.5 * (start + end)), coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_b, theta: psi_a + TAU - psi_b, spans_u: chart_spans, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: band_spans_v } }) });
1654                }
1655                // Over [ψa, ψb]: the lens between K and its rim, and the rest.
1656                let (surface, spans_u, spans_v) = patch(psi_a, psi_b)?;
1657                let rim_arc = rim_arcs[&(rim_k, arc_index(rim_k, psi_a)?)];
1658                let other_arc = rim_arcs[&(other_k, arc_index(other_k, psi_a)?)];
1659                let mid = 0.5 * (psi_a + psi_b);
1660                let v_k = root(mid).ok_or_else(|| refuse("torus_zone", "no grazing point mid-way".into()))?;
1661                let k_pc = |forward: bool| inverse_pcurve(&curves[k_curve].curve, psi_a, psi_b, spans_u, spans_v, forward);
1662                let lens_v = if at_end { 0.5 * (v_k + end) } else { 0.5 * (v_k + start) };
1663                let rest_v = if at_end { 0.5 * (v_k + start) } else { 0.5 * (v_k + end) };
1664                if at_end {
1665                    // Lens: K (ψa -> ψb) under the end rim, then the end rim back.
1666                    let lens = vec![(k_curve, true, k_pc(true)?), (rim_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?)];
1667                    caps.push(Cap { surface: surface.clone(), front: label(mid, lens_v), coedges: lens, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1668                    let rest = vec![
1669                        (other_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1670                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1671                        (k_curve, false, k_pc(false)?),
1672                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1673                    ];
1674                    caps.push(Cap { surface, front: label(mid, rest_v), coedges: rest, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1675                } else {
1676                    let lens = vec![(rim_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?), (k_curve, false, k_pc(false)?)];
1677                    caps.push(Cap { surface: surface.clone(), front: label(mid, lens_v), coedges: lens, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1678                    let rest = vec![
1679                        (k_curve, true, k_pc(true)?),
1680                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1681                        (other_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1682                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1683                    ];
1684                    caps.push(Cap { surface, front: label(mid, rest_v), coedges: rest, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1685                }
1686            }
1687            Kind::Ball { centre, radius } => {
1688                let m = frag(screw.velocity(*centre).normalized(), "ball_still")?;
1689                let d = frag(w.cross(m).normalized().or_else(|_| u1.cross(m).normalized()), "ball_axis")?;
1690                let (e1, e2) = (centre.add(d.scale(*radius)), centre.sub(d.scale(*radius)));
1691                points.push(e1);
1692                points.push(e2);
1693                let (i1, i2) = (points.len() - 2, points.len() - 1);
1694                let half = frag(make_revolution(*centre, m, &frag(make_line(e1, e1.add(m)), "line")?, PI), "great")?;
1695                let k_a = frag(half.iso_curve_v(0.0), "great")?;
1696                // Exact samples at even angles from e1 round to e2 (for a
1697                // lofted wall), turned the way the curve runs.
1698                let k_a_samples: Vec<Vec3> = {
1699                    let [a0, a1] = frag(k_a.domain(), "domain")?;
1700                    let middle = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?;
1701                    let arm = e1.sub(*centre);
1702                    let sense = if arm.rotate_about(m, 0.5 * PI).add(*centre).sub(middle).length() < arm.rotate_about(m, -0.5 * PI).add(*centre).sub(middle).length() { 1.0 } else { -1.0 };
1703                    let mut list: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| centre.add(arm.rotate_about(m, sense * PI * i as f64 / LOFT_SAMPLES as f64))).collect();
1704                    list[0] = e1;
1705                    list[LOFT_SAMPLES] = e2;
1706                    list
1707                };
1708                curves.push(ToolCurve { curve: k_a.clone(), start: i1, end: i2, degenerate: false, samples: Some(k_a_samples.clone()) });
1709                let k_a_index = curves.len() - 1;
1710                let [a0, a1] = frag(k_a.domain(), "domain")?;
1711                let h = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?.sub(*centre);
1712                let mut k_b_index: Option<usize> = None;
1713                for front in [true, false] {
1714                    let toward = if front { m } else { m.scale(-1.0) };
1715                    let da = if d.cross(h).dot(toward) > 0.0 { d } else { d.scale(-1.0) };
1716                    let mut generatrix = k_a.clone();
1717                    let mut surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1718                    let outward = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1719                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1720                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1721                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1722                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1723                    };
1724                    let mut forward = true;
1725                    if !outward(&surface)? {
1726                        generatrix = frag(generatrix.reversed(), "reversed")?;
1727                        surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1728                        forward = false;
1729                    }
1730                    let (start, end) = if forward { (i1, i2) } else { (i2, i1) };
1731                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1732                    let k_b = match k_b_index {
1733                        Some(index) => index,
1734                        None => {
1735                            // The other half of the great circle: the first half turned half way about `da`.
1736                            let mut samples: Vec<Vec3> = k_a_samples.iter().map(|&x| centre.add(x.sub(*centre).rotate_about(da, PI))).collect();
1737                            if !forward {
1738                                samples.reverse();
1739                            }
1740                            samples[0] = points[start];
1741                            samples[LOFT_SAMPLES] = points[end];
1742                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: Some(samples) });
1743                            k_b_index = Some(curves.len() - 1);
1744                            curves.len() - 1
1745                        }
1746                    };
1747                    let k_b_forward = curves[k_b].start == start;
1748                    let k_b_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1749                    let poles = [start, end].map(|p| {
1750                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1751                        curves.len() - 1
1752                    });
1753                    let coedges = vec![
1754                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1755                        (k_b, k_b_forward, k_b_pcurve),
1756                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1757                        (k_a_index, !forward, uv_line([0.0, g1], [0.0, g0])?),
1758                    ];
1759                    caps.push(Cap { surface, front, coedges, chart: None });
1760                }
1761            }
1762            Kind::Sphere { centre, pole_at_start } => {
1763                let rim = if *pole_at_start { above } else { below };
1764                let angles = rim_angles[&rim].clone();
1765                if angles.len() != 2 {
1766                    return Err(refuse("revolved_rims", "a hemisphere's rim is not split in two".into()));
1767                }
1768                let pole_side = w.scale(if *pole_at_start { m0[1] - m1[1] } else { m1[1] - m0[1] }.signum());
1769                let m = screw.velocity(*centre);
1770                let e1 = points[rim_points[&(rim, 0)]];
1771                let d = frag(e1.sub(*centre).normalized(), "lune_axis")?;
1772                let mut great: Option<usize> = None;
1773                for j in 0..2 {
1774                    let arc = rim_arcs[&(rim, j)];
1775                    let [a0, a1] = frag(curves[arc].curve.domain(), "domain")?;
1776                    let middle = frag(curves[arc].curve.evaluate(0.5 * (a0 + a1)), "middle")?;
1777                    let hv = middle.sub(*centre);
1778                    let da = if d.cross(hv).dot(pole_side) > 0.0 { d } else { d.scale(-1.0) };
1779                    // Turn the rim arc about da until its middle reaches K's plane.
1780                    let theta = (-m.dot(hv)).atan2(m.dot(da.cross(hv))).rem_euclid(TAU);
1781                    let theta = if theta > PI { theta - PI } else { theta };
1782                    if !(theta > 1e-9 && theta < PI - 1e-9) {
1783                        return Err(refuse("revolved_lune", "the great circle meets the rim's plane edge-on".into()));
1784                    }
1785                    let mut generatrix = curves[arc].curve.clone();
1786                    let mut surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1787                    // Outward: (x − centre) at the lune's middle.
1788                    let probe = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1789                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1790                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1791                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1792                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1793                    };
1794                    let mut forward = true;
1795                    if !probe(&surface)? {
1796                        generatrix = frag(generatrix.reversed(), "reversed")?;
1797                        surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1798                        forward = false;
1799                    }
1800                    let (start, end) = if forward { (curves[arc].start, curves[arc].end) } else { (curves[arc].end, curves[arc].start) };
1801                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1802                    // The great-circle half: the turned generatrix (u = 1), from
1803                    // `start` to `end`; made once, by the first lune.
1804                    let k_curve = match great {
1805                        Some(index) => index,
1806                        None => {
1807                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: None });
1808                            great = Some(curves.len() - 1);
1809                            curves.len() - 1
1810                        }
1811                    };
1812                    let k_forward = curves[k_curve].start == start;
1813                    let poles = [start, end].map(|p| {
1814                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1815                        curves.len() - 1
1816                    });
1817                    let k_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1818                    let coedges = vec![
1819                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1820                        (k_curve, k_forward, k_pcurve),
1821                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1822                        (arc, !forward, uv_line([0.0, g1], [0.0, g0])?),
1823                    ];
1824                    let mid_psi = if j == 0 { 0.5 * (angles[0] + angles[1]) } else { 0.5 * (angles[1] + angles[0] + TAU) };
1825                    let front = m.dot(at(1.0, 0.0, mid_psi).sub(origin)) > 0.0;
1826                    caps.push(Cap { surface, front, coedges, chart: None });
1827                }
1828            }
1829        }
1830    }
1831    Ok(Split {
1832        points,
1833        curves,
1834        caps,
1835        slides,
1836        slide_sides,
1837        scale,
1838        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1839    })
1840}
1841
1842/// `BREP_SWEEP_RING_WINDING` (default off): a ring whose grazing curves wind
1843/// round its tube as they go once round the ring is split along their
1844/// continuous unwrapping, in six pieces, instead of refused.
1845fn ring_winding_on() -> bool {
1846    crate::switch!("BREP_SWEEP_RING_WINDING", false)
1847}
1848
1849/// A ring split by grazing curves that wind round its tube: the curves' angle
1850/// v on the tube, unwrapped continuously along ψ, gains a whole number of
1851/// turns going once round the ring. None where it gains none (the two-halves
1852/// split serves). Six pieces along ψ keep each band's stretch of v short of a
1853/// whole turn while the curves turn, and leave the tumble's eight trial seams
1854/// (π/4 apart) four distinct placements.
1855#[allow(clippy::too_many_arguments)]
1856fn split_torus_wound(
1857    screw: &Screw,
1858    origin: Vec3,
1859    w: Vec3,
1860    u1: Vec3,
1861    u2: Vec3,
1862    centre: [f64; 2],
1863    radius: f64,
1864    meridian: &[OutlinePiece],
1865) -> Result<Option<Split>, KernelRefusal> {
1866    const PIECES: usize = 6;
1867    let (rho_c, z_c) = (centre[0], centre[1]);
1868    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1869    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
1870    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
1871    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
1872    let n = screw.loop_samples;
1873    let total = PIECES * n;
1874    // (ψ, lower, upper) round the whole ring, each base angle the one nearest
1875    // the last.
1876    let mut round: Vec<(f64, f64, f64)> = Vec::with_capacity(total + 1);
1877    let mut near = {
1878        let (a, b, _) = harmonic(|v| g(0.0, v));
1879        b.atan2(a)
1880    };
1881    for i in 0..=total {
1882        let psi = TAU * i as f64 / total as f64;
1883        let (a, b, c) = harmonic(|v| g(psi, v));
1884        let r = a.hypot(b);
1885        if !(c.abs() < r * (1.0 - 1e-9)) {
1886            return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
1887        }
1888        let base = near + (b.atan2(a) - near + PI).rem_euclid(TAU) - PI;
1889        if i > 0 && (base - near).abs() > 0.5 {
1890            return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
1891        }
1892        near = base;
1893        let spread = (-c / r).acos();
1894        round.push((psi, base - spread, base + spread));
1895    }
1896    if ((round[total].1 - round[0].1) / TAU).round() == 0.0 {
1897        return Ok(None);
1898    }
1899    let samples: Vec<Vec<(f64, f64, f64)>> = (0..PIECES).map(|k| round[k * n..=(k + 1) * n].to_vec()).collect();
1900    let seam_psi = |k: usize| TAU * k as f64 / PIECES as f64;
1901    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1902    let mut points: Vec<Vec3> = Vec::new();
1903    let mut curves: Vec<ToolCurve> = Vec::new();
1904    // Points: at each seam, on each branch (the last piece ends on seam 0,
1905    // a whole number of turns round the tube on).
1906    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, branch)
1907    for (seam, piece) in samples.iter().enumerate() {
1908        let (psi, lower, upper) = piece[0];
1909        for (branch, v) in [(0, lower), (1, upper)] {
1910            points.push(point(psi, v));
1911            corner.insert((seam, branch), points.len() - 1);
1912        }
1913    }
1914    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (piece, branch)
1915    for (piece, list) in samples.iter().enumerate() {
1916        for branch in 0..2 {
1917            let mut xyz: Vec<Vec3> = list.iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
1918            let (start, end) = (corner[&(piece, branch)], corner[&((piece + 1) % PIECES, branch)]);
1919            xyz[0] = points[start];
1920            xyz[n] = points[end];
1921            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
1922            branch_curve.insert((piece, branch), curves.len() - 1);
1923        }
1924    }
1925    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
1926        let start = point(psi, v0);
1927        let axis = radial(psi).cross(w);
1928        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
1929        frag(surface.iso_curve_v(0.0), "tube_arc")
1930    };
1931    // Seam arcs of each band: band 0 (front) from lower to upper, band 1
1932    // (back) from upper to lower + 2π.
1933    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
1934    for seam in 0..PIECES {
1935        let (psi, lower, upper) = samples[seam][0];
1936        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
1937        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
1938        seam_arc.insert((seam, 0), curves.len() - 1);
1939        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
1940        seam_arc.insert((seam, 1), curves.len() - 1);
1941    }
1942    let mut caps = Vec::new();
1943    for piece in 0..PIECES {
1944        let (psi_a, psi_b) = (seam_psi(piece), seam_psi(piece + 1));
1945        for band in 0..2 {
1946            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
1947            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
1948            // As in the two-halves split: a margin each side for end trims.
1949            let low = samples[piece].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
1950            let high = samples[piece].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
1951            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
1952            let (v_low, v_high) = (low - margin, high + margin);
1953            let theta_v = v_high - v_low;
1954            if theta_v >= TAU {
1955                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
1956            }
1957            let generatrix = tube_arc(psi_a, v_low, v_high)?;
1958            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
1959            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1960            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
1961            let uv_of = |psi: f64, v: f64| {
1962                Vec3::new(
1963                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
1964                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
1965                    0.0,
1966                )
1967            };
1968            let angles_of = |x: Vec3| -> (f64, f64) {
1969                let r = x.sub(origin);
1970                let psi = r.dot(u2).atan2(r.dot(u1));
1971                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
1972                let q = x.sub(tube_centre(psi));
1973                let v = q.dot(w).atan2(q.dot(radial(psi)));
1974                let mid = 0.5 * (v_low + v_high);
1975                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
1976            };
1977            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1978                let [d0, d1] = frag(curve.domain(), "domain")?;
1979                let ts: Vec<f64> = pcurve_stations(d0, d1);
1980                let mut uv = Vec::with_capacity(ts.len());
1981                for &t in &ts {
1982                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1983                    uv.push(uv_of(psi, v));
1984                }
1985                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
1986                if pcurve_joints_on() {
1987                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1988                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
1989                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1990                        let p = uv_of(psi, v);
1991                        Ok([p.x, p.y])
1992                    };
1993                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1994                        return Ok(fitted);
1995                    }
1996                }
1997                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
1998            };
1999            let lower_edge = branch_curve[&(piece, lo_branch)];
2000            let upper_edge = branch_curve[&(piece, hi_branch)];
2001            let right = seam_arc[&((piece + 1) % PIECES, band)];
2002            let left = seam_arc[&(piece, band)];
2003            let coedges = vec![
2004                (lower_edge, true, inverse_pcurve(&curves[lower_edge].curve)?),
2005                (right, true, inverse_pcurve(&curves[right].curve)?),
2006                (upper_edge, false, frag(inverse_pcurve(&curves[upper_edge].curve)?.reversed(), "reversed")?),
2007                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2008            ];
2009            let mid = &samples[piece][n / 2];
2010            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2011            caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre: [rho_c, z_c], start: v_low, sweep: theta_v, spans: spans_v } }) });
2012        }
2013    }
2014    Ok(Some(Split {
2015        points,
2016        curves,
2017        caps,
2018        slides: Vec::new(),
2019        slide_sides: Vec::new(),
2020        scale: rho_c + radius,
2021        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2022    }))
2023}
2024
2025/// A ring (torus: the circle of `radius` about `centre` in (ρ, z), off the
2026/// axis), split by its two grazing curves. For each angle ψ about the ring's
2027/// axis the grazing value along the tube's circle is A cos v + B sin v + C, so
2028/// each curve is a graph v(ψ) round the ring; the front band lies between
2029/// them. Each band is built in two halves (ψ in [0, π] and [π, 2π]) so no face
2030/// closes on itself.
2031#[allow(clippy::too_many_arguments)]
2032fn split_torus(
2033    screw: &Screw,
2034    origin: Vec3,
2035    w: Vec3,
2036    u1: Vec3,
2037    u2: Vec3,
2038    centre: [f64; 2],
2039    radius: f64,
2040    meridian: &[OutlinePiece],
2041) -> Result<Split, KernelRefusal> {
2042    if ring_winding_on() {
2043        if let Some(split) = split_torus_wound(screw, origin, w, u1, u2, centre, radius, meridian)? {
2044            return Ok(split);
2045        }
2046    }
2047    let (rho_c, z_c) = (centre[0], centre[1]);
2048    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
2049    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
2050    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
2051    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
2052    let reference = {
2053        let (a, b, _) = harmonic(|v| g(0.0, v));
2054        b.atan2(a)
2055    };
2056    // The lower and upper grazing angles v at ψ, unwrapped; the front between.
2057    let branches = |psi: f64| -> Option<(f64, f64)> {
2058        let (a, b, c) = harmonic(|v| g(psi, v));
2059        let r = a.hypot(b);
2060        if !(c.abs() < r * (1.0 - 1e-9)) {
2061            return None;
2062        }
2063        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
2064        let spread = (-c / r).acos();
2065        Some((base - spread, base + spread))
2066    };
2067    let n = screw.loop_samples;
2068    let halves = [(0.0, PI), (PI, TAU)];
2069    let mut samples: Vec<Vec<(f64, f64, f64)>> = Vec::new(); // per half: (ψ, lower, upper)
2070    for &(a, b) in &halves {
2071        let mut list = Vec::with_capacity(n + 1);
2072        let mut previous: Option<(f64, f64)> = None;
2073        for i in 0..=n {
2074            let psi = a + (b - a) * i as f64 / n as f64;
2075            let Some(pair) = branches(psi) else {
2076                return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
2077            };
2078            if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
2079                return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
2080            }
2081            previous = Some(pair);
2082            list.push((psi, pair.0, pair.1));
2083        }
2084        samples.push(list);
2085    }
2086    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
2087    let mut points: Vec<Vec3> = Vec::new();
2088    let mut curves: Vec<ToolCurve> = Vec::new();
2089    // Points: at ψ = 0 and π, on each branch.
2090    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam 0 | 1, branch)
2091    for seam in 0..2 {
2092        let (psi, (lower, upper)) = if seam == 0 { (0.0, (samples[0][0].1, samples[0][0].2)) } else { (PI, (samples[1][0].1, samples[1][0].2)) };
2093        for (branch, v) in [(0, lower), (1, upper)] {
2094            points.push(point(psi, v));
2095            corner.insert((seam, branch), points.len() - 1);
2096        }
2097    }
2098    let seam_of_end = |half: usize, at_end: bool| -> usize { if at_end { 1 - half } else { half } };
2099    // K: each branch over each half.
2100    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (half, branch)
2101    for half in 0..2 {
2102        for branch in 0..2 {
2103            let mut xyz: Vec<Vec3> = samples[half].iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
2104            let (start, end) = (corner[&(seam_of_end(half, false), branch)], corner[&(seam_of_end(half, true), branch)]);
2105            xyz[0] = points[start];
2106            xyz[n] = points[end];
2107            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
2108            branch_curve.insert((half, branch), curves.len() - 1);
2109        }
2110    }
2111    // Seam arcs of each band at ψ = 0 and π: band 0 (front) from lower to
2112    // upper, band 1 (back) from upper to lower + 2π.
2113    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
2114        let start = point(psi, v0);
2115        let axis = radial(psi).cross(w);
2116        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
2117        frag(surface.iso_curve_v(0.0), "tube_arc")
2118    };
2119    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
2120    for seam in 0..2 {
2121        let psi = if seam == 0 { 0.0 } else { PI };
2122        let (lower, upper) = (samples[seam][0].1, samples[seam][0].2);
2123        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
2124        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
2125        seam_arc.insert((seam, 0), curves.len() - 1);
2126        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
2127        seam_arc.insert((seam, 1), curves.len() - 1);
2128    }
2129    let mut caps = Vec::new();
2130    for half in 0..2 {
2131        let (psi_a, psi_b) = halves[half];
2132        for band in 0..2 {
2133            // The band's lower and upper edges (v), as branches.
2134            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
2135            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
2136            // A margin each side: an end cap may be carried a little across its
2137            // grazing curve (see `end_trim`), as far as the tube leaves room.
2138            let low = samples[half].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
2139            let high = samples[half].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
2140            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
2141            let (v_low, v_high) = (low - margin, high + margin);
2142            let theta_v = v_high - v_low;
2143            if theta_v >= TAU {
2144                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
2145            }
2146            let generatrix = tube_arc(psi_a, v_low, v_high)?;
2147            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
2148            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
2149            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
2150            let uv_of = |psi: f64, v: f64| {
2151                Vec3::new(
2152                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
2153                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
2154                    0.0,
2155                )
2156            };
2157            // (ψ, v) of a point, unwrapped near the patch.
2158            let angles_of = |x: Vec3| -> (f64, f64) {
2159                let r = x.sub(origin);
2160                let psi = r.dot(u2).atan2(r.dot(u1));
2161                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
2162                let q = x.sub(tube_centre(psi));
2163                let v = q.dot(w).atan2(q.dot(radial(psi)));
2164                let mid = 0.5 * (v_low + v_high);
2165                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
2166            };
2167            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
2168                let [d0, d1] = frag(curve.domain(), "domain")?;
2169                let ts: Vec<f64> = pcurve_stations(d0, d1);
2170                let mut uv = Vec::with_capacity(ts.len());
2171                for &t in &ts {
2172                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2173                    uv.push(uv_of(psi, v));
2174                }
2175                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
2176                if pcurve_joints_on() {
2177                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
2178                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
2179                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2180                        let p = uv_of(psi, v);
2181                        Ok([p.x, p.y])
2182                    };
2183                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
2184                        return Ok(fitted);
2185                    }
2186                }
2187                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
2188            };
2189            let branch_pcurve = |b: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> { inverse_pcurve(&curves[branch_curve[&(half, b)]].curve) };
2190            let lower_edge = branch_curve[&(half, lo_branch)];
2191            let upper_edge = branch_curve[&(half, hi_branch)];
2192            let right = seam_arc[&(seam_of_end(half, true), band)];
2193            let left = seam_arc[&(seam_of_end(half, false), band)];
2194            let coedges = vec![
2195                (lower_edge, true, branch_pcurve(lo_branch, 0.0)?),
2196                (right, true, inverse_pcurve(&curves[right].curve)?),
2197                (upper_edge, false, frag(branch_pcurve(hi_branch, hi_turn)?.reversed(), "reversed")?),
2198                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2199            ];
2200            let mid = &samples[half][n / 2];
2201            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2202            caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre: [rho_c, z_c], start: v_low, sweep: theta_v, spans: spans_v } }) });
2203        }
2204    }
2205    Ok(Split {
2206        points,
2207        curves,
2208        caps,
2209        slides: Vec::new(),
2210        slide_sides: Vec::new(),
2211        scale: rho_c + radius,
2212        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2213    })
2214}
2215
2216/// Builder of a closed shell with shared vertices and edges.
2217struct Shell {
2218    vertices: Vec<VertexRecord>,
2219    edges: Vec<EdgeRecord>,
2220    faces: Vec<FaceRecord>,
2221    next: u64,
2222    /// Loops beyond each face's first (holes).
2223    holes: usize,
2224}
2225
2226impl Shell {
2227    fn new() -> Self {
2228        Self { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 1, holes: 0 }
2229    }
2230
2231    fn id(&mut self) -> u64 {
2232        self.next += 1;
2233        self.next
2234    }
2235
2236    fn vertex(&mut self, point: Vec3) -> u64 {
2237        let id = self.id();
2238        self.vertices.push(VertexRecord { id, point });
2239        id
2240    }
2241
2242    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64, degenerate: bool) -> Result<u64, KernelRefusal> {
2243        let domain = frag(curve.domain(), "edge_domain")?;
2244        let id = self.id();
2245        self.edges.push(EdgeRecord { id, curve, t0: domain[0], t1: domain[1], start_vertex_id: start, end_vertex_id: end, degenerate, name: None });
2246        Ok(id)
2247    }
2248
2249    /// A face from its surface and its loop: (edge, traversed forward?, pcurve
2250    /// in the traversal direction).
2251    fn face(&mut self, surface: NurbsSurface, coedges: Vec<(u64, bool, NurbsCurve)>) -> u64 {
2252        let mut records = Vec::with_capacity(coedges.len());
2253        for (edge, forward, pcurve) in coedges {
2254            let id = self.id();
2255            records.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2256        }
2257        let loop_id = self.id();
2258        let id = self.id();
2259        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: vec![LoopRecord { id: loop_id, coedges: records }], name: None });
2260        id
2261    }
2262
2263    /// A face from its surface and its loops, the outer one first.
2264    fn face_loops(&mut self, surface: NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) -> u64 {
2265        let mut records = Vec::with_capacity(loops.len());
2266        for coedges in loops {
2267            let mut list = Vec::with_capacity(coedges.len());
2268            for (edge, forward, pcurve) in coedges {
2269                let id = self.id();
2270                list.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2271            }
2272            let id = self.id();
2273            records.push(LoopRecord { id, coedges: list });
2274        }
2275        self.holes += records.len().saturating_sub(1);
2276        let id = self.id();
2277        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: records, name: None });
2278        id
2279    }
2280
2281    fn solid(mut self) -> BrepSolid {
2282        let shell = self.id();
2283        let id = self.id();
2284        // One shell: V − E + F = 2 − 2g (every face one loop; a pole's
2285        // degenerate edge is not counted, as the validator counts).
2286        let edges = self.edges.iter().filter(|e| !e.degenerate).count() as i64;
2287        // A face with holes counts once for each loop beyond its first less.
2288        let euler = self.vertices.len() as i64 - edges + self.faces.len() as i64 - self.holes as i64;
2289        let genus = (2 - euler) / 2;
2290        BrepSolid {
2291            mass_properties_cache: Default::default(),
2292            id,
2293            vertices: self.vertices,
2294            edges: self.edges,
2295            shells: vec![ShellRecord { id: shell, faces: self.faces }],
2296            genus,
2297            kind: Default::default(),
2298            cells: Default::default(),
2299        }
2300    }
2301}
2302
2303/// The whole sweep of `tool` along `motion` (a single screw, turn or slide),
2304/// its two end positions included.
2305pub fn sweep_solid(tool: &SolidTool, motion: &SolidMotion) -> Result<BrepSolid, KernelRefusal> {
2306    let screw = Screw::from_motion(motion)?;
2307    let refusal = match sweep_with(&screw, tool) {
2308        Err(refusal) => refusal,
2309        body => return body,
2310    };
2311    // A rescue where the general route refuses: a cone turned about a line
2312    // crossing its axis inside it (`BREP_SWEEP_CONE_ACROSS`).
2313    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool {
2314        if cone_across::cone_across_on() {
2315            if let Ok(Some(body)) = cone_across::cone_across_axis(&screw, *axis_origin, *axis_direction, meridian) {
2316                return Ok(body);
2317            }
2318        }
2319    }
2320    Err(refusal)
2321}
2322
2323fn sweep_with(screw: &Screw, tool: &SolidTool) -> Result<BrepSolid, KernelRefusal> {
2324    let screw = *screw;
2325    if let SolidTool::Revolved { meridian, .. } = tool {
2326        refuse_elliptic(meridian)?;
2327    }
2328    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, radial } = tool {
2329        if let Some(body) = ball_across_axis(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2330            return Ok(body);
2331        }
2332        // (A tool whose radial direction lies along its axis is left to the
2333        // refusal below.)
2334        let radial_holds = match (tool, axis_direction.normalized()) {
2335            (SolidTool::Revolved { radial, .. }, Ok(w)) => radial.sub(w.scale(radial.dot(w))).normalized().is_ok(),
2336            _ => false,
2337        };
2338        if radial_holds && ball_screw::ball_screw_on() {
2339            if let Some(body) = ball_screw::ball_screwed_past_fold(&screw, *axis_origin, *axis_direction, meridian)? {
2340                return Ok(body);
2341            }
2342        }
2343    }
2344    if let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool {
2345        if ring_fold::ring_fold_on() {
2346            if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() {
2347                if ((end - start).abs() - TAU).abs() < 1e-12 {
2348                    let w = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
2349                    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
2350                    if let Some(body) = ring_fold::ring_slid_past_fold(&screw, *axis_origin, w, u1, w.cross(u1), *centre, *radius)? {
2351                        return Ok(body);
2352                    }
2353                }
2354            }
2355        }
2356        if let Some(body) = flat_ring(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2357            return Ok(body);
2358        }
2359        if let Some(body) = rod_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2360            return Ok(body);
2361        }
2362    }
2363    if let SolidTool::Polyhedron { vertices, faces } = tool {
2364        let slid = screw.omega == 0.0 && screw.c2 == 0.0 && screw.frame.is_none() && screw.turns.is_none();
2365        if slid && slid_hull_on() {
2366            return slid_polyhedron_hull(&screw, vertices, faces);
2367        }
2368    }
2369    if let SolidTool::Polyhedron { vertices, faces } = tool {
2370        let whole = screw.omega != 0.0 && screw.c == 0.0 && screw.c2 == 0.0 && screw.frame.is_none() && screw.turns.is_none() && screw.omega.abs() * (screw.t1 - screw.t0) >= TAU * (1.0 - 1e-12);
2371        if whole {
2372            return whole_turn_shadow(&screw, vertices, faces);
2373        }
2374    }
2375    let split = match tool {
2376        SolidTool::Polyhedron { vertices, faces } => split_polyhedron(&screw, vertices, faces)?,
2377        SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } => {
2378            split_revolved(&screw, *axis_origin, *axis_direction, *radial, meridian)?
2379        }
2380    };
2381    let grazing = split.grazing()?;
2382    // A tool slid along its own axis has no grazing curve: its sliding sides
2383    // join its back at the start to its front at the end.
2384    if grazing.is_empty() && split.slide_sides.is_empty() {
2385        return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
2386    }
2387    let times = row_times(&screw);
2388    let last = times.len() - 1;
2389    let mut shell = Shell::new();
2390    // Vertices and edges at the row times (0 and `last` are the end positions),
2391    // made on demand.
2392    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
2393    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
2394    let mut at_time = |shell: &mut Shell, j: usize, p: usize| -> u64 {
2395        *vertex_at.entry((j, p)).or_insert_with(|| shell.vertex(screw.apply(times[j], split.points[p])))
2396    };
2397    let mut time_edge = |shell: &mut Shell, j: usize, c: usize, vertex: &mut dyn FnMut(&mut Shell, usize, usize) -> u64| -> Result<u64, KernelRefusal> {
2398        if let Some(&edge) = edge_at.get(&(j, c)) {
2399            return Ok(edge);
2400        }
2401        let curve = &split.curves[c];
2402        let (a, b) = (vertex(shell, j, curve.start), vertex(shell, j, curve.end));
2403        let edge = shell.edge(screw.move_curve(times[j], &curve.curve)?, a, b, curve.degenerate)?;
2404        edge_at.insert((j, c), edge);
2405        Ok(edge)
2406    };
2407    // Caps: the back at t0, the front at t1.
2408    for cap in &split.caps {
2409        let j = if cap.front { last } else { 0 };
2410        let surface = screw.move_surface(times[j], &cap.surface)?;
2411        let mut coedges = Vec::with_capacity(cap.coedges.len());
2412        for (c, forward, pcurve) in &cap.coedges {
2413            let edge = time_edge(&mut shell, j, *c, &mut at_time)?;
2414            coedges.push((edge, *forward, pcurve.clone()));
2415        }
2416        shell.face(surface, coedges);
2417    }
2418    // Walls, a row at a time. The back cap at t0 runs K's curve with the back
2419    // on its left, so the wall beside it runs the other way: u along the curve
2420    // that way, v from the row's start to its end, the loop (u0,0) (u1,0)
2421    // (u1,1) (u0,1).
2422    // The paths of K's corners, a row at a time: (row, point) -> edge.
2423    let mut orbit_at: HashMap<(usize, usize), u64> = HashMap::new();
2424    for row in 0..last {
2425        let (ta, tb) = (times[row], times[row + 1]);
2426        let segments = carry_segments(&screw, ta, tb);
2427        let knots_v = carry_knots(segments);
2428        let mut orbits: HashMap<usize, u64> = HashMap::new();
2429        for &(c, _) in &grazing {
2430            for r in [split.curves[c].start, split.curves[c].end] {
2431                if orbits.contains_key(&r) {
2432                    continue;
2433                }
2434                let (v0, v1) = (at_time(&mut shell, row, r), at_time(&mut shell, row + 1, r));
2435                let edge = shell.edge(carry_curve(&screw, split.points[r], ta, tb, segments)?, v0, v1, false)?;
2436                orbits.insert(r, edge);
2437                orbit_at.insert((row, r), edge);
2438            }
2439        }
2440        for &(c, back_forward) in &grazing {
2441            let tool_curve = &split.curves[c];
2442            let along = if back_forward { frag(tool_curve.curve.reversed(), "reversed")? } else { tool_curve.curve.clone() };
2443            let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
2444            let mut rows = Vec::with_capacity(along.control_points.len());
2445            for p in &along.control_points {
2446                let x = frag(p.point(), "control_point")?;
2447                rows.push(carry_points(&screw, x, ta, tb, segments).into_iter().map(|q| Vec4::from_point(q, p.w)).collect::<Vec<_>>());
2448            }
2449            let surface = frag(NurbsSurface::new(along.degree, 5, along.knots.clone(), knots_v.clone(), rows), "wall")?;
2450            let [u0, u1] = frag(along.domain(), "domain")?;
2451            let bottom = time_edge(&mut shell, row, c, &mut at_time)?;
2452            let top = time_edge(&mut shell, row + 1, c, &mut at_time)?;
2453            let coedges = vec![
2454                (bottom, !back_forward, uv_line([u0, 0.0], [u1, 0.0])?),
2455                (orbits[&to], true, uv_line([u1, 0.0], [u1, 1.0])?),
2456                (top, back_forward, uv_line([u1, 1.0], [u0, 1.0])?),
2457                (orbits[&from], false, uv_line([u0, 1.0], [u0, 0.0])?),
2458            ];
2459            shell.face(surface, coedges);
2460        }
2461    }
2462    // Sliding ends: each rim arc where its neighbour's cap sits (back at t0,
2463    // front at t1), joined by the paths of the points where that changes.
2464    // Faces the tool slides within: the one-pass probe stands further off them.
2465    let mut sliding: std::collections::HashSet<u64> = std::collections::HashSet::new();
2466    let side_of: HashMap<usize, bool> = split.caps.iter().flat_map(|cap| cap.coedges.iter().map(move |&(c, _, _)| (c, cap.front))).collect();
2467    for slide in &split.slides {
2468        let centre = screw.apply(times[0], slide.centre);
2469        let u = screw.apply(times[0], slide.centre.add(slide.u)).sub(centre);
2470        let v = screw.apply(times[0], slide.centre.add(slide.v)).sub(centre);
2471        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2472            match side_of.get(&c) {
2473                Some(true) => Ok(last),
2474                Some(false) => Ok(0),
2475                None => Err(refuse("revolved_grazing", "a sliding end has no face beside its rim".into())),
2476            }
2477        };
2478        let mut coedges = Vec::new();
2479        let mut corners: Vec<Vec3> = Vec::new();
2480        let push = |coedges: &mut Vec<(u64, bool, NurbsCurve)>, corners: &mut Vec<Vec3>, edge: u64, forward: bool, curve: &NurbsCurve| -> Result<(), KernelRefusal> {
2481            let [d0, d1] = frag(curve.domain(), "domain")?;
2482            for k in 0..=8 {
2483                corners.push(frag(curve.evaluate(d0 + (d1 - d0) * k as f64 / 8.0), "slide")?);
2484            }
2485            coedges.push((edge, forward, plane_pcurve(centre, u, v, curve, forward)?));
2486            Ok(())
2487        };
2488        for (index, &(c, forward)) in slide.rim.iter().enumerate() {
2489            let j = row_of(c)?;
2490            let edge = time_edge(&mut shell, j, c, &mut at_time)?;
2491            push(&mut coedges, &mut corners, edge, forward, &screw.move_curve(times[j], &split.curves[c].curve)?)?;
2492            // On to the next arc's time along the path of the point between them.
2493            let (next, _) = slide.rim[(index + 1) % slide.rim.len()];
2494            let next_j = row_of(next)?;
2495            if next_j == j {
2496                continue;
2497            }
2498            let point = if forward { split.curves[c].end } else { split.curves[c].start };
2499            let rows: Vec<usize> = if next_j > j { (j..next_j).collect() } else { (next_j..j).rev().collect() };
2500            for row in rows {
2501                let Some(&orbit) = orbit_at.get(&(row, point)) else {
2502                    return Err(refuse("revolved_grazing", "a sliding end's rim changes side where no grazing curve meets it".into()));
2503                };
2504                let (ta, tb) = (times[row], times[row + 1]);
2505                let curve = carry_curve(&screw, split.points[point], ta, tb, carry_segments(&screw, ta, tb))?;
2506                push(&mut coedges, &mut corners, orbit, next_j > j, &curve)?;
2507            }
2508        }
2509        sliding.insert(shell.face(plane_patch(centre, u, v, &corners)?, coedges));
2510    }
2511    // Sliding cylinders: from the start rim where its neighbour sits to the
2512    // end rim where its neighbour sits, in halves seamed along generators.
2513    for side in &split.slide_sides {
2514        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2515            match side_of.get(&c) {
2516                Some(true) => Ok(last),
2517                Some(false) => Ok(0),
2518                None => Err(refuse("revolved_grazing", "a sliding side has no face beside its rim".into())),
2519            }
2520        };
2521        let origin = screw.apply(times[0], side.origin);
2522        let w = screw.apply(times[0], side.origin.add(side.w)).sub(origin);
2523        let rows: Vec<[usize; 2]> = side.patches.iter().map(|patch| Ok([row_of(patch.2)?, row_of(patch.3)?])).collect::<Result<_, KernelRefusal>>()?;
2524        if rows.iter().any(|r| *r != rows[0]) {
2525            return Err(refuse("revolved_grazing", "a sliding side's rim changes side along it".into()));
2526        }
2527        let [jb, ja] = rows[0];
2528        // Seams: the generator at each patch's start angle, rim point to rim point.
2529        let mut seams = Vec::with_capacity(side.patches.len());
2530        for patch in &side.patches {
2531            let (a, b) = (at_time(&mut shell, jb, patch.4[0]), at_time(&mut shell, ja, patch.4[1]));
2532            let line = frag(make_line(screw.apply(times[jb], split.points[patch.4[0]]), screw.apply(times[ja], split.points[patch.4[1]])), "seam")?;
2533            seams.push((shell.edge(line.clone(), a, b, false)?, line));
2534        }
2535        for (k, patch) in side.patches.iter().enumerate() {
2536            let surface = frag(make_revolution(origin, w, &seams[k].1, patch.1), "slide_side")?;
2537            let lower = time_edge(&mut shell, jb, patch.2, &mut at_time)?;
2538            let upper = time_edge(&mut shell, ja, patch.3, &mut at_time)?;
2539            let next = (k + 1) % side.patches.len();
2540            let face = shell.face(
2541                surface,
2542                vec![
2543                    (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
2544                    (seams[next].0, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
2545                    (upper, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
2546                    (seams[k].0, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
2547                ],
2548            );
2549            sliding.insert(face);
2550        }
2551    }
2552    let body = shell.solid();
2553    let issues = body.validate();
2554    if !issues.is_empty() {
2555        return Err(refuse("assembly", format!("the assembled sweep is not valid: {:?}", issues.first())));
2556    }
2557    // A ball under one screw is proved one pass from its centre's helix
2558    // (`BREP_SWEEP_BALL_ONE_PASS`, default on): nothing for the walk to find.
2559    if !crate::solid_sweep_one_pass::ball_screw_one_pass(&screw, tool) {
2560        check_single_pass(&screw, &split, &body, &sliding)?;
2561    }
2562    Ok(body)
2563}
2564
2565/// A rod (a cylinder with flat ends) TURNED about a line that crosses its
2566/// axis squarely between its ends, if `meridian` is one and the motion such.
2567///
2568/// Arm by arm: the rod is its arm one way from the turn's axis and its arm
2569/// the other way, and sweeps what they sweep. At a height z (half-width
2570/// w = √(r² − z²)) an arm of length L is the rectangle 0 ≤ x ≤ L, |y| ≤ w,
2571/// which a circle about the turn's axis of radius ρ ≤ L meets in one arc
2572/// holding the arm's own direction, and beyond, out to √(L² + w²), in two
2573/// arcs ±[a, b] with a ≤ acos(L / √(L² + r²)). Turned by more than 2a, the
2574/// two arcs sweep the same angles as the arc [−b, b] they leave a gap in:
2575/// the arm with the gap filled, its points beyond its end within
2576/// √(L² + r²) of the crossing point (a cap of that ball). The filled arm
2577/// meets every circle in one arc holding its direction, so it sweeps itself
2578/// where it starts and where it stops and, between, its section by the half
2579/// plane at its direction turned. So the sweep is the union of the filled rod
2580/// (one solid of revolution about the rod's axis) at both ends of the turn
2581/// and the two arms' sections turned.
2582fn rod_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2583    if screw.frame.is_some() || screw.turns.is_some() || screw.omega == 0.0 || screw.c != 0.0 || screw.c2 != 0.0 {
2584        return Ok(None);
2585    }
2586    let Ok(w) = axis.normalized() else { return Ok(None) };
2587    // A rectangle against the axis: radius r from z0 to z1.
2588    let mut corners: Vec<[f64; 2]> = Vec::new();
2589    for piece in meridian {
2590        let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2591        corners.push(*from);
2592        corners.push(*to);
2593    }
2594    if meridian.len() != 4 {
2595        return Ok(None);
2596    }
2597    let r = corners.iter().map(|c| c[0]).fold(0.0f64, f64::max);
2598    let (z0, z1) = corners.iter().map(|c| c[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
2599    let scale = r.max(z0.abs()).max(z1.abs());
2600    let on = |a: f64, b: f64| (a - b).abs() <= 1e-12 * scale;
2601    if !(r > 0.0 && z1 > z0) || !corners.iter().all(|c| (on(c[0], 0.0) || on(c[0], r)) && (on(c[1], z0) || on(c[1], z1))) {
2602        return Ok(None);
2603    }
2604    // The turn's axis squarely across the rod's, between its ends.
2605    if w.dot(screw.e).abs() > 1e-12 {
2606        return Ok(None);
2607    }
2608    let offset = screw.a.sub(origin);
2609    let along = offset.dot(w);
2610    let foot = origin.add(w.scale(along));
2611    let apart = screw.a.sub(foot);
2612    if apart.sub(screw.e.scale(apart.dot(screw.e))).length() > 1e-12 * (scale + offset.length()) {
2613        return Ok(None);
2614    }
2615    if !(along > z0 + 1e-9 * scale && along < z1 - 1e-9 * scale) {
2616        return Ok(None);
2617    }
2618    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2619    let arms = [z1 - along, along - z0];
2620    let gap = arms.iter().map(|l| (l / l.hypot(r)).acos()).fold(0.0f64, f64::max);
2621    if !(theta > 2.0 * gap * (1.0 + 1e-9) && theta < TAU * (1.0 - 1e-9)) {
2622        return Err(refuse("rod_across", "a rod turned about a line through it is swept only for a turn wider than its ends' gaps and short of a whole turn".into()));
2623    }
2624    let arc = |centre: Vec3, from: Vec3, normal: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
2625        let surface = frag(make_revolution(centre, normal, &frag(make_line(from, from.add(normal)), "line")?, angle), "rod_across")?;
2626        frag(surface.iso_curve_v(0.0), "rod_across")
2627    };
2628    let line = |a: Vec3, b: Vec3| frag(make_line(a, b), "rod_across");
2629    // At one time: the crossing point, the rod's direction and the turn's.
2630    let filled_at = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2631        let o = screw.apply(t, foot);
2632        let x = screw.apply(t, foot.add(w)).sub(o);
2633        let up = screw.e;
2634        let at = |rho: f64, s: f64| o.add(up.scale(rho)).add(x.scale(s));
2635        let n = up.cross(x);
2636        let (far_plus, far_minus) = (arms[0].hypot(r), arms[1].hypot(r));
2637        let profile = [
2638            arc(o, at(0.0, -far_minus), n, r.atan2(arms[1]))?,
2639            line(at(r, -arms[1]), at(r, arms[0]))?,
2640            arc(o, at(r, arms[0]), n, r.atan2(arms[0]))?,
2641            line(at(0.0, far_plus), at(0.0, -far_minus))?,
2642        ];
2643        frag(crate::revolve_profile_brep(&profile, o, x, TAU), "rod_across")
2644    };
2645    let o = screw.apply(screw.t0, foot);
2646    let x = screw.apply(screw.t0, foot.add(w)).sub(o);
2647    let turn_axis = screw.e.scale(screw.omega.signum());
2648    let section = |direction: Vec3, length: f64| -> Result<BrepSolid, KernelRefusal> {
2649        let at = |rho: f64, z: f64| o.add(direction.scale(rho)).add(screw.e.scale(z));
2650        let half = (r / length.hypot(r)).asin();
2651        let profile = [
2652            line(at(0.0, -r), at(length, -r))?,
2653            arc(o, at(length, -r), direction.cross(screw.e), 2.0 * half)?,
2654            line(at(length, r), at(0.0, r))?,
2655            line(at(0.0, r), at(0.0, -r))?,
2656        ];
2657        frag(crate::revolve_profile_brep(&profile, o, turn_axis, theta), "rod_across")
2658    };
2659    let parts = [filled_at(screw.t0)?, filled_at(screw.t1)?, section(x, arms[0])?, section(x.scale(-1.0), arms[1])?];
2660    crate::boolean_operation_nary(&parts, crate::BooleanOperation::Union).map(Some)
2661}
2662
2663/// `BREP_SWEEP_RING_LENS_SEWN` (on by default; `=0` restores the booleans): a
2664/// ring slid flat short of its
2665/// hole's width is the filled ring's sweep less the lens its hole leaves open
2666/// at both ends. That lens is built here and sewn into the sweep's top and
2667/// bottom faces in place of the two booleans (the lens intersect and the
2668/// subtract): its caps are the two holes' top and bottom discs in common,
2669/// whose outlines become inner loops of the sweep's flat faces, and its walls
2670/// are the two holes' own tube surfaces, meeting in the slide's bisector
2671/// plane along `y(ψ) = √(ρ(ψ)² − D²/4)`, `ρ = R − r cos ψ`, `z = r sin ψ`
2672/// (the tube's section by that plane, interpolated through exact points and
2673/// read back against them). A lens that pinches at the tube's middle (`D ≥
2674/// 2 (R − r)`) or anything that does not validate is left to the booleans.
2675pub(crate) fn ring_lens_sewn_on() -> bool {
2676    crate::switch!("BREP_SWEEP_RING_LENS_SEWN", true)
2677}
2678
2679/// `BREP_SWEEP_RING_LENS_SEWN_CHECK` (default off): both built, the booleans'
2680/// body kept; the sewn one's volume and area compared with it
2681/// ([`ring_lens_check_take`]).
2682fn ring_lens_sewn_check_on() -> bool {
2683    crate::switch!("BREP_SWEEP_RING_LENS_SEWN_CHECK", false)
2684}
2685
2686thread_local! {
2687    static RING_LENS_CHECK: std::cell::Cell<(u64, u64, f64)> = const { std::cell::Cell::new((0, 0, 0.0)) };
2688}
2689
2690/// (bodies compared, sewn bodies missing or differing past `1e-7` relative
2691/// in volume or area, the worst relative difference) on this thread since the
2692/// last call. The bar is the booleans' own error, the bench's tier: the sewn
2693/// body reads the closed form to `1e-10` where the booleans' body reads it
2694/// `2.9e-9` off (tube 2 round 6, slid 6) and `3.8e-8` off (tube 1 round 5,
2695/// slid 3).
2696pub fn ring_lens_check_take() -> (u64, u64, f64) {
2697    RING_LENS_CHECK.with(|cell| cell.replace((0, 0, 0.0)))
2698}
2699
2700fn ring_lens_check_record(cut: &BrepSolid, sewn: Option<&BrepSolid>) {
2701    let worst = match (crate::solid_mass_properties(cut), sewn.map(crate::solid_mass_properties)) {
2702        (Ok(a), Some(Ok(b))) => ((a.volume - b.volume) / a.volume).abs().max(((a.surface_area - b.surface_area) / a.surface_area).abs()),
2703        _ => f64::INFINITY,
2704    };
2705    RING_LENS_CHECK.with(|cell| {
2706        let (n, bad, w) = cell.get();
2707        cell.set((n + 1, bad + u64::from(!(worst <= 1e-7)), w.max(worst)));
2708    });
2709}
2710
2711/// The filled ring's sweep `whole` (a slide of the ring's centre from `c0` to
2712/// `c1`, square to its axis `w`, its tube `tube` round the circle of radius
2713/// `big`) less the lens both holes share, built directly. `None` where it
2714/// does not apply or does not validate.
2715fn sewn_lens(whole: &BrepSolid, c0: Vec3, c1: Vec3, w: Vec3, big: f64, tube: f64) -> Option<BrepSolid> {
2716    let slide = c1.sub(c0);
2717    let d = slide.length();
2718    let scale = (big + tube + d).max(1e-300);
2719    if !(slide.dot(w).abs() <= 1e-12 * scale && d > 1e-9 * scale && d < 2.0 * (big - tube) * (1.0 - 1e-9)) {
2720        return None;
2721    }
2722    let ed = slide.scale(1.0 / d);
2723    let ey = w.cross(ed);
2724    let mid = c0.add(ed.scale(0.5 * d));
2725    let half = 0.5 * d;
2726    let alpha = (half / big).acos();
2727    let y_top = (big * big - half * half).sqrt();
2728    let corner = |side: f64, z: f64| mid.add(ey.scale(side * y_top)).add(w.scale(z));
2729    let (t_plus, t_minus, b_plus, b_minus) = (corner(1.0, tube), corner(-1.0, tube), corner(1.0, -tube), corner(-1.0, -tube));
2730    // The flat faces the caps sit in.
2731    let shell = whole.shells.first()?;
2732    let flat_at = |z: f64| -> Option<usize> {
2733        shell.faces.iter().position(|f| {
2734            f.loops.len() == 1
2735                && f.surface.degree_u == 1
2736                && f.surface.degree_v == 1
2737                && f.surface.control_points.iter().flatten().all(|c| c.point().map(|p| (p.sub(c0).dot(w) - z).abs() <= 1e-12 * scale).unwrap_or(false))
2738        })
2739    };
2740    let (top, bottom) = (flat_at(tube)?, flat_at(-tube)?);
2741    // Edges. Arcs: A on the circle about c0 (the lens's side away from c0's
2742    // far rim: angles −α..α from ed), B about c1 (π−α..π+α).
2743    let arc = |centre: Vec3, from: f64, to: f64| crate::make_arc(centre, ed, ey, big, from, to).ok();
2744    let a_top = arc(c0.add(w.scale(tube)), -alpha, alpha)?; // t_minus -> t_plus
2745    let b_top = arc(c1.add(w.scale(tube)), PI - alpha, PI + alpha)?; // t_plus -> t_minus
2746    let a_bot = arc(c0.add(w.scale(-tube)), -alpha, alpha)?; // b_minus -> b_plus
2747    let b_bot = arc(c1.add(w.scale(-tube)), PI - alpha, PI + alpha)?; // b_plus -> b_minus
2748    // The walls' carriers: each hole's inner tube half turned a whole turn
2749    // about its axis, its generatrix drawn opposite the lens (the turn's seam
2750    // away from the wall).
2751    let wall_surface = |centre: Vec3, away: Vec3| -> Option<NurbsSurface> {
2752        let n = w.cross(away);
2753        let at = |rho: f64, z: f64| centre.add(away.scale(rho)).add(w.scale(z));
2754        let from = at(big, -tube);
2755        let half_round = crate::make_revolution(at(big, 0.0), n, &crate::make_line(from, from.add(n)).ok()?, PI).ok()?.iso_curve_v(0.0).ok()?;
2756        crate::make_revolution(centre, w, &half_round, TAU).ok()
2757    };
2758    let (wall_a, wall_b) = (wall_surface(c0, ed.scale(-1.0))?, wall_surface(c1, ed)?);
2759    // Seams, bottom to top, through exact points of the bisector section, with
2760    // their pcurves on both walls interpolated through the same points' feet
2761    // at the same parameters; all three read back at the mid-samples.
2762    // (Each seam in two halves, split at the tube's waist ψ = 0: the walls'
2763    // half-round generatrix is two quarter arcs, its parameter speed jumps
2764    // there, and a pcurve through it would kink.)
2765    let seam = |side: f64, from: f64, to: f64| -> Option<(NurbsCurve, NurbsCurve, NurbsCurve)> {
2766        let at = |psi: f64| {
2767            let rho = big - tube * psi.cos();
2768            mid.add(ey.scale(side * (rho * rho - half * half).max(0.0).sqrt())).add(w.scale(tube * psi.sin()))
2769        };
2770        let feet = |surface: &NurbsSurface, points: &[Vec3]| -> Option<Vec<Vec3>> {
2771            let mut out: Vec<Vec3> = Vec::with_capacity(points.len());
2772            for point in points {
2773                // From the last foot; where that lands off the point (the tube
2774                // turning fast near its top and bottom), the global reading.
2775                let seeded = out.last().and_then(|last| crate::project_point_to_surface_seeded(surface, *point, last.x, last.y).ok());
2776                let q = match seeded {
2777                    Some(q) if q.distance <= 1e-7 * scale => q,
2778                    _ => crate::project_point_to_surface(surface, *point).ok()?,
2779                };
2780                // The projector stops near 1e-9; the point is on the carrier
2781                // exactly, so Gauss-Newton on |S(u, v) − p|² takes the foot to
2782                // rounding.
2783                let (mut u, mut v) = (q.u, q.v);
2784                for _ in 0..4 {
2785                    let d = surface.derivatives(u, v, 1).ok()?;
2786                    let (f, su, sv) = (d[0][0].sub(*point), d[1][0], d[0][1]);
2787                    let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv));
2788                    let (g0, g1) = (su.dot(f), sv.dot(f));
2789                    let det = a * c - b * b;
2790                    if !(det > 0.0) {
2791                        return None;
2792                    }
2793                    u -= (c * g0 - b * g1) / det;
2794                    v -= (a * g1 - b * g0) / det;
2795                }
2796                if !(surface.evaluate(u, v).ok()?.sub(*point).length() <= 1e-11 * scale) {
2797                    return None;
2798                }
2799                out.push(Vec3::new(u, v, 0.0));
2800            }
2801            Some(out)
2802        };
2803        let mut n = 16usize;
2804        loop {
2805            let psis: Vec<f64> = (0..=n).map(|k| from + (to - from) * k as f64 / n as f64).collect();
2806            let points: Vec<Vec3> = psis.iter().map(|&psi| at(psi)).collect();
2807            let params: Vec<f64> = psis.iter().map(|psi| (psi - from) / (to - from)).collect();
2808            let curve = crate::interpolate_curve(&points, 3, &params).ok()?;
2809            let on_a = crate::interpolate_curve(&feet(&wall_a, &points)?, 3, &params).ok()?;
2810            let on_b = crate::interpolate_curve(&feet(&wall_b, &points)?, 3, &params).ok()?;
2811            let mut worst = 0.0f64;
2812            for k in 0..n {
2813                let psi = 0.5 * (psis[k] + psis[k + 1]);
2814                let t = (psi - from) / (to - from);
2815                let p = curve.evaluate(t).ok()?;
2816                worst = worst.max(p.sub(at(psi)).length());
2817                for (surface, pcurve) in [(&wall_a, &on_a), (&wall_b, &on_b)] {
2818                    let uv = pcurve.evaluate(t).ok()?;
2819                    worst = worst.max(surface.evaluate(uv.x, uv.y).ok()?.sub(p).length());
2820                }
2821            }
2822            if worst <= 1e-10 * scale {
2823                return Some((curve, on_a, on_b));
2824            }
2825            if n >= 4096 {
2826                return None;
2827            }
2828            n *= 2;
2829        }
2830    };
2831    let (lower_plus, upper_plus) = (seam(1.0, -0.5 * PI, 0.0)?, seam(1.0, 0.0, 0.5 * PI)?);
2832    let (lower_minus, upper_minus) = (seam(-1.0, -0.5 * PI, 0.0)?, seam(-1.0, 0.0, 0.5 * PI)?);
2833    let waist = |side: f64| mid.add(ey.scale(side * ((big - tube).powi(2) - half * half).sqrt()));
2834    let (m_plus, m_minus) = (waist(1.0), waist(-1.0));
2835    // Ids past every existing one.
2836    let mut next = whole.vertices.iter().map(|v| v.id).chain(whole.edges.iter().map(|e| e.id)).chain(shell.faces.iter().flat_map(|f| std::iter::once(f.id).chain(f.loops.iter().flat_map(|l| std::iter::once(l.id).chain(l.coedges.iter().map(|c| c.id)))))).max().unwrap_or(0) + 1;
2837    let mut id = || {
2838        next += 1;
2839        next
2840    };
2841    let mut body = whole.clone();
2842    let vertex = |body: &mut BrepSolid, id: u64, point: Vec3| body.vertices.push(VertexRecord { id, point });
2843    let (vt_plus, vt_minus, vb_plus, vb_minus, vm_plus, vm_minus) = (id(), id(), id(), id(), id(), id());
2844    vertex(&mut body, vm_plus, m_plus);
2845    vertex(&mut body, vm_minus, m_minus);
2846    vertex(&mut body, vt_plus, t_plus);
2847    vertex(&mut body, vt_minus, t_minus);
2848    vertex(&mut body, vb_plus, b_plus);
2849    vertex(&mut body, vb_minus, b_minus);
2850    let mut edge = |body: &mut BrepSolid, curve: NurbsCurve, start: u64, end: u64| -> Option<u64> {
2851        let [t0, t1] = curve.domain().ok()?;
2852        let e = id();
2853        body.edges.push(EdgeRecord { id: e, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
2854        Some(e)
2855    };
2856    // The arcs' ends must be the corners they are named for.
2857    for (curve, a, b) in [(&a_top, t_minus, t_plus), (&b_top, t_plus, t_minus), (&a_bot, b_minus, b_plus), (&b_bot, b_plus, b_minus), (&lower_plus.0, b_plus, m_plus), (&upper_plus.0, m_plus, t_plus), (&lower_minus.0, b_minus, m_minus), (&upper_minus.0, m_minus, t_minus)] {
2858        let [t0, t1] = curve.domain().ok()?;
2859        if curve.evaluate(t0).ok()?.sub(a).length() > 1e-9 * scale || curve.evaluate(t1).ok()?.sub(b).length() > 1e-9 * scale {
2860            return None;
2861        }
2862    }
2863    // The seams' pcurves, built with them: (edge, wall, pcurve along the edge).
2864    let mut given: Vec<(u64, usize, NurbsCurve)> = Vec::new();
2865    let e_a_top = edge(&mut body, a_top, vt_minus, vt_plus)?;
2866    let e_b_top = edge(&mut body, b_top, vt_plus, vt_minus)?;
2867    let e_a_bot = edge(&mut body, a_bot, vb_minus, vb_plus)?;
2868    let e_b_bot = edge(&mut body, b_bot, vb_plus, vb_minus)?;
2869    let mut seam_edge = |body: &mut BrepSolid, piece: (NurbsCurve, NurbsCurve, NurbsCurve), start: u64, end: u64, given: &mut Vec<(u64, usize, NurbsCurve)>| -> Option<u64> {
2870        let (curve, on_a, on_b) = piece;
2871        let e = edge(body, curve, start, end)?;
2872        given.extend([(e, 1, on_a), (e, 2, on_b)]);
2873        Some(e)
2874    };
2875    let e_lp = seam_edge(&mut body, lower_plus, vb_plus, vm_plus, &mut given)?;
2876    let e_up = seam_edge(&mut body, upper_plus, vm_plus, vt_plus, &mut given)?;
2877    let e_lm = seam_edge(&mut body, lower_minus, vb_minus, vm_minus, &mut given)?;
2878    let e_um = seam_edge(&mut body, upper_minus, vm_minus, vt_minus, &mut given)?;
2879    let curve_of = |body: &BrepSolid, e: u64| body.edges.iter().find(|x| x.id == e).map(|x| x.curve.clone());
2880    // A coedge of edge `e` on `surface`, forward or reversed, with its pcurve
2881    // fitted along the coedge.
2882    let coedge = |body: &BrepSolid, id: u64, surface: &NurbsSurface, e: u64, forward: bool, given: &[(u64, usize, NurbsCurve)], wall: usize| -> Option<CoedgeRecord> {
2883        if let Some((_, _, pcurve)) = given.iter().find(|(edge, on, _)| *edge == e && *on == wall) {
2884            let pcurve = if forward { pcurve.clone() } else { pcurve.reversed().ok()? };
2885            return Some(CoedgeRecord { id, edge_id: e, forward, pcurve });
2886        }
2887        let fit = crate::fit_pcurve_on_surface(surface, &curve_of(body, e)?).ok()?;
2888        if !(fit.report.residual <= 1e-7 * scale) {
2889            return None;
2890        }
2891        let pcurve = if forward { fit.curve } else { fit.curve.reversed().ok()? };
2892        Some(CoedgeRecord { id, edge_id: e, forward, pcurve })
2893    };
2894    // The loop's signed area in its face's parameters.
2895    let uv_area = |coedges: &[CoedgeRecord]| -> f64 {
2896        let mut area = 0.0;
2897        for c in coedges {
2898            let Ok([p0, p1]) = c.pcurve.domain() else { return f64::NAN };
2899            let samples = 64;
2900            let mut last = match c.pcurve.evaluate(p0) { Ok(p) => p, Err(_) => return f64::NAN };
2901            for k in 1..=samples {
2902                let Ok(p) = c.pcurve.evaluate(p0 + (p1 - p0) * k as f64 / samples as f64) else { return f64::NAN };
2903                area += last.x * p.y - p.x * last.y;
2904                last = p;
2905            }
2906        }
2907        0.5 * area
2908    };
2909    // Caps: the top's hole runs clockwise seen from outside (from +w), the
2910    // bottom's clockwise seen from −w.
2911    for (face_index, loop_edges) in [(top, [(e_a_top, false), (e_b_top, false)]), (bottom, [(e_a_bot, true), (e_b_bot, true)])] {
2912        let surface = body.shells[0].faces[face_index].surface.clone();
2913        let mut coedges = Vec::new();
2914        for (e, forward) in loop_edges {
2915            let c = id();
2916            coedges.push(coedge(&body, c, &surface, e, forward, &given, 0)?);
2917        }
2918        // An inner loop runs opposite its face's outer loop in the parameters.
2919        let outer = uv_area(&body.shells[0].faces[face_index].loops[0].coedges);
2920        let inner = uv_area(&coedges);
2921        if !(outer.is_finite() && inner.is_finite() && outer * inner < 0.0) {
2922            return None;
2923        }
2924        let loop_id = id();
2925        body.shells[0].faces[face_index].loops.push(LoopRecord { id: loop_id, coedges });
2926    }
2927    // Walls: A uses the arcs the caps reversed and B likewise, the seams once each way.
2928    for (wall, surface, centre, loop_edges) in [
2929        (1usize, wall_a, c0, vec![(e_a_top, true), (e_up, false), (e_lp, false), (e_a_bot, false), (e_lm, true), (e_um, true)]),
2930        (2usize, wall_b, c1, vec![(e_b_top, true), (e_um, false), (e_lm, false), (e_b_bot, false), (e_lp, true), (e_up, true)]),
2931    ] {
2932        let mut coedges = Vec::new();
2933        for (e, forward) in loop_edges {
2934            let c = id();
2935            coedges.push(coedge(&body, c, &surface, e, forward, &given, wall)?);
2936        }
2937        let area = uv_area(&coedges);
2938        if !(area.is_finite() && area != 0.0) {
2939            return None;
2940        }
2941        // Counter-clockwise in the parameters: the loop's outward is the
2942        // surface's normal side; it must face into the lens (towards the
2943        // hole's own axis).
2944        let same_sense = area > 0.0;
2945        let face_id = id();
2946        let loop_id = id();
2947        let face = FaceRecord { id: face_id, surface, same_sense, loops: vec![LoopRecord { id: loop_id, coedges }], name: None };
2948        // Sense check at the wall's middle: towards the hole's axis.
2949        let middle = mid.add(ed.scale(if centre.sub(c0).length() == 0.0 { big - tube - half } else { -(big - tube - half) }));
2950        let q = crate::project_point_to_surface(&face.surface, middle).ok()?;
2951        let n = face.surface.normal(q.u, q.v).ok()?;
2952        let n = if face.same_sense { n } else { n.scale(-1.0) };
2953        let toward_axis = centre.sub(middle);
2954        let toward_axis = toward_axis.sub(w.scale(toward_axis.dot(w)));
2955        if !(n.dot(toward_axis) > 0.0) {
2956            return None;
2957        }
2958        body.shells[0].faces.push(face);
2959    }
2960    // The lens runs through from the top face to the bottom: one handle more.
2961    body.genus = whole.genus + 1;
2962    body.mass_properties_cache = Default::default();
2963    if body.validate().iter().any(|issue| issue.severity == "error") {
2964        return None;
2965    }
2966    Some(body)
2967}
2968
2969/// A ring (or another tool with a hole about its axis walled straight
2970/// through) lying flat to its motion (a turn about an axis parallel to the
2971/// tool's, a slide square to it), if `meridian` is one and the motion such.
2972///
2973/// Every point then moves in its own plane square to the ring's axis, where
2974/// the ring's section is an annulus. The tube passes over where the hole was,
2975/// so the sweep does not pass each point once; but an annulus sweeps what its
2976/// filled disc sweeps as soon as it travels far enough that no point stays in
2977/// the hole from start to end (the hole at the start and at the end share
2978/// nothing: travel beyond the hole's greatest width, the tube's centre
2979/// circle). So the ring sweeps what the FILLED ring sweeps: a tool with a
2980/// half-round rim and flat faces, which is swept whole. A whole turn sweeps
2981/// the solid of revolution of that tool's shadow about the turn's axis.
2982fn flat_ring(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2983    if screw.frame.is_some() || screw.turns.is_some() || screw.c2 != 0.0 {
2984        return Ok(None);
2985    }
2986    let Ok(w) = axis.normalized() else { return Ok(None) };
2987    let flat = if screw.omega != 0.0 { screw.e.cross(w).length() <= 1e-12 && screw.c == 0.0 } else { screw.e.dot(w).abs() <= 1e-12 };
2988    if !flat {
2989        return Ok(None);
2990    }
2991    // The holed tool: a torus (`torus`: its tube), or straight-sided pieces
2992    // whose hole is one upright wall from the tool's top to its bottom.
2993    // `big`: half the hole's greatest width. `filled_meridian`: the tool
2994    // with its hole closed, flat across at its top and bottom.
2995    let (big, level, torus, filled_meridian): (f64, f64, Option<f64>, Vec<OutlinePiece>) = match meridian {
2996        [OutlinePiece::Arc { centre, radius, start, end }] => {
2997            let (big, tube, level) = (centre[0], *radius, centre[1]);
2998            if ((end - start).abs() - TAU).abs() >= 1e-12 || big <= tube {
2999                return Ok(None);
3000            }
3001            (
3002                big,
3003                level,
3004                Some(tube),
3005                vec![
3006                    OutlinePiece::Line { from: [0.0, level - tube], to: [big, level - tube] },
3007                    OutlinePiece::Arc { centre: [big, level], radius: tube, start: -0.5 * PI, end: 0.5 * PI },
3008                    OutlinePiece::Line { from: [big, level + tube], to: [0.0, level + tube] },
3009                    OutlinePiece::Line { from: [0.0, level + tube], to: [0.0, level - tube] },
3010                ],
3011            )
3012        }
3013        pieces => {
3014            let mut ends: Vec<([f64; 2], [f64; 2])> = Vec::with_capacity(pieces.len());
3015            for piece in pieces {
3016                let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
3017                ends.push((*from, *to));
3018            }
3019            let scale = ends.iter().flat_map(|(a, b)| [a[0].abs(), a[1].abs(), b[0].abs(), b[1].abs()]).fold(0.0f64, f64::max).max(1e-300);
3020            let inner = ends.iter().flat_map(|(a, b)| [a[0], b[0]]).fold(f64::INFINITY, f64::min);
3021            let (low, high) = ends.iter().flat_map(|(a, b)| [a[1], b[1]]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
3022            if ends.len() < 3 || inner <= 1e-9 * scale {
3023                return Ok(None);
3024            }
3025            let walls: Vec<usize> = (0..ends.len())
3026                .filter(|&k| {
3027                    let (a, b) = ends[k];
3028                    (a[0] - inner).abs() <= 1e-12 * scale && (b[0] - inner).abs() <= 1e-12 * scale && (a[1].min(b[1]) - low).abs() <= 1e-12 * scale && (a[1].max(b[1]) - high).abs() <= 1e-12 * scale
3029                })
3030                .collect();
3031            let [wall] = walls.as_slice() else { return Ok(None) };
3032            let (from, to) = ends[*wall];
3033            // From the wall's end round the outside back to its start, then
3034            // across to the axis and along it.
3035            let mut filled = vec![OutlinePiece::Line { from: [0.0, to[1]], to }];
3036            for k in 1..pieces.len() {
3037                filled.push(pieces[(wall + k) % pieces.len()].clone());
3038            }
3039            filled.push(OutlinePiece::Line { from, to: [0.0, from[1]] });
3040            filled.push(OutlinePiece::Line { from: [0.0, from[1]], to: [0.0, to[1]] });
3041            (inner, 0.5 * (low + high), None, filled)
3042        }
3043    };
3044    let centre0 = origin.add(w.scale(level));
3045    let filled = SolidTool::Revolved { axis_origin: origin, axis_direction: w, radial, meridian: filled_meridian };
3046    let short = || refuse("ring_flat", "a ring lying flat to its motion travels less than its hole is wide: the hole is not swept shut".into());
3047    if screw.omega == 0.0 {
3048        if screw.c.abs() * (screw.t1 - screw.t0) <= 2.0 * big * (1.0 + 1e-9) {
3049            let Some(tube) = torus else { return Err(short()) };
3050            // Short of its hole: what stays open, all the way through, is the
3051            // lens the hole shares where the ring starts and where it stops.
3052            // The hole at one place: inside the ring's inner half, between
3053            // its top and bottom planes.
3054            let hole = |t: f64| -> Result<BrepSolid, KernelRefusal> {
3055                let o = screw.apply(t, centre0);
3056                let u = frag(radial.sub(w.scale(radial.dot(w))).normalized(), "ring_flat")?;
3057                let at = |rho: f64, z: f64| o.add(u.scale(rho)).add(w.scale(z));
3058                let n = w.cross(u);
3059                let from = at(big, -tube);
3060                let inner = frag(frag(make_revolution(at(big, 0.0), n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?.iso_curve_v(0.0), "ring_flat")?;
3061                let profile = [
3062                    frag(make_line(at(0.0, -tube), at(big, -tube)), "ring_flat")?,
3063                    inner,
3064                    frag(make_line(at(big, tube), at(0.0, tube)), "ring_flat")?,
3065                    frag(make_line(at(0.0, tube), at(0.0, -tube)), "ring_flat")?,
3066                ];
3067                frag(crate::revolve_profile_brep(&profile, o, w, TAU), "ring_flat")
3068            };
3069            let (sewn_on, sewn_check) = (ring_lens_sewn_on(), ring_lens_sewn_check_on());
3070            if sewn_on || sewn_check {
3071                let whole = sweep_with(screw, &filled)?;
3072                let c0 = screw.apply(screw.t0, centre0);
3073                let c1 = screw.apply(screw.t1, centre0);
3074                let sewn = sewn_lens(&whole, c0, c1, w, big, tube);
3075                if sewn_check {
3076                    let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3077                    let cut = crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract)?;
3078                    ring_lens_check_record(&cut, sewn.as_ref());
3079                    return Ok(Some(cut));
3080                }
3081                if let Some(body) = sewn {
3082                    return Ok(Some(body));
3083                }
3084            }
3085            let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3086            let whole = sweep_with(screw, &filled)?;
3087            return crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract).map(Some);
3088        }
3089        return sweep_with(screw, &filled).map(Some);
3090    }
3091    // A turn: the ring's centre runs a circle of radius `reach` about the axis.
3092    let start_centre = screw.apply(screw.t0, centre0);
3093    let from_axis = start_centre.sub(screw.a);
3094    let across = from_axis.sub(screw.e.scale(from_axis.dot(screw.e)));
3095    let reach = across.length();
3096    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
3097    if theta >= TAU * (1.0 - 1e-12) {
3098        let Some(tube) = torus else {
3099            return Err(refuse("ring_flat", "a whole turn of a holed tool in its own plane is swept for a ring only".into()));
3100        };
3101        if reach <= (big + tube) * (1.0 + 1e-9) {
3102            return Err(refuse("ring_flat", "a ring turned a whole turn in its own plane reaches the turn's axis".into()));
3103        }
3104        let out = frag(across.normalized(), "ring_flat")?;
3105        let foot = start_centre.sub(across);
3106        let at = |rho: f64, z: f64| foot.add(out.scale(rho)).add(screw.e.scale(z));
3107        let half_round = |centre: Vec3, from: Vec3| -> Result<NurbsCurve, KernelRefusal> {
3108            let n = out.cross(screw.e);
3109            let surface = frag(make_revolution(centre, n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?;
3110            frag(surface.iso_curve_v(0.0), "ring_flat")
3111        };
3112        let profile = [
3113            frag(make_line(at(reach - big, -tube), at(reach + big, -tube)), "ring_flat")?,
3114            half_round(at(reach + big, 0.0), at(reach + big, -tube))?,
3115            frag(make_line(at(reach + big, tube), at(reach - big, tube)), "ring_flat")?,
3116            half_round(at(reach - big, 0.0), at(reach - big, tube))?,
3117        ];
3118        return frag(crate::revolve_profile_brep(&profile, foot, screw.e, TAU), "ring_flat").map(Some);
3119    }
3120    let covered = if theta >= PI { big < reach } else { reach * (0.5 * theta).sin() > big * (1.0 + 1e-9) };
3121    if !covered {
3122        return Err(short());
3123    }
3124    sweep_with(screw, &filled).map(Some)
3125}
3126
3127/// The sweep of `tool` along `motion`, where it lies in `clip` (the caller
3128/// cuts a workpiece inside that region). A TURN about the clip's own axis
3129/// whose two end positions stay outside the clip's wedge covers the wedge
3130/// wholly with the tool's shadow in (ρ, z): that shadow, turned over the wedge,
3131/// is the sweep there (a convex polyhedron's shadow is bounded by conic arcs
3132/// from its edges and straight lines from its faces, so every surface is
3133/// exact); a turn about that axis whose ends reach the wedge is refused. A
3134/// screw or turn about the region's axis whose tool reaches far past the
3135/// region's radius sweeps only the tool's part that can reach it (see
3136/// `trim_to_clip`). Any other motion gets the whole sweep ([`sweep_solid`]).
3137pub fn sweep_solid_clipped(tool: &SolidTool, motion: &SolidMotion, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3138    let screw = Screw::from_motion(motion)?;
3139    if let (SolidTool::Polyhedron { vertices, faces }, Some(wedge)) = (tool, clip.angle) {
3140        let axis = clip.axis_direction.normalized().map_err(|_| input("clip_axis", "the clip's axis has no direction".into()))?;
3141        let same_axis = screw.c == 0.0 && screw.c2 == 0.0
3142            && screw.e.cross(axis).length() < 1e-12
3143            && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3144        if same_axis {
3145            return turn_shadow(&screw, vertices, faces, clip, axis, wedge);
3146        }
3147    }
3148    if let SolidTool::Polyhedron { vertices, faces } = tool {
3149        if let Some((vertices, faces)) = trim_to_clip(&screw, vertices, faces, clip)? {
3150            return sweep_solid(&SolidTool::Polyhedron { vertices, faces }, motion);
3151        }
3152    }
3153    sweep_solid(tool, motion)
3154}
3155
3156/// The sweep of `tool` along a turn whose rise grows as it turns, where it lies
3157/// in `clip` (as [`sweep_solid_clipped`]). Its front and back are those at
3158/// the middle of the motion; a tool whose faces change side along it is refused.
3159pub fn sweep_solid_rising(tool: &SolidTool, motion: &RisingTurn, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3160    let screw = Screw::from_rising(motion)?;
3161    let SolidTool::Polyhedron { vertices, faces } = tool else {
3162        return Err(refuse("rising_tool", "a growing rise sweeps a polyhedron only".into()));
3163    };
3164    let (vertices, faces) = trim_to_clip(&screw, vertices, faces, clip)?.unwrap_or_else(|| (vertices.clone(), faces.clone()));
3165    sweep_with(&screw, &SolidTool::Polyhedron { vertices, faces })
3166}
3167
3168/// The sweep of `tool` along `motion` as parts whose union it is (a caller cuts
3169/// a workpiece by all of them). One part where the whole sweep passes once. A
3170/// convex polyhedron whose sweep folds over itself (a face facing away from a
3171/// screw's or turn's axis grazes along a line inside it, and the faces beyond
3172/// that line are swept over again) is split by the plane through the axis and
3173/// that line: each half grazes that face only along its cut edge, and is swept
3174/// whole. The halves' walls share cylinders about the axis.
3175pub fn sweep_solid_parts(tool: &SolidTool, motion: &SolidMotion) -> Result<Vec<BrepSolid>, KernelRefusal> {
3176    let folded = match sweep_solid(tool, motion) {
3177        Ok(body) => return Ok(vec![body]),
3178        Err(error) if refused_as(&error) == Some("folds") => error,
3179        Err(error) => return Err(error),
3180    };
3181    let SolidTool::Polyhedron { vertices, faces } = tool else { return Err(folded) };
3182    let screw = Screw::from_motion(motion)?;
3183    if screw.omega == 0.0 {
3184        return Err(folded);
3185    }
3186    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |a, &p| a.add(p)).scale(1.0 / vertices.len() as f64);
3187    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3188    for face in faces {
3189        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3190        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3191        if n.dot(p.sub(centroid)) < 0.0 {
3192            n = n.scale(-1.0);
3193        }
3194        planes.push((n, n.dot(p)));
3195    }
3196    // A face square to the axis' plane through it (its normal square to the
3197    // axis) graze along the line through its foot from the axis; it folds if
3198    // it faces away from the axis and that line crosses it.
3199    for (n, d) in planes.clone() {
3200        if n.dot(screw.e).abs() > 1e-12 {
3201            continue;
3202        }
3203        let foot = screw.a.add(n.scale(d - n.dot(screw.a)));
3204        let radial = foot.sub(screw.a).sub(screw.e.scale(foot.sub(screw.a).dot(screw.e)));
3205        if radial.dot(n) <= 0.0 {
3206            continue; // faces the axis: its grazing line is the sweep's inner wall
3207        }
3208        let cut = match screw.e.cross(radial).normalized() {
3209            Ok(m) => m,
3210            Err(_) => continue,
3211        };
3212        let offset = cut.dot(screw.a);
3213        let mut parts = Vec::with_capacity(2);
3214        for sense in [1.0, -1.0] {
3215            let mut half = planes.clone();
3216            half.push((cut.scale(sense), offset * sense));
3217            let (corners, loops) = polyhedron_of_planes(&half)?;
3218            if corners.len() < 4 || loops.len() < 4 {
3219                parts.clear();
3220                break;
3221            }
3222            match sweep_solid(&SolidTool::Polyhedron { vertices: corners, faces: loops }, motion) {
3223                Ok(body) => parts.push(body),
3224                Err(_) => {
3225                    parts.clear();
3226                    break;
3227                }
3228            }
3229        }
3230        if parts.len() == 2 {
3231            return Ok(parts);
3232        }
3233    }
3234    Err(folded)
3235}
3236
3237/// A screw or turn about the clip's axis maps the clip's cylinder (radius
3238/// ≤ R) onto itself, so inside it the sweep of the tool is the sweep of any
3239/// part of the tool holding the tool's part inside the cylinder. A tool
3240/// reaching far past it (a bar pointing at the axis) is replaced by its part
3241/// inside the prism over the shadow's piece of a slightly larger disc, with
3242/// that disc's arc replaced by the two tangents at its ends: those faces graze
3243/// only along their own end edges, where the far ends of a long tool would
3244/// fold the sweep over itself. None when the tool needs no trim.
3245fn trim_to_clip(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip) -> Result<Option<(Vec<Vec3>, Vec<Vec<usize>>)>, KernelRefusal> {
3246    let Ok(axis) = clip.axis_direction.normalized() else { return Ok(None) };
3247    let same_axis = screw.omega != 0.0
3248        && screw.e.cross(axis).length() < 1e-12
3249        && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3250    if !same_axis || !clip.radius[1].is_finite() {
3251        return Ok(None);
3252    }
3253    let ez = axis;
3254    let ex = Vec3::new(1.0, 0.0, 0.0).sub(ez.scale(ez.x)).normalized().or_else(|_| Vec3::new(0.0, 1.0, 0.0).sub(ez.scale(ez.y)).normalized()).map_err(|e| input("clip_axis", e))?;
3255    let ey = ez.cross(ex);
3256    let flat = |p: Vec3| {
3257        let r = p.sub(clip.axis_origin);
3258        [r.dot(ex), r.dot(ey)]
3259    };
3260    let radius = clip.radius[1] * 1.02;
3261    let shadow: Vec<[f64; 2]> = vertices.iter().map(|&p| flat(p)).collect();
3262    if shadow.iter().all(|q| q[0].hypot(q[1]) <= radius) {
3263        return Ok(None);
3264    }
3265    // The shadow's convex hull, counter-clockwise.
3266    let mut points = shadow.clone();
3267    points.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
3268    let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
3269    let mut hull: Vec<[f64; 2]> = Vec::new();
3270    for pass in 0..2 {
3271        let start = hull.len();
3272        let ordered: Vec<[f64; 2]> = if pass == 0 { points.clone() } else { points.iter().rev().copied().collect() };
3273        for p in ordered {
3274            while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
3275                hull.pop();
3276            }
3277            hull.push(p);
3278        }
3279        hull.pop();
3280    }
3281    // Where the hull's boundary leaves and re-enters the disc.
3282    let m = hull.len();
3283    let inside = |q: [f64; 2]| q[0].hypot(q[1]) <= radius;
3284    // Leave a tool that does not reach the disc, or wraps the axis.
3285    let mut nearest = f64::INFINITY;
3286    let mut wraps = true;
3287    for k in 0..m {
3288        let (a, b) = (hull[k], hull[(k + 1) % m]);
3289        let d = [b[0] - a[0], b[1] - a[1]];
3290        let t = (-(a[0] * d[0] + a[1] * d[1]) / (d[0] * d[0] + d[1] * d[1])).clamp(0.0, 1.0);
3291        nearest = nearest.min((a[0] + d[0] * t).hypot(a[1] + d[1] * t));
3292        if cross(a, b, [0.0, 0.0]) < 0.0 {
3293            wraps = false;
3294        }
3295    }
3296    if wraps || nearest >= radius || (0..m).all(|k| inside(hull[k])) {
3297        return Ok(None);
3298    }
3299    let mut leave: Vec<f64> = Vec::new();
3300    let mut enter: Vec<f64> = Vec::new();
3301    for k in 0..m {
3302        let (a, b) = (hull[k], hull[(k + 1) % m]);
3303        let d = [b[0] - a[0], b[1] - a[1]];
3304        let (qa, qb, qc) = (d[0] * d[0] + d[1] * d[1], 2.0 * (a[0] * d[0] + a[1] * d[1]), a[0] * a[0] + a[1] * a[1] - radius * radius);
3305        let disc = qb * qb - 4.0 * qa * qc;
3306        if disc <= 0.0 {
3307            continue;
3308        }
3309        for t in [(-qb - disc.sqrt()) / (2.0 * qa), (-qb + disc.sqrt()) / (2.0 * qa)] {
3310            if t > 0.0 && t < 1.0 {
3311                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3312                let outward = 2.0 * (q[0] * d[0] + q[1] * d[1]) > 0.0;
3313                (if outward { &mut leave } else { &mut enter }).push(q[1].atan2(q[0]));
3314            }
3315        }
3316    }
3317    let ([a], [b]) = (leave.as_slice(), enter.as_slice()) else {
3318        return Err(refuse("clip_trim", "the tool's shadow leaves the clip's disc more than once".into()));
3319    };
3320    let width = (b - a).rem_euclid(TAU);
3321    if width >= 0.9 * PI {
3322        return Err(refuse("clip_trim", "the tool's shadow spans too much of the clip's circle to be trimmed".into()));
3323    }
3324    // Planes of the tool, and the two tangents (outward normals in the plane).
3325    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3326    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &p| s.add(p)).scale(1.0 / vertices.len() as f64);
3327    for face in faces {
3328        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3329        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3330        if n.dot(p.sub(centroid)) < 0.0 {
3331            n = n.scale(-1.0);
3332        }
3333        planes.push((n, n.dot(p)));
3334    }
3335    for angle in [*a, *b] {
3336        let n = ex.scale(angle.cos()).add(ey.scale(angle.sin()));
3337        planes.push((n, n.dot(clip.axis_origin) + radius));
3338    }
3339    Ok(Some(polyhedron_of_planes(&planes)?))
3340}
3341
3342/// `BREP_SWEEP_SLID_POLYHEDRON_HULL` (default on; `=0` restores the refusal): a convex polyhedron slid
3343/// straight sweeps exactly the convex hull of its two end positions (every
3344/// point between is on a segment from one to the other), so the sweep is that
3345/// hull. The grazing split refused a face the slide moves in its own plane (a
3346/// block slid along one of its faces: the face's sweep is flat).
3347fn slid_hull_on() -> bool {
3348    crate::switch!("BREP_SWEEP_SLID_POLYHEDRON_HULL", true)
3349}
3350
3351/// The convex hull of the polyhedron at the screw's two ends, the screw being a
3352/// straight slide. The polyhedron must be the convex one its faces bound (the
3353/// hull of a concave tool is not its sweep), so its faces are read first: each
3354/// flat, the set closed, and every corner on the inner side of every face.
3355fn slid_polyhedron_hull(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3356    if vertices.len() < 4 || faces.len() < 4 || vertices.len() > 256 {
3357        return Err(input("polyhedron", "the tool needs at least four corners and four faces (and at most 256 corners)".into()));
3358    }
3359    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &p| s.add(p)).scale(1.0 / vertices.len() as f64);
3360    let extent = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max);
3361    if !(extent > 0.0) {
3362        return Err(input("polyhedron", "the tool's corners coincide".into()));
3363    }
3364    let slack = 1e-9 * extent;
3365    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
3366    // Either winding is a face's (as the grazing split reads it): each is
3367    // turned to run counter-clockwise from outside before the faces are read.
3368    let mut oriented: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
3369    let mut normals: Vec<Vec3> = Vec::with_capacity(faces.len());
3370    for (index, face) in faces.iter().enumerate() {
3371        if face.len() < 3 || face.iter().any(|&k| k >= vertices.len()) {
3372            return Err(input("face", format!("face {index} names fewer than three corners or one past the tool's")));
3373        }
3374        // Newell's normal, then outward by the centroid.
3375        let mut normal = Vec3::new(0.0, 0.0, 0.0);
3376        for k in 0..face.len() {
3377            let (a, b) = (vertices[face[k]].sub(centroid), vertices[face[(k + 1) % face.len()]].sub(centroid));
3378            normal = normal.add(Vec3::new((a.y - b.y) * (a.z + b.z), (a.z - b.z) * (a.x + b.x), (a.x - b.x) * (a.y + b.y)));
3379        }
3380        // Against the tool's own size, not an absolute floor.
3381        let length = normal.length();
3382        if !(length > 1e-18 * extent * extent) {
3383            return Err(input("face", format!("face {index} has no area")));
3384        }
3385        let mut normal = normal.scale(1.0 / length);
3386        let mut face = face.clone();
3387        let d = normal.dot(vertices[face[0]].sub(centroid));
3388        let d = if d < 0.0 {
3389            normal = normal.scale(-1.0);
3390            face.reverse();
3391            -d
3392        } else {
3393            d
3394        };
3395        for &k in &face {
3396            if (normal.dot(vertices[k].sub(centroid)) - d).abs() > slack {
3397                return Err(input("face", format!("face {index}'s corners are not in one plane")));
3398            }
3399        }
3400        if vertices.iter().any(|p| normal.dot(p.sub(centroid)) - d > slack) {
3401            return Err(input("convex", "the tool is not convex: a corner lies outside one of its faces".into()));
3402        }
3403        for k in 0..face.len() {
3404            let (a, b) = (face[k], face[(k + 1) % face.len()]);
3405            if owner.insert((a, b), index).is_some() {
3406                return Err(input("closed", "an edge is used more than once the same way".into()));
3407            }
3408        }
3409        oriented.push(face);
3410        normals.push(normal);
3411    }
3412    for &(a, b) in owner.keys() {
3413        if !owner.contains_key(&(b, a)) {
3414            return Err(input("closed", "the polyhedron's faces do not close".into()));
3415        }
3416    }
3417    // The faces must bound one closed part (the polyhedron builder's own
3418    // reading: faces given twice, once each way, close into separate parts).
3419    crate::make_polyhedron_brep(vertices, &oriented)?;
3420    // The sweep is the tool's Minkowski sum with the slide [0, s]: faces it
3421    // leaves behind at the start (n · s < 0), faces it leads with at the end
3422    // (n · s > 0), faces it slides in their own plane stretched to the hull of
3423    // their two copies, and one parallelogram per edge where the faces either
3424    // side face opposite ways. Built from the tool's own faces, no plane is
3425    // searched for and no tolerance grows with the slide.
3426    let n = vertices.len();
3427    let start: Vec<Vec3> = vertices.iter().map(|&p| screw.apply(screw.t0, p)).collect();
3428    let end: Vec<Vec3> = vertices.iter().map(|&p| screw.apply(screw.t1, p)).collect();
3429    let slide = end[0].sub(start[0]);
3430    let travel = slide.length();
3431    if !(travel > 0.0 && travel.is_finite()) {
3432        return Err(input("still", "the slide does not move".into()));
3433    }
3434    let along = slide.scale(1.0 / travel);
3435    // The polyhedron builder reads its faces against its whole extent, so a
3436    // slide far longer than the tool's thinnest width is beyond what it
3437    // builds (that width: the least spread of the corners along a face's
3438    // normal).
3439    let width = normals.iter().map(|nf| {
3440        let reach: Vec<f64> = vertices.iter().map(|p| nf.dot(*p)).collect();
3441        reach.iter().copied().fold(f64::NEG_INFINITY, f64::max) - reach.iter().copied().fold(f64::INFINITY, f64::min)
3442    }).fold(f64::INFINITY, f64::min);
3443    if slide.length() > 1e6 * width {
3444        return Err(refuse("slid_hull", format!("the slide ({:.3e}) is more than 1e6 times the tool's thinnest width ({width:.3e})", slide.length())));
3445    }
3446    let side: Vec<i8> = normals.iter().map(|nf| {
3447        let c = nf.dot(along);
3448        if c.abs() <= 1e-12 { 0 } else if c > 0.0 { 1 } else { -1 }
3449    }).collect();
3450    let corners: Vec<Vec3> = start.iter().chain(end.iter()).copied().collect();
3451    // A corner the slide carries onto another (a block slid by its own width)
3452    // is one corner: every index is read as its first coincident one.
3453    let canonical: Vec<usize> = (0..corners.len())
3454        .map(|k| (0..k).find(|&j| corners[j].sub(corners[k]).length() <= slack).unwrap_or(k))
3455        .collect();
3456    let mut pool: Vec<usize> = canonical.clone();
3457    pool.sort_unstable();
3458    pool.dedup();
3459    let canon = |set: Vec<usize>| -> Vec<usize> {
3460        let mut out: Vec<usize> = set.into_iter().map(|k| canonical[k]).collect();
3461        out.sort_unstable();
3462        out.dedup();
3463        out
3464    };
3465    // A ring of corner indices, ordered as the convex hull of its points
3466    // counter-clockwise about `normal` (corners inside it or on its sides
3467    // dropped).
3468    let ring = |set: &[usize], normal: Vec3| -> Option<Vec<usize>> {
3469        let middle = set.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &k| s.add(corners[k])).scale(1.0 / set.len() as f64);
3470        // The longest offset in the plane, divided by its own length (no
3471        // absolute floor: a small face is as good as a large one).
3472        let u = set
3473            .iter()
3474            .map(|&k| corners[k].sub(middle))
3475            .map(|r| r.sub(normal.scale(r.dot(normal))))
3476            .max_by(|a, b| a.length().total_cmp(&b.length()))?;
3477        let u = (u.length() > 0.0).then(|| u.scale(1.0 / u.length()))?;
3478        let v = normal.cross(u);
3479        let flat = |k: usize| {
3480            let r = corners[k].sub(middle);
3481            (r.dot(u), r.dot(v))
3482        };
3483        let mut order = set.to_vec();
3484        order.sort_by(|&a, &b| {
3485            let (pa, pb) = (flat(a), flat(b));
3486            pa.0.total_cmp(&pb.0).then(pa.1.total_cmp(&pb.1))
3487        });
3488        // A point is on the line through two others when it stands off it by
3489        // no more than the tool's tolerance (a distance, whatever the slide's
3490        // length): twice the triangle's area over the base.
3491        let left = |o: usize, a: usize, b: usize| {
3492            let (po, pa, pb) = (flat(o), flat(a), flat(b));
3493            let cross = (pa.0 - po.0) * (pb.1 - po.1) - (pa.1 - po.1) * (pb.0 - po.0);
3494            cross > slack * (pb.0 - po.0).hypot(pb.1 - po.1)
3495        };
3496        let mut hull: Vec<usize> = Vec::new();
3497        for pass in [false, true] {
3498            let begin = hull.len();
3499            let sequence: Vec<usize> = if pass { order.iter().rev().copied().collect() } else { order.clone() };
3500            for k in sequence {
3501                while hull.len() >= begin + 2 && !left(hull[hull.len() - 2], hull[hull.len() - 1], k) {
3502                    hull.pop();
3503                }
3504                hull.push(k);
3505            }
3506            hull.pop();
3507        }
3508        if hull.len() < 3 {
3509            return None;
3510        }
3511        // Every corner of the sweep on a side of this ring stays on it, in
3512        // order: whichever face it came from, the neighbour across that side
3513        // reads the same corners there, so the two rings carry the same edges.
3514        let mut out: Vec<usize> = Vec::with_capacity(set.len());
3515        for k in 0..hull.len() {
3516            let (p, q) = (hull[k], hull[(k + 1) % hull.len()]);
3517            out.push(p);
3518            let (a, d) = (corners[p], corners[q].sub(corners[p]));
3519            let length = d.length();
3520            let mut between: Vec<(f64, usize)> = pool
3521                .iter()
3522                .filter(|&&m| m != p && m != q)
3523                .filter_map(|&m| {
3524                    let r = corners[m].sub(a);
3525                    let t = r.dot(d) / (length * length);
3526                    let off = r.sub(d.scale(t)).length();
3527                    (t > 0.0 && t < 1.0 && off <= slack).then_some((t, m))
3528                })
3529                .collect();
3530            between.sort_by(|x, y| x.0.total_cmp(&y.0));
3531            out.extend(between.into_iter().map(|(_, m)| m));
3532        }
3533        Some(out)
3534    };
3535    // Coplanar faces of a convex polyhedron are one face of it: grouped by
3536    // plane, each group read as one (the union of its corners).
3537    let offsets: Vec<f64> = oriented.iter().zip(&normals).map(|(face, nf)| nf.dot(vertices[face[0]].sub(centroid))).collect();
3538    let mut group = vec![usize::MAX; oriented.len()];
3539    let mut groups: Vec<Vec<usize>> = Vec::new();
3540    for f in 0..oriented.len() {
3541        if group[f] != usize::MAX {
3542            continue;
3543        }
3544        group[f] = groups.len();
3545        let mut members = vec![f];
3546        for g in f + 1..oriented.len() {
3547            // One face only if the slide reads them alike too: two faces a
3548            // hair apart in angle can face it opposite ways, and then their
3549            // shared edge is a silhouette of its own.
3550            if group[g] == usize::MAX && side[g] == side[f] && normals[g].sub(normals[f]).length() <= 1e-9 && (offsets[g] - offsets[f]).abs() <= slack {
3551                group[g] = groups.len();
3552                members.push(g);
3553            }
3554        }
3555        groups.push(members);
3556    }
3557    let mut hull_faces: Vec<Vec<usize>> = Vec::new();
3558    for (index, members) in groups.iter().enumerate() {
3559        let f = members[0];
3560        let mut corners_of: Vec<usize> = members.iter().flat_map(|&m| oriented[m].iter().copied()).collect();
3561        corners_of.sort_unstable();
3562        corners_of.dedup();
3563        let set: Vec<usize> = canon(match side[f] {
3564            -1 => corners_of,
3565            1 => corners_of.iter().map(|&k| k + n).collect(),
3566            _ => corners_of.iter().flat_map(|&k| [k, k + n]).collect(),
3567        });
3568        hull_faces.push(ring(&set, normals[f]).ok_or_else(|| refuse("slid_hull", format!("face group {index}'s sweep has no area")))?);
3569    }
3570    // In a fixed order, so the same tool builds the same body.
3571    let mut edges: Vec<(usize, usize)> = owner.keys().copied().filter(|&(a, b)| a < b).collect();
3572    edges.sort_unstable();
3573    for (a, b) in edges {
3574        let (f, g) = (owner[&(a, b)], owner[&(b, a)]);
3575        // Once per edge between two faces of the hull's own (not two
3576        // coplanar pieces of one), where the face on its left leads and the
3577        // one on its right trails (or the other way): the edge's own sweep is
3578        // a face.
3579        if group[f] != group[g] && side[f] * side[g] < 0 {
3580            let edge = start[b].sub(start[a]);
3581            // Against the edge's own length (an edge of a silhouette is never
3582            // along the slide: its faces would both slide in their planes).
3583            let cross = edge.cross(along);
3584            let length = cross.length();
3585            if !(length > 1e-12 * edge.length()) {
3586                return Err(refuse("slid_hull", "a silhouette edge runs along the slide".into()));
3587            }
3588            let mut normal = cross.scale(1.0 / length);
3589            if normal.dot(start[a].sub(centroid)) < 0.0 {
3590                normal = normal.scale(-1.0);
3591            }
3592            hull_faces.push(ring(&canon(vec![a, b, a + n, b + n]), normal).ok_or_else(|| refuse("slid_hull", "an edge's sweep has no area".into()))?);
3593        }
3594    }
3595    crate::make_polyhedron_brep(&corners, &hull_faces)
3596}
3597
3598/// The convex polyhedron {n · p ≤ d for every plane}: its corners (where three
3599/// planes meet inside all) and a face per plane that bounds it.
3600pub fn polyhedron_of_planes(planes: &[(Vec3, f64)]) -> Result<(Vec<Vec3>, Vec<Vec<usize>>), KernelRefusal> {
3601    let k = planes.len();
3602    let mut corners: Vec<Vec3> = Vec::new();
3603    let scale = planes.iter().map(|p| p.1.abs()).fold(1.0f64, f64::max);
3604    for i in 0..k {
3605        for j in i + 1..k {
3606            for l in j + 1..k {
3607                let (a, b, c) = (planes[i].0, planes[j].0, planes[l].0);
3608                let det = a.dot(b.cross(c));
3609                if det.abs() < 1e-12 {
3610                    continue;
3611                }
3612                let p = b.cross(c).scale(planes[i].1).add(c.cross(a).scale(planes[j].1)).add(a.cross(b).scale(planes[l].1)).scale(1.0 / det);
3613                if planes.iter().all(|(n, d)| n.dot(p) - d <= 1e-9 * scale) && !corners.iter().any(|q| q.sub(p).length() <= 1e-9 * scale) {
3614                    corners.push(p);
3615                }
3616            }
3617        }
3618    }
3619    let mut faces = Vec::new();
3620    for (n, d) in planes {
3621        let on: Vec<usize> = (0..corners.len()).filter(|&c| (n.dot(corners[c]) - d).abs() <= 1e-9 * scale).collect();
3622        if on.len() < 3 {
3623            continue;
3624        }
3625        let middle = on.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &c| s.add(corners[c])).scale(1.0 / on.len() as f64);
3626        let u = frag(corners[on[0]].sub(middle).normalized(), "face_axis")?;
3627        let v = n.cross(u);
3628        let mut ordered = on.clone();
3629        ordered.sort_by(|&p, &q| {
3630            let (rp, rq) = (corners[p].sub(middle), corners[q].sub(middle));
3631            rp.dot(v).atan2(rp.dot(u)).total_cmp(&rq.dot(v).atan2(rq.dot(u)))
3632        });
3633        faces.push(ordered);
3634    }
3635    Ok((corners, faces))
3636}
3637
3638fn turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip, axis: Vec3, wedge: [f64; 2]) -> Result<BrepSolid, KernelRefusal> {
3639    let ez = axis;
3640    let ex = clip.reference.sub(ez.scale(clip.reference.dot(ez))).normalized().map_err(|_| input("clip_reference", "the clip's reference lies along its axis".into()))?;
3641    let ey = ez.cross(ex);
3642    // Turning by ω t about e = ±ez moves angles about ez by ±ω t.
3643    let rate = screw.omega * screw.e.dot(ez).signum();
3644    let local = |p: Vec3| {
3645        let r = p.sub(clip.axis_origin);
3646        [r.dot(ex), r.dot(ey), r.dot(ez)]
3647    };
3648    let corners: Vec<[f64; 3]> = vertices.iter().map(|&p| local(p)).collect();
3649    // The tool's angular extent about the axis (its corners'; the tool must
3650    // keep off the axis, so its shadow on the plane misses the origin).
3651    let mid = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
3652    let mid_angle = mid[1].atan2(mid[0]);
3653    let angles: Vec<f64> = corners.iter().map(|c| mid_angle + (c[1].atan2(c[0]) - mid_angle + PI).rem_euclid(TAU) - PI).collect();
3654    let (low, high) = (angles.iter().copied().fold(f64::INFINITY, f64::min), angles.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3655    if high - low >= PI {
3656        return Err(refuse("turn_shadow", "the tool reaches round the turn's axis".into()));
3657    }
3658    let (start, end) = (rate * screw.t0, rate * screw.t1);
3659    let (first, last) = if rate > 0.0 { (start, end) } else { (end, start) };
3660    let reference = 0.5 * (wedge[0] + wedge[1]);
3661    let near = |a: f64| reference + (a - reference + PI).rem_euclid(TAU) - PI;
3662    // Before the wedge at one end, after it at the other (angles taken near the wedge).
3663    let clear = near(high + first) < wedge[0] - 1e-9 && near(low + last) > wedge[1] + 1e-9 && (last - first) < TAU;
3664    if !clear {
3665        return Err(refuse("turn_shadow", "the turned tool's ends reach the clip's wedge; its sweep there is not its turned shadow".into()));
3666    }
3667    let profile = polyhedron_shadow(&corners, faces, false)?;
3668    // The profile in the half-plane at the wedge's start angle.
3669    let (c0, s0) = (wedge[0].cos(), wedge[0].sin());
3670    let world = |rho: f64, z: f64| clip.axis_origin.add(ez.scale(z)).add(ex.scale(rho * c0)).add(ey.scale(rho * s0));
3671    let mut curves = Vec::with_capacity(profile.len());
3672    for piece in &profile {
3673        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3674        let curve = if points.len() == 2 {
3675            frag(make_line(frag(points[0].point(), "point")?, frag(points[1].point(), "point")?), "line")?
3676        } else {
3677            frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")?
3678        };
3679        curves.push(curve);
3680    }
3681    frag(crate::revolve_profile_brep(&curves, clip.axis_origin, ez, wedge[1] - wedge[0]), "turn_shadow")
3682}
3683
3684/// A convex polyhedron turned a whole turn (no advance): the solid of
3685/// revolution of its shadow {(ρ, z)} about the turn's axis, which may pass
3686/// through it. Its corners' paths bound it only where an edge is farthest
3687/// from the axis; an edge skew to the axis turns a hyperboloid.
3688fn whole_turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3689    let ez = screw.e;
3690    let ex = frag(ez.perpendicular(), "turn_shadow")?;
3691    let ex = frag(ex.sub(ez.scale(ex.dot(ez))).normalized(), "turn_shadow")?;
3692    let ey = ez.cross(ex);
3693    let corners: Vec<[f64; 3]> = vertices
3694        .iter()
3695        .map(|&p| {
3696            let r = screw.apply(screw.t0, p).sub(screw.a);
3697            [r.dot(ex), r.dot(ey), r.dot(ez)]
3698        })
3699        .collect();
3700    let profile = polyhedron_shadow(&corners, faces, true)?;
3701    // A point of the outline on the axis to round-off is on it.
3702    let reach = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(0.0f64, f64::max);
3703    let world = |rho: f64, z: f64| screw.a.add(ez.scale(z)).add(ex.scale(if rho.abs() <= 1e-10 * reach { 0.0 } else { rho }));
3704    let mut curves = Vec::with_capacity(profile.len());
3705    // The outline's stretch along the axis, as one edge (it comes a piece per
3706    // corner height).
3707    let on_axis = |piece: &ShadowPiece| piece.iter().all(|&(rho, _, _)| rho.abs() <= 1e-10 * reach);
3708    let mut along: Option<(f64, f64)> = None;
3709    for piece in &profile {
3710        if on_axis(piece) {
3711            let (za, zb) = (piece[0].1, piece[piece.len() - 1].1);
3712            along = Some(match along {
3713                Some((from, _)) => (from, zb),
3714                None => (za, zb),
3715            });
3716            continue;
3717        }
3718        if let Some((from, to)) = along.take() {
3719            curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3720        }
3721        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3722        let (first, last) = (frag(points[0].point(), "point")?, frag(points[points.len() - 1].point(), "point")?);
3723        if first.sub(last).length() <= 1e-12 * (1.0 + first.length()) {
3724            continue;
3725        }
3726        let curve = if points.len() == 2 { frag(make_line(first, last), "line")? } else { frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")? };
3727        curves.push(curve);
3728    }
3729    if let Some((from, to)) = along.take() {
3730        curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3731    }
3732    frag(crate::revolve_profile_brep(&curves, screw.a, ez, TAU), "turn_shadow")
3733}
3734
3735/// One piece of the shadow's outline: a segment (two points) or a rational
3736/// quadratic arc (three, the middle with its weight), as (ρ, z, weight).
3737type ShadowPiece = Vec<(f64, f64, f64)>;
3738
3739/// The shadow {(ρ, z)} of a convex polyhedron (corners in the axis frame):
3740/// at each z its section is a convex polygon, the ρ it reaches an interval
3741/// from the section's nearest point to its farthest corner. The farthest is
3742/// always on an edge (ρ² = quadratic in z: a conic arc); the nearest is on a
3743/// face (ρ linear in z: a segment) or an edge.
3744///
3745/// `through`: the axis may pass through the tool (its nearest ρ is then 0 and
3746/// the outline runs along the axis there); refused otherwise.
3747fn polyhedron_shadow(corners: &[[f64; 3]], faces: &[Vec<usize>], through: bool) -> Result<Vec<ShadowPiece>, KernelRefusal> {
3748    let zs: Vec<f64> = corners.iter().map(|c| c[2]).collect();
3749    let (z_low, z_high) = (zs.iter().copied().fold(f64::INFINITY, f64::min), zs.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3750    let scale = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(1.0f64, f64::max);
3751    // The hull's edges (from the faces' loops) and the faces beside each.
3752    let mut edge_faces: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
3753    for (f, face) in faces.iter().enumerate() {
3754        for k in 0..face.len() {
3755            let (i, j) = (face[k], face[(k + 1) % face.len()]);
3756            edge_faces.entry((i.min(j), i.max(j))).or_default().push(f);
3757        }
3758    }
3759    let mut edges: Vec<(usize, usize)> = edge_faces.keys().copied().collect();
3760    edges.sort_unstable();
3761    // Each face's plane in the axis frame: n · p = d.
3762    let planes: Vec<([f64; 3], f64)> = faces
3763        .iter()
3764        .map(|face| {
3765            let (a, b, c) = (corners[face[0]], corners[face[1]], corners[face[2]]);
3766            let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
3767            let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
3768            (n, n[0] * a[0] + n[1] * a[1] + n[2] * a[2])
3769        })
3770        .collect();
3771    #[derive(Clone, Copy, PartialEq, Debug)]
3772    enum Source {
3773        /// The crossing of edge k.
3774        Edge(usize),
3775        /// The nearest point of face f's section line.
3776        Face(usize),
3777        /// The axis itself, where it passes through the tool.
3778        Axis,
3779    }
3780    let edge_at = |k: usize, z: f64| -> [f64; 2] {
3781        let (a, b) = (corners[edges[k].0], corners[edges[k].1]);
3782        let t = (z - a[2]) / (b[2] - a[2]);
3783        [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
3784    };
3785    let crossing = |z: f64| -> Vec<usize> {
3786        (0..edges.len()).filter(|&k| (corners[edges[k].0][2] - z) * (corners[edges[k].1][2] - z) < 0.0).collect()
3787    };
3788    let farthest = |z: f64| -> (Source, f64) {
3789        let mut best = (Source::Edge(0), f64::NEG_INFINITY);
3790        for k in crossing(z) {
3791            let p = edge_at(k, z);
3792            let r = p[0].hypot(p[1]);
3793            if r > best.1 {
3794                best = (Source::Edge(k), r);
3795            }
3796        }
3797        best
3798    };
3799    // The section polygon: edge crossings ordered by angle about their mean.
3800    let nearest = |z: f64| -> Result<(Source, f64), KernelRefusal> {
3801        let list = crossing(z);
3802        let points: Vec<[f64; 2]> = list.iter().map(|&k| edge_at(k, z)).collect();
3803        let m = points.len();
3804        if m < 3 {
3805            return Err(refuse("turn_shadow", "a section of the tool is not a polygon".into()));
3806        }
3807        let centre = points.iter().fold([0.0, 0.0], |s, p| [s[0] + p[0] / m as f64, s[1] + p[1] / m as f64]);
3808        let mut order: Vec<usize> = (0..m).collect();
3809        order.sort_by(|&a, &b| {
3810            let (pa, pb) = (points[a], points[b]);
3811            (pa[1] - centre[1]).atan2(pa[0] - centre[0]).total_cmp(&(pb[1] - centre[1]).atan2(pb[0] - centre[0]))
3812        });
3813        let mut inside = true;
3814        let mut best = (Source::Edge(0), f64::INFINITY);
3815        for k in 0..m {
3816            let (ia, ib) = (order[k], order[(k + 1) % m]);
3817            let (a, b) = (points[ia], points[ib]);
3818            let d = [b[0] - a[0], b[1] - a[1]];
3819            if d[0] * (0.0 - a[1]) - d[1] * (0.0 - a[0]) < 0.0 {
3820                inside = false;
3821            }
3822            let length2 = d[0] * d[0] + d[1] * d[1];
3823            let t = -(a[0] * d[0] + a[1] * d[1]) / length2;
3824            let (source, r) = if t > 0.0 && t < 1.0 {
3825                let (ea, eb) = (edges[list[ia]], edges[list[ib]]);
3826                let shared = edge_faces[&ea].iter().find(|f| edge_faces[&eb].contains(f)).copied();
3827                let Some(face) = shared else {
3828                    return Err(refuse("turn_shadow", "a section side does not lie on one face".into()));
3829                };
3830                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3831                (Source::Face(face), q[0].hypot(q[1]))
3832            } else {
3833                let q = if t <= 0.0 { a } else { b };
3834                (Source::Edge(list[if t <= 0.0 { ia } else { ib }]), q[0].hypot(q[1]))
3835            };
3836            if r < best.1 {
3837                best = (source, r);
3838            }
3839        }
3840        if inside {
3841            if !through {
3842                return Err(refuse("turn_shadow", "the turn's axis passes through the tool".into()));
3843            }
3844            return Ok((Source::Axis, 0.0));
3845        }
3846        Ok(best)
3847    };
3848    // ρ of a source at z, from its own geometry (smooth across the piece).
3849    let value = |source: Source, z: f64| -> f64 {
3850        match source {
3851            Source::Edge(k) => {
3852                let p = edge_at(k, z);
3853                p[0].hypot(p[1])
3854            }
3855            Source::Face(f) => {
3856                let (n, d) = planes[f];
3857                (d - n[2] * z).abs() / n[0].hypot(n[1])
3858            }
3859            Source::Axis => 0.0,
3860        }
3861    };
3862    // Breaks: corner heights, and where the farthest or nearest source changes.
3863    let mut heights: Vec<f64> = zs.clone();
3864    heights.sort_by(|a, b| a.total_cmp(b));
3865    heights.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * scale);
3866    let mut pieces_far: Vec<(f64, f64, Source)> = Vec::new();
3867    let mut pieces_near: Vec<(f64, f64, Source)> = Vec::new();
3868    for window in heights.windows(2) {
3869        let (za, zb) = (window[0], window[1]);
3870        let samples = 400;
3871        let inner = |k: usize| za + (zb - za) * (k as f64 + 0.5) / samples as f64;
3872        for near in [false, true] {
3873            let source_at = |z: f64| -> Result<Source, KernelRefusal> { Ok(if near { nearest(z)?.0 } else { farthest(z).0 }) };
3874            let mut runs: Vec<(f64, Source)> = vec![(za, source_at(inner(0))?)];
3875            for k in 1..samples {
3876                let (z0, z1) = (inner(k - 1), inner(k));
3877                let (s0, s1) = (source_at(z0)?, source_at(z1)?);
3878                // Two sources tied over the stretch (edges equally far from
3879                // the axis) are one piece of the outline.
3880                let tied = [z0, 0.5 * (z0 + z1), z1].iter().all(|&z| (value(s0, z) - value(s1, z)).abs() <= 1e-12 * scale);
3881                if s0 == s1 || tied {
3882                    continue;
3883                }
3884                // Where the source changes, by bisection (a side handing over
3885                // to its corner touches it, so their values do not cross).
3886                let (mut lo, mut hi) = (z0, z1);
3887                for _ in 0..200 {
3888                    let midz = 0.5 * (lo + hi);
3889                    if source_at(midz)? == s0 { lo = midz } else { hi = midz }
3890                }
3891                runs.push((0.5 * (lo + hi), s1));
3892            }
3893            let list = if near { &mut pieces_near } else { &mut pieces_far };
3894            for k in 0..runs.len() {
3895                let z_end = if k + 1 < runs.len() { runs[k + 1].0 } else { zb };
3896                list.push((runs[k].0, z_end, runs[k].1));
3897            }
3898        }
3899    }
3900    // Exact pieces: a pair's ρ(z) is a conic arc, a side's a segment.
3901    let piece = |source: Source, za: f64, zb: f64| -> Vec<ShadowPiece> {
3902        let (ra, rb) = (value(source, za), value(source, zb));
3903        if matches!(source, Source::Face(..) | Source::Axis) {
3904            return vec![vec![(ra, za, 1.0), (rb, zb, 1.0)]];
3905        }
3906        // ρ² = α z² + β z + γ; split so each arc turns little.
3907        let rho = |z: f64| value(source, z);
3908        // Differences kept inside the piece (an edge through the axis has a
3909        // corner in ρ at its end there).
3910        let (z_min, z_max) = (za.min(zb), za.max(zb));
3911        let slope = |z: f64| {
3912            let h = 1e-6 * (zb - za).abs().max(1e-300);
3913            let (zp, zm) = ((z + h).min(z_max), (z - h).max(z_min));
3914            (rho(zp) - rho(zm)) / (zp - zm)
3915        };
3916        let parts = 4;
3917        let mut out = Vec::new();
3918        for k in 0..parts {
3919            let (z0, z1) = (za + (zb - za) * k as f64 / parts as f64, za + (zb - za) * (k + 1) as f64 / parts as f64);
3920            let (a, b) = ((rho(z0), z0), (rho(z1), z1));
3921            // Straight (an edge meeting the axis): a segment.
3922            let bend = [0.25, 0.5, 0.75].iter().map(|&t| (rho(z0 + (z1 - z0) * t) - (a.0 + (b.0 - a.0) * t)).abs()).fold(0.0f64, f64::max);
3923            if bend <= 1e-12 * scale {
3924                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3925                continue;
3926            }
3927            let (ta, tb) = ((slope(z0), 1.0), (slope(z1), 1.0));
3928            // Tangent lines' intersection.
3929            let det = ta.0 * (-tb.1) - ta.1 * (-tb.0);
3930            if det.abs() < 1e-12 {
3931                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3932                continue;
3933            }
3934            let rhs = (b.0 - a.0, b.1 - a.1);
3935            let s = (rhs.0 * (-tb.1) - rhs.1 * (-tb.0)) / det;
3936            let c = (a.0 + ta.0 * s, a.1 + ta.1 * s);
3937            // Shoulder: the conic's point on the line from the chord's middle to c.
3938            let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
3939            let on = |u: f64| {
3940                let p = (m.0 + (c.0 - m.0) * u, m.1 + (c.1 - m.1) * u);
3941                p.0 - rho(p.1)
3942            };
3943            let (mut lo, mut hi) = (0.0, 1.0);
3944            let sign_lo = on(lo);
3945            for _ in 0..200 {
3946                let mid = 0.5 * (lo + hi);
3947                if (on(mid) > 0.0) == (sign_lo > 0.0) { lo = mid } else { hi = mid }
3948            }
3949            let u = 0.5 * (lo + hi);
3950            let weight = u / (1.0 - u);
3951            out.push(vec![(a.0, a.1, 1.0), (c.0, c.1, weight), (b.0, b.1, 1.0)]);
3952        }
3953        out
3954    };
3955    // Outline: up the near side, across the top, down the far side, across the bottom.
3956    let mut outline: Vec<ShadowPiece> = Vec::new();
3957    for &(za, zb, source) in &pieces_near {
3958        outline.extend(piece(source, za, zb));
3959    }
3960    let (near_top, far_top) = (value(pieces_near.last().expect("near").2, z_high), value(pieces_far.last().expect("far").2, z_high));
3961    if far_top - near_top > 1e-12 * scale {
3962        outline.push(vec![(near_top, z_high, 1.0), (far_top, z_high, 1.0)]);
3963    }
3964    for &(za, zb, source) in pieces_far.iter().rev() {
3965        for mut arc in piece(source, za, zb).into_iter().rev() {
3966            arc.reverse();
3967            outline.push(arc);
3968        }
3969    }
3970    let (near_bottom, far_bottom) = (value(pieces_near[0].2, z_low), value(pieces_far[0].2, z_low));
3971    if far_bottom - near_bottom > 1e-12 * scale {
3972        outline.push(vec![(far_bottom, z_low, 1.0), (near_bottom, z_low, 1.0)]);
3973    }
3974    // Snap consecutive ends together.
3975    for k in 0..outline.len() {
3976        let next = (k + 1) % outline.len();
3977        let end = *outline[k].last().expect("piece");
3978        outline[next][0] = (end.0, end.1, 1.0);
3979    }
3980    Ok(outline)
3981}
3982
3983/// A ball TURNED about an axis that passes through it. Its grazing circle (in
3984/// the plane of the axis and the centre) crosses the axis at two poles N and S;
3985/// the part beyond the axis turns inside the sweep, and near the axis the ends
3986/// overlap. So the sweep has three faces: the wall, the outer arc of that
3987/// circle turned (a spindle torus's outer part, pinched at N and S); the
3988/// ball's back at the start less the ball at the end; and its front at the end
3989/// less the ball at the start. The two caps meet along the far arc, from S to
3990/// N, of the circle where the two spheres meet. None when the motion or tool
3991/// is not of that kind.
3992fn ball_whole_turn_on() -> bool {
3993    crate::switch!("BREP_SWEEP_BALL_WHOLE_TURN", true)
3994}
3995
3996fn ball_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
3997    let [OutlinePiece::Arc { centre, radius, start, end }, OutlinePiece::Line { .. }] = meridian else { return Ok(None) };
3998    let (centre, r) = (*centre, *radius);
3999    if centre[0].abs() > 1e-12 * r || ((end - start).abs() - PI).abs() > 1e-12 || screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 {
4000        return Ok(None);
4001    }
4002    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
4003    let centre_tool = origin.add(w.scale(centre[1]));
4004    let turned = screw.omega * (screw.t1 - screw.t0);
4005    if turned.abs() >= TAU - 1e-9 {
4006        // `BREP_SWEEP_BALL_WHOLE_TURN` (default on; `=0` restores the refusal): a ball turned a whole
4007        // turn about an axis that misses it sweeps the torus its great circle
4008        // in the axis' half-plane turns: that circle, revolved about the axis.
4009        let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
4010        let unit = |p: Vec3| finite(p) && (p.length() - 1.0).abs() <= 1e-9;
4011        if ball_whole_turn_on() && turned.is_finite() && finite(radial) && finite(origin) && finite(axis) && unit(w) && finite(screw.a) && unit(screw.e) {
4012            // The tool's own frame must be one (as every route reads it), and
4013            // its meridian the half disc: the arc closed by the diameter back
4014            // from the arc's end to its start.
4015            radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
4016            let [_, OutlinePiece::Line { from, to }] = meridian else { return Ok(None) };
4017            let at = |angle: f64| [centre[0] + r * angle.cos(), centre[1] + r * angle.sin()];
4018            let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-12 * r;
4019            if !(near(*from, at(*end)) && near(*to, at(*start)) && from[0].abs() <= 1e-12 * r && to[0].abs() <= 1e-12 * r) {
4020                return Err(input("meridian", "the ball's meridian is not the half disc closed by its diameter on the axis".into()));
4021            }
4022            let e = screw.e;
4023            let off = centre_tool.sub(screw.a);
4024            let radial = off.sub(e.scale(off.dot(e)));
4025            // Whole only if the shortfall leaves no gap the ball's own size
4026            // would see: the arc it misses, out at the ball's far side.
4027            let gap = (TAU - turned.abs()).max(0.0) * (radial.length() + r);
4028            if radial.length() > r * (1.0 + 1e-9) && gap <= 1e-9 * r {
4029                let normal = frag(e.cross(radial).normalized(), "ball_turn")?;
4030                let circle = frag(crate::make_circle(centre_tool, normal, r), "ball_turn")?;
4031                return Ok(Some(frag(crate::revolve_profile_brep(&[circle], screw.a, e, TAU), "ball_turn")?));
4032            }
4033        }
4034        return Ok(None);
4035    }
4036    let e = screw.e.scale(screw.omega.signum()); // the sense the ball turns about
4037    let c0 = screw.apply(screw.t0, centre_tool);
4038    let c1 = screw.apply(screw.t1, centre_tool);
4039    let foot = |c: Vec3| screw.a.add(e.scale(c.sub(screw.a).dot(e)));
4040    let rho = c0.sub(foot(c0)).length();
4041    if rho >= r * (1.0 - 1e-9) || rho <= 1e-9 * r {
4042        return Ok(None);
4043    }
4044    let h0 = frag(c0.sub(foot(c0)).normalized(), "radial")?;
4045    let height = (r * r - rho * rho).sqrt();
4046    let (north, south) = (foot(c0).add(e.scale(height)), foot(c0).sub(e.scale(height)));
4047    // An arc from `from` turned about `axis` through `centre` by `angle`.
4048    let arc = |about: Vec3, k: Vec3, from: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
4049        let surface = frag(make_revolution(about, k, &frag(make_line(from, from.add(k)), "line")?, angle), "arc")?;
4050        frag(surface.iso_curve_v(0.0), "arc")
4051    };
4052    // The outer arc of the grazing circle, S -> N through c0 + r h0: in the
4053    // (h0, e) plane about c0, from angle -α to α through 0, α = atan2(height, -ρ).
4054    let alpha = height.atan2(-rho);
4055    let outer = arc(c0, h0.cross(e), south, 2.0 * alpha)?;
4056    let wall = frag(make_revolution(screw.a, e, &outer, turned.abs()), "wall")?;
4057    let outer_end = frag(wall.iso_curve_u(1.0), "wall_end")?;
4058    // The far arc where the spheres meet, S -> N beyond the axis.
4059    let mid = c0.add(c1).scale(0.5);
4060    let towards = frag(mid.sub(foot(mid)).normalized(), "bisector")?;
4061    let rho_mid = mid.sub(foot(mid)).length();
4062    let beta = height.atan2(rho_mid); // S and N seen from mid, off the far direction
4063    // From S at angle β − π (in the (towards, e) plane about mid) down through
4064    // π to N at π − β: the decreasing sense, about e × towards.
4065    let meet = arc(mid, e.cross(towards), south, 2.0 * beta)?;
4066    {
4067        // The arc must pass beyond the axis (its middle on the far side).
4068        let [d0, d1] = frag(meet.domain(), "domain")?;
4069        let middle = frag(meet.evaluate(0.5 * (d0 + d1)), "middle")?;
4070        if middle.sub(foot(middle)).dot(towards) > 0.0 {
4071            return Err(refuse("ball_across_axis", "the spheres' common circle runs the wrong way round".into()));
4072        }
4073    }
4074    // A trimmed sphere cap: a chart whose poles and seam lie where the cap is not.
4075    let cap = |c: Vec3, inward: Vec3, side: Vec3, other: Vec3| -> Result<(NurbsSurface, Box<dyn Fn(Vec3) -> Vec3>), KernelRefusal> {
4076        // South pole just off the far end of the grazing circle, on the removed
4077        // side (inside the other end's ball); the seam crosses the grazing
4078        // circle beyond the axis only.
4079        let toward_south = frag(inward.add(side.scale(-0.3)).normalized(), "pole")?;
4080        let polar = toward_south.scale(-1.0);
4081        let seam = frag(side.sub(polar.scale(side.dot(polar))).normalized(), "seam")?;
4082        for k in 0..=64 {
4083            // The seam's part on the cap's side of the grazing circle must lie
4084            // inside the other ball (where the cap is not).
4085            let a = PI * k as f64 / 64.0;
4086            let q = c.add(polar.scale(-r * a.cos())).add(seam.scale(r * a.sin()));
4087            if q.sub(c).dot(side) < 0.0 && q.sub(other).length() >= r * (1.0 - 1e-9) {
4088                return Err(refuse("ball_across_axis", "no seam place for a cap".into()));
4089            }
4090        }
4091        let south_pole = c.sub(polar.scale(r));
4092        if south_pole.sub(other).length() >= r * (1.0 - 1e-6) {
4093            return Err(refuse("ball_across_axis", "no pole place for a cap".into()));
4094        }
4095        let generatrix = arc(c, polar.scale(-1.0).cross(seam), south_pole, PI)?;
4096        let surface = frag(make_revolution(c, polar, &generatrix, TAU), "cap")?;
4097        let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
4098        let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
4099        let around = polar.cross(seam);
4100        let inverse = move |x: Vec3| -> Vec3 {
4101            let d = x.sub(c).scale(1.0 / r);
4102            let latitude = d.dot(polar).clamp(-1.0, 1.0).asin();
4103            let longitude = d.dot(around).atan2(d.dot(seam)).rem_euclid(TAU);
4104            Vec3::new(
4105                crate::circle_angle_to_parameter(spans_u, TAU, longitude),
4106                crate::circle_angle_to_parameter(spans_v, PI, latitude + 0.5 * PI),
4107                0.0,
4108            )
4109        };
4110        Ok((surface, Box::new(inverse)))
4111    };
4112    let moving0 = e.cross(h0);
4113    let h1 = frag(c1.sub(foot(c1)).normalized(), "radial")?;
4114    let moving1 = e.cross(h1);
4115    // The back cap at the start (its removed part near c0 − r h0 on the back);
4116    // the front cap at the end.
4117    let (back, back_inverse) = cap(c0, h0.scale(-1.0), moving0.scale(1.0), c1)?;
4118    let (front, front_inverse) = cap(c1, h1.scale(-1.0), moving1.scale(-1.0), c0)?;
4119    let (back_joints, front_joints) = (surface_joints(&back), surface_joints(&front));
4120    let pcurve = |inverse: &dyn Fn(Vec3) -> Vec3, curve: &NurbsCurve, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
4121        let [d0, d1] = frag(curve.domain(), "domain")?;
4122        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
4123        let uv: Vec<Vec3> = ts.iter().map(|&t| curve.evaluate(t).map(|x| inverse(x))).collect::<Result<_, _>>().map_err(|e| refuse("pcurve", e))?;
4124        if pcurve_joints_on() {
4125            // The two caps share their structure (one make_revolution each).
4126            let (ju, jv) = (&back_joints.0, &back_joints.1);
4127            debug_assert_eq!(back_joints, front_joints);
4128            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
4129                let p = inverse(frag(curve.evaluate(t), "point")?);
4130                Ok([p.x, p.y])
4131            };
4132            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, ju, jv, curve)? {
4133                return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
4134            }
4135        }
4136        let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "cap_pcurve")?;
4137        if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
4138    };
4139    let mut shell = Shell::new();
4140    let (vn, vs) = (shell.vertex(north), shell.vertex(south));
4141    let k0 = shell.edge(outer.clone(), vs, vn, false)?;
4142    let k1 = shell.edge(outer_end.clone(), vs, vn, false)?;
4143    let c = shell.edge(meet.clone(), vs, vn, false)?;
4144    let ds = shell.edge(frag(make_line(south, south), "point")?, vs, vs, true)?;
4145    let dn = shell.edge(frag(make_line(north, north), "point")?, vn, vn, true)?;
4146    // Wall: u turns, v runs S -> N; outward needs v the other way round the
4147    // circle's normal, so test and pick the loop's sense.
4148    let wall_outward = {
4149        let p = frag(wall.evaluate(0.5, 0.5), "probe")?;
4150        let su = frag(wall.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(wall.evaluate(0.5 - 1e-6, 0.5), "probe")?);
4151        let sv = frag(wall.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(wall.evaluate(0.5, 0.5 - 1e-6), "probe")?);
4152        su.cross(sv).dot(p.sub(foot(p))) > 0.0
4153    };
4154    let [g0, g1] = frag(outer.domain(), "domain")?;
4155    let wall_loop = vec![
4156        (ds, true, uv_line([0.0, g0], [1.0, g0])?),
4157        (k1, true, uv_line([1.0, g0], [1.0, g1])?),
4158        (dn, true, uv_line([1.0, g1], [0.0, g1])?),
4159        (k0, false, uv_line([0.0, g1], [0.0, g0])?),
4160    ];
4161    let reversed = |list: Vec<(u64, bool, NurbsCurve)>| -> Result<Vec<(u64, bool, NurbsCurve)>, KernelRefusal> {
4162        list.into_iter().rev().map(|(e, f, p)| Ok((e, !f, frag(p.reversed(), "reversed")?))).collect()
4163    };
4164    shell.face(wall.clone(), if wall_outward { wall_loop } else { reversed(wall_loop)? });
4165    // Caps: loop (grazing arc S -> N, then the meeting arc N -> S), sense by
4166    // the signed area of its parameters (the charts' u × v points outward).
4167    for (surface, inverse, k_edge, k_curve) in [(back, &back_inverse, k0, &outer), (front, &front_inverse, k1, &outer_end)] {
4168        let mut lp = vec![(k_edge, true, pcurve(inverse.as_ref(), k_curve, true)?), (c, false, pcurve(inverse.as_ref(), &meet, false)?)];
4169        let mut area = 0.0;
4170        for (_, _, pc) in &lp {
4171            let [d0, d1] = frag(pc.domain(), "domain")?;
4172            for j in 0..64 {
4173                let (a, b) = (frag(pc.evaluate(d0 + (d1 - d0) * j as f64 / 64.0), "uv")?, frag(pc.evaluate(d0 + (d1 - d0) * (j + 1) as f64 / 64.0), "uv")?);
4174                area += a.x * b.y - b.x * a.y;
4175            }
4176        }
4177        if area < 0.0 {
4178            lp = reversed(lp)?;
4179        }
4180        shell.face(surface, lp);
4181    }
4182    let body = shell.solid();
4183    let issues = body.validate();
4184    if !issues.is_empty() {
4185        return Err(refuse("assembly", format!("the turned ball's sweep is not valid: {:?}", issues.first())));
4186    }
4187    let probe = Split { points: Vec::new(), curves: Vec::new(), caps: Vec::new(), slides: Vec::new(), slide_sides: Vec::new(), scale: r + rho, shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() } };
4188    check_single_pass(screw, &probe, &body, &std::collections::HashSet::new())?;
4189    Ok(Some(body))
4190}
4191
4192/// A frame riding a cubic Bézier curve (`control`, in a plane square to
4193/// `up`): its origin on the curve, its first axis along the curve's tangent,
4194/// `up` fixed. The tool is given in the frame at the curve's start and carried
4195/// by it over the whole curve.
4196#[derive(Clone, Copy, Debug)]
4197pub struct FrameCurve {
4198    pub control: [Vec3; 4],
4199    pub up: Vec3,
4200}
4201
4202/// The whole sweep of a solid of revolution carried by a frame along a
4203/// curve. In the riding frame the velocity field is the speed along the
4204/// tangent plus the turn about `up`, so the grazing loop moves on the tool with
4205/// the curve's curvature. It is split at sample times (its structure must not
4206/// change), each piece sampled exactly, and the walls lofted through those
4207/// samples (quintic both ways; the samples' count doubles until the wall is
4208/// within `LOFT_TARGET` of the exact loop at the times between). Caps are the tool's
4209/// back at the start and front at the end.
4210pub fn sweep_solid_along(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4211    // An upright solid of revolution on a planar curve is translated by it:
4212    // its sweep is the planar distance to the curve within the tool's radius,
4213    // folds and crossings included (`BREP_SWEEP_UPRIGHT_SLOT`). With the
4214    // direct build on (`BREP_SWEEP_UPRIGHT_DIRECT`) the route answers only
4215    // where the general routes refuse and the curve may turn tighter than the
4216    // tool, built face by face; every sweep the general routes build is theirs
4217    // as before, and where the direct build declines their refusal stands.
4218    // With the direct build off the route takes every upright sweep.
4219    if crate::solid_sweep_upright::upright_slot_on() {
4220        if let Some(slot) = crate::solid_sweep_upright::upright_slot(tool, path) {
4221            if !crate::solid_sweep_upright::upright_direct_on() {
4222                return slot.solid();
4223            }
4224            let general = sweep_solid_along_general(tool, path);
4225            if general.is_err() && slot.turns_tighter() {
4226                if let Ok(solid) = slot.direct_solid() {
4227                    return Ok(solid);
4228                }
4229            }
4230            return general;
4231        }
4232    }
4233    sweep_solid_along_general(tool, path)
4234}
4235
4236/// [`sweep_solid_along`] by its general routes (the planar ring, the lofted
4237/// grazing loop), without the upright route.
4238fn sweep_solid_along_general(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4239    // A ring on a planar curve, from its slices (`BREP_SWEEP_PLANAR_RING`).
4240    if let Some(ring) = crate::solid_sweep_planar_ring::planar_ring_on().then(|| crate::solid_sweep_planar_ring::planar_ring_sweep(tool, path)).flatten() {
4241        return ring;
4242    }
4243    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
4244    let base = path.control[0];
4245    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
4246        return Err(input("plane", "the curve is not in a plane square to up".into()));
4247    }
4248    let tangent = path.control[1].sub(base);
4249    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
4250    let start_tangent = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
4251    let frame = Frame { control: path.control, up, start_tangent };
4252    let (mut speed, mut rate, mut extent) = (0.0f64, 0.0f64, 0.0f64);
4253    let mut previous = 0.0;
4254    for k in 0..=512 {
4255        let t = k as f64 / 512.0;
4256        let first = frame.first(t);
4257        if first.length() <= 1e-12 {
4258            return Err(input("tangent", "the curve stops (zero tangent)".into()));
4259        }
4260        speed = speed.max(first.length());
4261        rate = rate.max(frame.angle_rate(t).abs());
4262        extent = extent.max(frame.point(t).sub(base).length());
4263        let angle = frame.angle(t);
4264        if (angle - previous).abs() > 0.5 {
4265            return Err(refuse("frame_turns", "the frame turns half way round".into()));
4266        }
4267        previous = angle;
4268    }
4269    let screw = Screw { a: base, e: up, omega: rate, c: speed, c2: 0.0, t0: 0.0, t1: 1.0, frame: Some(frame), turns: None, frozen: None,
4270        loop_samples: LOFT_SAMPLES, extent };
4271    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
4272        return Err(refuse("along_tool", "a frame along a curve carries a solid of revolution only".into()));
4273    };
4274    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
4275    // The splits name their pieces by angle about the tool's axis from its
4276    // radial direction: a grazing angle passing that reference renames them,
4277    // so try a few references.
4278    let mut last = None;
4279    for k in 0..8 {
4280        let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
4281        match lofted(&screw, *axis_origin, axis, reference, meridian) {
4282            Err(error) if refused_as(&error) == Some("loft_structure") => last = Some(error),
4283            other => return other,
4284        }
4285    }
4286    Err(last.expect("tried"))
4287}
4288
4289/// The whole sweep of a prism carried by a frame along a planar curve (its
4290/// axis along the frame's up): the prism `outline` (a convex polygon in the
4291/// start frame: first coordinate along the start tangent, second along
4292/// up × tangent) between `from` and `to` along up. The motion is planar, so the
4293/// sweep is the plane region the moving outline covers, extruded. That region
4294/// is found exactly: its boundary lies on the outline's corner paths, the paths
4295/// of each edge's grazing point (where the edge's normal is square to the
4296/// velocity), and the outline's edges at the two ends; these are split where
4297/// they meet, and a piece is kept where one side of it is covered and the other
4298/// not (folds, where a corner digs past a side, come out right).
4299pub fn sweep_prism_along(outline: &[[f64; 2]], from: f64, to: f64, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4300    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
4301    let base = path.control[0];
4302    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
4303        return Err(input("plane", "the curve is not in a plane square to up".into()));
4304    }
4305    let tangent = path.control[1].sub(base);
4306    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
4307    let e1 = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
4308    let e2 = up.cross(e1);
4309    let frame = Frame { control: path.control, up, start_tangent: e1 };
4310    // The frame in plane coordinates: origin c(s), turned by φ(s).
4311    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
4312    let pose = |s: f64| (flat(frame.point(s)), frame.angle(s));
4313    let rates = |s: f64| {
4314        let first = frame.first(s);
4315        ([first.dot(e1), first.dot(e2)], frame.angle_rate(s))
4316    };
4317    prism_region_sweep(outline, from, to, base, e1, e2, up, &pose, &rates, false)
4318}
4319
4320/// The whole sweep of a prism (the convex polygon `outline` in the plane
4321/// through `base` spanned by `e1`, `e2`, between `from` and `to` along `up`)
4322/// under a planar rigid motion: at s ∈ [0, 1] a point q of the plane (in the
4323/// tool's own coordinates) is at origin(s) + R(angle(s)) q, `pose` giving
4324/// (origin, angle) and `rates` their derivatives in s. The sweep is the plane
4325/// region the moving outline covers, extruded. That region is found exactly:
4326/// its boundary lies on the outline's corner paths, the paths of each edge's
4327/// grazing point (where the edge's normal is square to the velocity), and,
4328/// unless the motion is `closed` (it ends where it starts), the outline's
4329/// edges at the two ends; these are split where they meet or cross
4330/// themselves, and a piece is kept where one side of it is covered and the
4331/// other not. The region may have holes.
4332#[allow(clippy::too_many_arguments)]
4333pub fn prism_region_sweep(
4334    outline: &[[f64; 2]],
4335    from: f64,
4336    to: f64,
4337    base: Vec3,
4338    e1: Vec3,
4339    e2: Vec3,
4340    up: Vec3,
4341    pose: &dyn Fn(f64) -> ([f64; 2], f64),
4342    rates: &dyn Fn(f64) -> ([f64; 2], f64),
4343    closed: bool,
4344) -> Result<BrepSolid, KernelRefusal> {
4345    if outline.len() < 3 || !(to > from) {
4346        return Err(input("prism", "a prism needs three corners and a positive height".into()));
4347    }
4348    // Counter-clockwise, convex.
4349    let n = outline.len();
4350    let mut corners = outline.to_vec();
4351    let area: f64 = (0..n).map(|k| corners[k][0] * corners[(k + 1) % n][1] - corners[(k + 1) % n][0] * corners[k][1]).sum();
4352    if area < 0.0 {
4353        corners.reverse();
4354    }
4355    for k in 0..n {
4356        let (a, b, c) = (corners[k], corners[(k + 1) % n], corners[(k + 2) % n]);
4357        if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= 0.0 {
4358            return Err(input("prism", "the outline is not convex".into()));
4359        }
4360    }
4361    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
4362    let place = |s: f64, q: [f64; 2]| -> [f64; 2] {
4363        let (o, angle) = pose(s);
4364        let (sn, cs) = angle.sin_cos();
4365        [o[0] + cs * q[0] - sn * q[1], o[1] + sn * q[0] + cs * q[1]]
4366    };
4367    let local = |s: f64, p: [f64; 2]| -> [f64; 2] {
4368        let (o, angle) = pose(s);
4369        let (sn, cs) = angle.sin_cos();
4370        let d = [p[0] - o[0], p[1] - o[1]];
4371        [cs * d[0] + sn * d[1], -sn * d[0] + cs * d[1]]
4372    };
4373    // Edges: outward normals and offsets in the start frame.
4374    let edges: Vec<([f64; 2], f64)> = (0..n)
4375        .map(|k| {
4376            let (a, b) = (corners[k], corners[(k + 1) % n]);
4377            let d = [b[0] - a[0], b[1] - a[1]];
4378            let length = d[0].hypot(d[1]);
4379            let normal = [d[1] / length, -d[0] / length];
4380            (normal, normal[0] * a[0] + normal[1] * a[1])
4381        })
4382        .collect();
4383    let inside = |q: [f64; 2]| edges.iter().map(|(nn, d)| nn[0] * q[0] + nn[1] * q[1] - d).fold(f64::NEG_INFINITY, f64::max);
4384    // Is p covered at some time? The least signed distance over the motion.
4385    let depth = |p: [f64; 2]| -> f64 {
4386        let samples = 2000;
4387        let f = |s: f64| inside(local(s, p));
4388        let mut best = (f64::INFINITY, 0usize);
4389        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4390        for (k, &v) in values.iter().enumerate() {
4391            if v < best.0 {
4392                best = (v, k);
4393            }
4394        }
4395        // Refine every local minimum near the least.
4396        let mut least = best.0;
4397        for k in 0..=samples {
4398            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4399            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4400            if values[k] <= left && values[k] <= right && values[k] < best.0 + 1e-3 * scale {
4401                let (mut lo, mut hi) = (((k as f64) - 1.0).max(0.0) / samples as f64, ((k as f64) + 1.0).min(samples as f64) / samples as f64);
4402                for _ in 0..80 {
4403                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4404                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4405                }
4406                least = least.min(f(0.5 * (lo + hi)));
4407            }
4408        }
4409        least
4410    };
4411    // Candidate boundary paths, each a map [0, 1] -> plane.
4412    #[derive(Clone, Copy)]
4413    enum Path {
4414        Corner(usize),
4415        /// Edge k's grazing point over the times [s0, s1].
4416        Graze(usize, f64, f64),
4417        /// Edge k at the start (false) or end (true).
4418        End(usize, bool),
4419    }
4420    // Where along edge k's line (0 at its start corner, 1 at its end) the
4421    // grazing point is at s, on the edge or beyond it.
4422    let graze_at = |k: usize, s: f64| -> Option<f64> {
4423        // Along edge k at x (in the tool's coordinates) the velocity's part
4424        // along the edge's normal n is w·n + φ' (ẑ × x)·n, w the origin's
4425        // velocity read in the tool's frame.
4426        let (a, b) = (corners[k], corners[(k + 1) % n]);
4427        let (nn, _) = edges[k];
4428        let (velocity, rate) = rates(s);
4429        let (sn, cs) = pose(s).1.sin_cos();
4430        let w = [cs * velocity[0] + sn * velocity[1], -sn * velocity[0] + cs * velocity[1]];
4431        let along = w[0] * nn[0] + w[1] * nn[1];
4432        let rot = |x: [f64; 2]| -x[1] * nn[0] + x[0] * nn[1]; // (ẑ × x)·n
4433        // An edge the origin moves along grazes where (ẑ × x)·n = 0 whatever
4434        // the turning rate (also where it is zero, at an inflection).
4435        let (ga, gb) = if along.abs() < 1e-15 * w[0].hypot(w[1]) { (rot(a), rot(b)) } else { (along + rate * rot(a), along + rate * rot(b)) };
4436        if ga == gb {
4437            return None;
4438        }
4439        Some(ga / (ga - gb))
4440    };
4441    let graze_point = |k: usize, s: f64| -> Option<f64> { graze_at(k, s).filter(|&u| u > 0.0 && u < 1.0) };
4442    let mut paths: Vec<Path> = (0..n).map(Path::Corner).collect();
4443    // Where a grazing point enters or leaves its edge it is at a corner:
4444    // (that corner, the time), a place its path is split at.
4445    let mut junctions: Vec<(usize, f64)> = Vec::new();
4446    for k in 0..n {
4447        // Where along the motion edge k has a grazing point inside it, each
4448        // run's ends found where the point passes a corner.
4449        let steps = 2000;
4450        let mut run: Option<f64> = None;
4451        let mut passes = |inside: f64, outside: f64| -> f64 {
4452            let (mut a, mut b) = (inside, outside);
4453            for _ in 0..80 {
4454                let mid = 0.5 * (a + b);
4455                if graze_point(k, mid).is_some() { a = mid } else { b = mid }
4456            }
4457            let corner = if graze_at(k, a).is_some_and(|u| u < 0.5) { k } else { (k + 1) % n };
4458            junctions.push((corner, a));
4459            a
4460        };
4461        for j in 0..=steps {
4462            let s = j as f64 / steps as f64;
4463            let on = graze_point(k, s).is_some();
4464            match (on, run) {
4465                (true, None) => run = Some(if j == 0 { s } else { passes(s, s - 1.0 / steps as f64) }),
4466                (false, Some(s0)) => {
4467                    paths.push(Path::Graze(k, s0, passes(s - 1.0 / steps as f64, s)));
4468                    run = None;
4469                }
4470                _ => {}
4471            }
4472        }
4473        if let Some(s0) = run {
4474            paths.push(Path::Graze(k, s0, 1.0));
4475        }
4476        if !closed {
4477            paths.push(Path::End(k, false));
4478            paths.push(Path::End(k, true));
4479        }
4480    }
4481    let eval = |path: Path, t: f64| -> [f64; 2] {
4482        match path {
4483            Path::Corner(k) => place(t, corners[k]),
4484            Path::Graze(k, s0, s1) => {
4485                let s = s0 + (s1 - s0) * t;
4486                let u = graze_at(k, s).map_or(0.5, |u| u.clamp(0.0, 1.0));
4487                let (a, b) = (corners[k], corners[(k + 1) % n]);
4488                place(s, [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u])
4489            }
4490            Path::End(k, at_end) => {
4491                let (a, b) = (corners[k], corners[(k + 1) % n]);
4492                place(if at_end { 1.0 } else { 0.0 }, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])
4493            }
4494        }
4495    };
4496    let count = paths.len();
4497    region_from_paths(
4498        count,
4499        &|index: usize, t: f64| eval(paths[index], t),
4500        &|index: usize| matches!(paths[index], Path::End(..)),
4501        &|_: usize| closed,
4502        &junctions,
4503        &depth,
4504        scale,
4505        (base, e1, e2, up),
4506        (from, to),
4507    )
4508}
4509
4510/// Everything a tube (the ball of `radius` swept along the curve
4511/// `centreline(s)`, s ∈ [0, 1], its ends included) passes through as it slides
4512/// by `slide`, inside the slab `slab[0] ≤ (x − slab_origin)·n ≤ slab[1]` (`n` =
4513/// `slab_normal` normalised), which the tube must cross wholly: before the
4514/// slab at the start, past it at the end (checked at 8001 points of the
4515/// centreline, with a margin of the longest step between them). The
4516/// returned prism along the slide agrees with the sweep inside the slab; the
4517/// caller cuts a workpiece that lies within it.
4518///
4519/// The centreline must be resolved by its samples (as every path of the plane
4520/// region arrangement is): smooth, its height changing between two of the
4521/// 8001 checking samples by no more than the step between them, so that the
4522/// samples bound it. A curve that wanders between samples is outside this
4523/// contract.
4524///
4525/// Why a prism: a point x of the slab is in the sweep iff the line through x
4526/// along the slide meets the tube. If it does, `n·` grows along the line, so
4527/// its topmost point y of the starting tube lies before x, and y + slide (a
4528/// point of the final tube) past it: x − y is a multiple of the slide in
4529/// [0, 1). So the sweep in the slab is the slab's part of the prism over the
4530/// tube's shadow along the slide: in the plane square to it the union of the
4531/// discs of `radius` about the shadow γ of the centreline. That region is
4532/// bounded by γ's two offset curves (each disc's grazing points, γ ± radius
4533/// along its normal) and the end discs' circles, built exactly by the plane
4534/// region arrangement of [`sweep_prism_along`].
4535pub fn sweep_tube_slid_across(
4536    centreline: &dyn Fn(f64) -> Vec3,
4537    radius: f64,
4538    slide: Vec3,
4539    slab_origin: Vec3,
4540    slab_normal: Vec3,
4541    slab: [f64; 2],
4542) -> Result<BrepSolid, KernelRefusal> {
4543    if !(radius.is_finite() && radius > 0.0) {
4544        return Err(input("tube_radius", "the tube's radius must be positive".into()));
4545    }
4546    let up = slide.normalized().map_err(|_| input("slide", "the slide has no length".into()))?;
4547    let normal = slab_normal.normalized().map_err(|_| input("slab", "the slab's normal has no direction".into()))?;
4548    if !(slab[1] > slab[0]) || up.dot(normal).abs() < 1e-9 {
4549        return Err(input("slab", "the slab must have thickness and the slide must cross it".into()));
4550    }
4551    // Orient so the slide runs up the slab's normal.
4552    let (normal, slab) = if up.dot(normal) > 0.0 { (normal, slab) } else { (normal.scale(-1.0), [-slab[1], -slab[0]]) };
4553    let points: Vec<Vec3> = (0..=8000).map(|k| centreline(k as f64 / 8000.0)).collect();
4554    if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) {
4555        return Err(input("centreline", "the centreline has a point that is not finite".into()));
4556    }
4557    let step = points.windows(2).map(|w| w[1].sub(w[0]).length()).fold(0.0f64, f64::max);
4558    let heights: Vec<f64> = points.iter().map(|q| q.sub(slab_origin).dot(normal)).collect();
4559    let (low, high) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &h| (a.min(h), b.max(h)));
4560    let rise = slide.dot(normal);
4561    if !(high + radius + step < slab[0] && low - radius - step + rise > slab[1]) {
4562        return Err(refuse("tube_slab", "the tube does not pass wholly through the slab (it starts or ends within reach of it)".into()));
4563    }
4564    let e1 = {
4565        let seed = if up.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
4566        seed.sub(up.scale(seed.dot(up))).normalized().map_err(|_| input("slide", "no frame".into()))?
4567    };
4568    let e2 = up.cross(e1);
4569    // The plane's origin on the centreline itself, so that every tolerance
4570    // reads the tube's own size, wherever it lies.
4571    let base = points[0];
4572    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
4573    let centre = |s: f64| -> [f64; 2] { flat(centreline(s)) };
4574    let velocity = |s: f64| -> [f64; 2] {
4575        let h = 1e-7;
4576        let (a, b) = ((s - h).max(0.0), (s + h).min(1.0));
4577        let (p, q) = (centre(a), centre(b));
4578        [(q[0] - p[0]) / (b - a), (q[1] - p[1]) / (b - a)]
4579    };
4580    // The shadow must keep moving (a disc standing still has no grazing points).
4581    for k in 0..=2000 {
4582        let w = velocity(k as f64 / 2000.0);
4583        if w[0].hypot(w[1]) < 1e-9 * (1.0 + radius) {
4584            return Err(refuse("tube_shadow", "the tube's shadow along the slide stops (its centreline runs along the slide)".into()));
4585        }
4586    }
4587    // Tolerances read the tube's radius (a probe beside a boundary must stay
4588    // within the tube), never more than its extent; a tube longer than 1e6
4589    // radii is beyond what the coordinates resolve at that size.
4590    let extent = (0..=64).map(|k| { let c = centre(k as f64 / 64.0); c[0].hypot(c[1]) }).fold(radius, f64::max);
4591    if extent > 1e6 * radius {
4592        return Err(refuse("tube_shadow", "the tube is too long for its radius (over a million radii)".into()));
4593    }
4594    let scale = extent.min(1e3 * radius);
4595    // Paths: the two offset curves, then the two end circles.
4596    let eval = |index: usize, t: f64| -> [f64; 2] {
4597        match index {
4598            0 | 1 => {
4599                let c = centre(t);
4600                let w = velocity(t);
4601                let length = w[0].hypot(w[1]);
4602                let side = if index == 0 { 1.0 } else { -1.0 };
4603                [c[0] - side * radius * w[1] / length, c[1] + side * radius * w[0] / length]
4604            }
4605            _ => {
4606                let c = centre(if index == 2 { 0.0 } else { 1.0 });
4607                let angle = TAU * t;
4608                [c[0] + radius * angle.cos(), c[1] + radius * angle.sin()]
4609            }
4610        }
4611    };
4612    // Inside: nearer than `radius` to the shadow at some time.
4613    let depth = |p: [f64; 2]| -> f64 {
4614        let samples = 4000;
4615        let f = |s: f64| { let c = centre(s); (p[0] - c[0]).hypot(p[1] - c[1]) - radius };
4616        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4617        let mut least = values.iter().cloned().fold(f64::INFINITY, f64::min);
4618        for k in 0..=samples {
4619            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4620            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4621            if values[k] <= left && values[k] <= right && values[k] < least + 1e-3 * scale {
4622                let (mut lo, mut hi) = (((k as f64) - 1.0).max(0.0) / samples as f64, ((k as f64) + 1.0).min(samples as f64) / samples as f64);
4623                for _ in 0..80 {
4624                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4625                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4626                }
4627                least = least.min(f(0.5 * (lo + hi)));
4628            }
4629        }
4630        least
4631    };
4632    // The prism spans the slab's crossing of every line through the region:
4633    // from below the starting tube to past the final one, along the slide.
4634    let (a0, a1) = points.iter().map(|q| q.sub(base).dot(up)).fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(h), b.max(h)));
4635    let margin = radius + step + 1e-3 * scale;
4636    // Each offset curve ends on its end circle, tangent to it there (both run
4637    // along the velocity), which no crossing test finds: split the circles at
4638    // those points (the angles of ±the normal there).
4639    let mut touches: Vec<(usize, f64)> = Vec::new();
4640    for (circle, s) in [(2usize, 0.0f64), (3, 1.0)] {
4641        let w = velocity(s);
4642        for side in [1.0f64, -1.0] {
4643            let angle = (side * w[0]).atan2(-side * w[1]);
4644            touches.push((circle, angle.rem_euclid(TAU) / TAU));
4645        }
4646    }
4647    region_from_paths(
4648        4,
4649        &eval,
4650        &|_| false,
4651        &|index| index >= 2,
4652        &touches,
4653        &depth,
4654        scale,
4655        (base, e1, e2, up),
4656        (a0 - margin, a1 + slide.length() + margin),
4657    )
4658}
4659
4660/// The crossing search's box culling in [`region_from_paths`]
4661/// (`BREP_SWEEP_REGION_CROSS_BOXES`, default on; `=0` visits every segment
4662/// pair, the same crossings found more slowly: square-on-a-planet-carrier
4663/// tests 74.4M pairs without it, 0.75M with it, for the same 74 Newton runs).
4664fn region_cross_boxes_on() -> bool {
4665    crate::switch!("BREP_SWEEP_REGION_CROSS_BOXES", true)
4666}
4667
4668/// The plane region bounded by pieces of the candidate `count` paths (each
4669/// `eval(index, t)`, t ∈ [0, 1]), extruded along `up` from `heights.0` to
4670/// `heights.1`: the paths are split where they cross each other or
4671/// themselves (and at `extra_cuts`), a piece is kept where `depth` (negative
4672/// inside the region) reads one side covered and the other not, and the kept
4673/// pieces chain into one outer loop and its holes. `straight_path(index)`: the
4674/// path is a segment (built as a line); `closed_path(index)`: its two ends
4675/// meet (neighbours for the self-crossing test).
4676#[allow(clippy::too_many_arguments)]
4677fn region_from_paths(
4678    count: usize,
4679    eval: &dyn Fn(usize, f64) -> [f64; 2],
4680    straight_path: &dyn Fn(usize) -> bool,
4681    closed_path: &dyn Fn(usize) -> bool,
4682    extra_cuts: &[(usize, f64)],
4683    depth: &dyn Fn([f64; 2]) -> f64,
4684    scale: f64,
4685    frame: (Vec3, Vec3, Vec3, Vec3),
4686    heights: (f64, f64),
4687) -> Result<BrepSolid, KernelRefusal> {
4688    let (base, e1, e2, up) = frame;
4689    let (from, to) = heights;
4690    // Split parameters: mutual crossings (polyline, then Newton), and each
4691    // path's ends lying on another.
4692    let m = 400;
4693    let polylines: Vec<Vec<[f64; 2]>> = (0..count).map(|p| (0..=m).map(|i| eval(p, i as f64 / m as f64)).collect()).collect();
4694    let mut cuts: Vec<Vec<f64>> = vec![vec![0.0, 1.0]; count];
4695    let tol = 1e-10 * scale;
4696    // Under `BREP_SWEEP_REGION_CROSS_BOXES` the segment pairs are visited
4697    // chunk by chunk (16 segments each), a chunk pair only where their boxes,
4698    // grown by 1e-6 of the scale and by the pair test's own reach past a
4699    // segment's ends, overlap: a crossing the test takes lies in both boxes,
4700    // and none is missed. The cuts are
4701    // sorted after, so the order they are found in does not matter.
4702    const CHUNK: usize = 16;
4703    let boxed = region_cross_boxes_on();
4704    let chunks = (m + CHUNK - 1) / CHUNK;
4705    let grow = 1e-6 * scale;
4706    let boxes: Vec<Vec<[f64; 4]>> = polylines
4707        .iter()
4708        .filter(|_| boxed)
4709        .map(|line| {
4710            (0..chunks)
4711                .map(|c| {
4712                    let (lo, hi) = (c * CHUNK, ((c + 1) * CHUNK).min(m));
4713                    let b = line[lo..=hi].iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
4714                    // The pair test takes a crossing up to 1e-9 of a segment's
4715                    // length past its end: grow by twice that of the chunk's
4716                    // longest segment, so every crossing it takes lies in both
4717                    // segments' boxes.
4718                    let longest = line[lo..=hi].windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).fold(0.0f64, f64::max);
4719                    let g = grow + 2e-9 * longest;
4720                    [b[0] - g, b[1] - g, b[2] + g, b[3] + g]
4721                })
4722                .collect()
4723        })
4724        .collect();
4725    let overlap = |a: &[f64; 4], b: &[f64; 4]| a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
4726    for a in 0..count {
4727        for b in a..count {
4728            // One segment pair: a crossing of the polylines, polished by Newton on the exact paths.
4729            let mut test = |i: usize, j: usize| {
4730                    // A path against itself: only where it crosses over
4731                    // (stretches apart along it; a closed path's ends are
4732                    // neighbours too).
4733                    if a == b && (j < i + 3 || (closed_path(a) && i < 3 && j + 3 > m)) {
4734                        return;
4735                    }
4736                    let (p0, p1, q0, q1) = (polylines[a][i], polylines[a][i + 1], polylines[b][j], polylines[b][j + 1]);
4737                    let d1 = [p1[0] - p0[0], p1[1] - p0[1]];
4738                    let d2 = [q1[0] - q0[0], q1[1] - q0[1]];
4739                    let det = d1[0] * d2[1] - d1[1] * d2[0];
4740                    if det.abs() < 1e-300 {
4741                        return;
4742                    }
4743                    let r = [q0[0] - p0[0], q0[1] - p0[1]];
4744                    let (x, y) = ((r[0] * d2[1] - r[1] * d2[0]) / det, (r[0] * d1[1] - r[1] * d1[0]) / det);
4745                    if !(-1e-9..=1.0 + 1e-9).contains(&x) || !(-1e-9..=1.0 + 1e-9).contains(&y) {
4746                        return;
4747                    }
4748                    // Newton on the exact paths.
4749                    let (mut ta, mut tb) = ((i as f64 + x) / m as f64, (j as f64 + y) / m as f64);
4750                    for _ in 0..50 {
4751                        let (pa, pb) = (eval(a, ta), eval(b, tb));
4752                        let h = 1e-7;
4753                        let da = { let q = eval(a, (ta + h).min(1.0)); let p = eval(a, (ta - h).max(0.0)); let w = (ta + h).min(1.0) - (ta - h).max(0.0); [(q[0] - p[0]) / w, (q[1] - p[1]) / w] };
4754                        let db = { let q = eval(b, (tb + h).min(1.0)); let p = eval(b, (tb - h).max(0.0)); let w = (tb + h).min(1.0) - (tb - h).max(0.0); [(q[0] - p[0]) / w, (q[1] - p[1]) / w] };
4755                        let f = [pa[0] - pb[0], pa[1] - pb[1]];
4756                        let det = -da[0] * db[1] + da[1] * db[0];
4757                        if det.abs() < 1e-300 {
4758                            break;
4759                        }
4760                        let dta = (-f[0] * db[1] + f[1] * db[0]) / det;
4761                        let dtb = (da[0] * f[1] - da[1] * f[0]) / det;
4762                        ta = (ta - dta).clamp(0.0, 1.0);
4763                        tb = (tb - dtb).clamp(0.0, 1.0);
4764                        if dta.abs() + dtb.abs() < 1e-15 {
4765                            break;
4766                        }
4767                    }
4768                    let (pa, pb) = (eval(a, ta), eval(b, tb));
4769                    if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < tol && !(a == b && (ta - tb).abs() < 1.0 / m as f64) {
4770                        cuts[a].push(ta);
4771                        cuts[b].push(tb);
4772                    }
4773            };
4774            if boxed {
4775                // Only the segment pairs of chunks whose boxes overlap.
4776                for ca in 0..chunks {
4777                    for cb in 0..chunks {
4778                        if !overlap(&boxes[a][ca], &boxes[b][cb]) {
4779                            continue;
4780                        }
4781                        for i in ca * CHUNK..((ca + 1) * CHUNK).min(m) {
4782                            for j in cb * CHUNK..((cb + 1) * CHUNK).min(m) {
4783                                test(i, j);
4784                            }
4785                        }
4786                    }
4787                }
4788            } else {
4789                for i in 0..m {
4790                    for j in 0..m {
4791                        test(i, j);
4792                    }
4793                }
4794            }
4795        }
4796    }
4797    // Extra splits the caller names (a corner's path where a grazing point passes it).
4798    for &(path, t) in extra_cuts {
4799        cuts[path].push(t);
4800    }
4801    for c in &mut cuts {
4802        c.sort_by(|x, y| x.total_cmp(y));
4803        c.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
4804    }
4805    // Pieces on the boundary: covered on exactly one side.
4806    struct Piece {
4807        path: usize,
4808        t0: f64,
4809        t1: f64,
4810    }
4811    let eps = 1e-7 * scale;
4812    let mut pieces: Vec<Piece> = Vec::new();
4813    for (index, c) in cuts.iter().enumerate() {
4814        for w in c.windows(2) {
4815            let (t0, t1) = (w[0], w[1]);
4816            if t1 - t0 < 1e-9 {
4817                continue;
4818            }
4819            let (pa, pb) = (eval(index, t0), eval(index, t1));
4820            if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < 1e-9 * scale {
4821                continue;
4822            }
4823            let tm = 0.5 * (t0 + t1);
4824            let (p, q) = (eval(index, tm), eval(index, (tm + 1e-6).min(1.0)));
4825            let d = [q[0] - p[0], q[1] - p[1]];
4826            let length = d[0].hypot(d[1]);
4827            if length == 0.0 {
4828                continue;
4829            }
4830            let left = [p[0] - d[1] / length * eps, p[1] + d[0] / length * eps];
4831            let right = [p[0] + d[1] / length * eps, p[1] - d[0] / length * eps];
4832            let (l, r) = (depth(left) < -1e-12 * scale, depth(right) < -1e-12 * scale);
4833            match (l, r) {
4834                (true, false) => pieces.push(Piece { path: index, t0, t1 }),
4835                (false, true) => pieces.push(Piece { path: index, t0: t1, t1: t0 }),
4836                _ => {}
4837            }
4838        }
4839    }
4840    // Chain into loops, the region on their left (the outer one runs
4841    // counter-clockwise, a hole's clockwise).
4842    if pieces.is_empty() {
4843        return Err(refuse("prism_along", "no boundary found".into()));
4844    }
4845    let mut used = vec![false; pieces.len()];
4846    let mut loops: Vec<Vec<usize>> = Vec::new();
4847    while let Some(first) = (0..pieces.len()).find(|&k| !used[k]) {
4848        let mut order = vec![first];
4849        used[first] = true;
4850        loop {
4851            let last = &pieces[*order.last().expect("order")];
4852            let end = eval(last.path, last.t1);
4853            let start = eval(pieces[order[0]].path, pieces[order[0]].t0);
4854            if (end[0] - start[0]).hypot(end[1] - start[1]) < 1e-8 * scale {
4855                break;
4856            }
4857            let next = (0..pieces.len()).filter(|&k| !used[k]).min_by(|&x, &y| {
4858                let (px, py) = (eval(pieces[x].path, pieces[x].t0), eval(pieces[y].path, pieces[y].t0));
4859                (px[0] - end[0]).hypot(px[1] - end[1]).total_cmp(&(py[0] - end[0]).hypot(py[1] - end[1]))
4860            });
4861            let Some(next) = next else {
4862                return Err(refuse("prism_along", "the boundary does not close".into()));
4863            };
4864            let p = eval(pieces[next].path, pieces[next].t0);
4865            if (p[0] - end[0]).hypot(p[1] - end[1]) > 1e-8 * scale {
4866                return Err(refuse("prism_along", format!("the boundary does not close (gap {:e})", (p[0] - end[0]).hypot(p[1] - end[1]))));
4867            }
4868            used[next] = true;
4869            order.push(next);
4870        }
4871        loops.push(order);
4872    }
4873    // The outer loop first: the one of greatest area.
4874    let area_of = |order: &Vec<usize>| -> f64 {
4875        let mut points: Vec<[f64; 2]> = Vec::new();
4876        for &k in order {
4877            let piece = &pieces[k];
4878            for i in 0..32 {
4879                points.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 32.0));
4880            }
4881        }
4882        (0..points.len()).map(|i| { let (a, b) = (points[i], points[(i + 1) % points.len()]); a[0] * b[1] - b[0] * a[1] }).sum::<f64>() * 0.5
4883    };
4884    let areas: Vec<f64> = loops.iter().map(area_of).collect();
4885    let outer = (0..loops.len()).max_by(|&x, &y| areas[x].abs().total_cmp(&areas[y].abs())).expect("loops");
4886    if areas[outer] <= 0.0 || (0..loops.len()).any(|k| k != outer && areas[k] >= 0.0) {
4887        return Err(refuse("prism_along", "the swept region is not one region with holes".into()));
4888    }
4889    loops.swap(0, outer);
4890    // Plane curves of the loops, then the extrusion.
4891    let world = |q: [f64; 2], h: f64| base.add(e1.scale(q[0])).add(e2.scale(q[1])).add(up.scale(h));
4892    let mut shell = Shell::new();
4893    let mut top_loops = Vec::with_capacity(loops.len());
4894    let mut bottom_loops = Vec::with_capacity(loops.len());
4895    let mut extent: Vec<[f64; 2]> = Vec::new();
4896    for order in &loops {
4897        let mut loop_points: Vec<[f64; 2]> = order.iter().map(|&k| eval(pieces[k].path, pieces[k].t0)).collect();
4898        loop_points.push(loop_points[0]);
4899        let count = order.len();
4900        let (bottom_v, top_v): (Vec<u64>, Vec<u64>) = (0..count).map(|k| (shell.vertex(world(loop_points[k], from)), shell.vertex(world(loop_points[k], to)))).unzip();
4901        let mut bottom_e = Vec::with_capacity(count);
4902        let mut top_e = Vec::with_capacity(count);
4903        let mut curves2d = Vec::with_capacity(count);
4904        for (slot, &k) in order.iter().enumerate() {
4905            let piece = &pieces[k];
4906            let straight = straight_path(piece.path);
4907            let next = (slot + 1) % count;
4908            for i in 0..=16 {
4909                extent.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 16.0));
4910            }
4911            let curve_at = |h: f64| -> Result<NurbsCurve, KernelRefusal> {
4912                if straight {
4913                    return frag(make_line(world(loop_points[slot], h), world(loop_points[next], h)), "line");
4914                }
4915                let samples = 192;
4916                let ts: Vec<f64> = (0..=samples).map(|i| i as f64 / samples as f64).collect();
4917                let mut points: Vec<Vec3> = ts.iter().map(|&t| world(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * t), h)).collect();
4918                points[0] = world(loop_points[slot], h);
4919                points[samples] = world(loop_points[next], h);
4920                frag(crate::interpolate_curve(&points, 5, &ts), "plane_path")
4921            };
4922            let (cb, ct) = (curve_at(from)?, curve_at(to)?);
4923            bottom_e.push(shell.edge(cb.clone(), bottom_v[slot], bottom_v[next], false)?);
4924            top_e.push(shell.edge(ct.clone(), top_v[slot], top_v[next], false)?);
4925            curves2d.push((cb, ct));
4926        }
4927        let verticals: Vec<u64> = (0..count).map(|k| shell.edge(make_line(world(loop_points[k], from), world(loop_points[k], to)).expect("line"), bottom_v[k], top_v[k], false)).collect::<Result<_, _>>()?;
4928        // Top (outward up) and bottom (outward down) loops.
4929        let mut coedges = Vec::with_capacity(count);
4930        for k in 0..count {
4931            coedges.push((top_e[k], true, plane_pcurve(world([0.0, 0.0], to), e1, e2, &curves2d[k].1, true)?));
4932        }
4933        top_loops.push(coedges);
4934        let mut coedges = Vec::with_capacity(count);
4935        for k in (0..count).rev() {
4936            coedges.push((bottom_e[k], false, plane_pcurve(world([0.0, 0.0], from), e2, e1, &curves2d[k].0, false)?));
4937        }
4938        bottom_loops.push(coedges);
4939        // Sides: the bottom curve extruded (u along it, v up), outward on its right.
4940        for k in 0..count {
4941            let next = (k + 1) % count;
4942            let (cb, _) = &curves2d[k];
4943            let rows: Vec<Vec<Vec4>> = cb
4944                .control_points
4945                .iter()
4946                .map(|p| {
4947                    let x = p.point().expect("point");
4948                    vec![Vec4::from_point(x, p.w), Vec4::from_point(x.add(up.scale(to - from)), p.w)]
4949                })
4950                .collect();
4951            let surface = frag(NurbsSurface::new(cb.degree, 1, cb.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows), "side")?;
4952            let [u0, u1] = frag(cb.domain(), "domain")?;
4953            let coedges = vec![
4954                (bottom_e[k], true, uv_line([u0, 0.0], [u1, 0.0])?),
4955                (verticals[next], true, uv_line([u1, 0.0], [u1, 1.0])?),
4956                (top_e[k], false, uv_line([u1, 1.0], [u0, 1.0])?),
4957                (verticals[k], false, uv_line([u0, 1.0], [u0, 0.0])?),
4958            ];
4959            shell.face(surface, coedges);
4960        }
4961    }
4962    let top_points: Vec<Vec3> = extent.iter().map(|&q| world(q, to)).collect();
4963    shell.face_loops(plane_patch(world([0.0, 0.0], to), e1, e2, &top_points)?, top_loops);
4964    let bottom_points: Vec<Vec3> = extent.iter().map(|&q| world(q, from)).collect();
4965    shell.face_loops(plane_patch(world([0.0, 0.0], from), e2, e1, &bottom_points)?, bottom_loops);
4966    let body = shell.solid();
4967    let issues = body.validate();
4968    if !issues.is_empty() {
4969        return Err(refuse("assembly", format!("the swept prism is not valid: {:?}", issues.first())));
4970    }
4971    Ok(body)
4972}
4973
4974/// A prism whose section is a convex polygon, carried by turns about axes
4975/// all along its own (a planar motion: a planet on its carrier) that ends
4976/// where it starts: its whole sweep (`prism_region_sweep`), or None when the
4977/// tool or motion is not of that kind. `steps`: each turn's axis point,
4978/// direction and rate, applied in order at every t ∈ [t0, t1].
4979#[allow(clippy::too_many_arguments)]
4980pub fn closed_planar_prism(
4981    origin: Vec3,
4982    normal: Vec3,
4983    x_axis: Vec3,
4984    outline: &[OutlinePiece],
4985    from: f64,
4986    to: f64,
4987    steps: &[(Vec3, Vec3, f64, f64)],
4988    t0: f64,
4989    t1: f64,
4990) -> Result<Option<BrepSolid>, KernelRefusal> {
4991    let Ok(up) = normal.normalized() else { return Ok(None) };
4992    let Ok(e1) = x_axis.sub(up.scale(x_axis.dot(up))).normalized() else { return Ok(None) };
4993    let e2 = up.cross(e1);
4994    // A polygon of straight sides, in order.
4995    let mut corners: Vec<[f64; 2]> = Vec::with_capacity(outline.len());
4996    for (k, piece) in outline.iter().enumerate() {
4997        let OutlinePiece::Line { from: a, to: b } = piece else { return Ok(None) };
4998        let OutlinePiece::Line { from: next, .. } = &outline[(k + 1) % outline.len()] else { return Ok(None) };
4999        if (b[0] - next[0]).hypot(b[1] - next[1]) > 1e-9 * (1.0 + b[0].hypot(b[1])) {
5000            return Ok(None);
5001        }
5002        corners.push(*a);
5003    }
5004    if corners.len() < 3 || steps.is_empty() || !(t1 > t0) {
5005        return Ok(None);
5006    }
5007    // Convex (either way round), or it is another engine's.
5008    let turn_of = |k: usize| {
5009        let (a, b, c) = (corners[k], corners[(k + 1) % corners.len()], corners[(k + 2) % corners.len()]);
5010        (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
5011    };
5012    let first_turn = turn_of(0);
5013    if first_turn == 0.0 || (1..corners.len()).any(|k| turn_of(k) * first_turn <= 0.0) {
5014        return Ok(None);
5015    }
5016    // Turns only, about axes along the prism's own: (centre in the plane, rate about +up).
5017    let mut turns: Vec<([f64; 2], f64)> = Vec::with_capacity(steps.len());
5018    for &(point, direction, turn, advance) in steps {
5019        let Ok(axis) = direction.normalized() else { return Ok(None) };
5020        if advance != 0.0 || axis.cross(up).length() > 1e-12 {
5021            return Ok(None);
5022        }
5023        let r = point.sub(origin);
5024        turns.push(([r.dot(e1), r.dot(e2)], turn * axis.dot(up).signum()));
5025    }
5026    let moved = |t: f64, q: [f64; 2]| -> [f64; 2] {
5027        let mut x = q;
5028        for &(c, rate) in &turns {
5029            let (sn, cs) = (rate * t).sin_cos();
5030            let d = [x[0] - c[0], x[1] - c[1]];
5031            x = [c[0] + cs * d[0] - sn * d[1], c[1] + sn * d[0] + cs * d[1]];
5032        }
5033        x
5034    };
5035    let total: f64 = turns.iter().map(|t| t.1).sum();
5036    // The turns compose to one rigid motion of the plane: a point q (where
5037    // it stands before any motion) is at moved(t, 0) + R(total t) q.
5038    let pose = |s: f64| -> ([f64; 2], f64) {
5039        let t = t0 + (t1 - t0) * s;
5040        (moved(t, [0.0, 0.0]), total * t)
5041    };
5042    // The turns are defined at every t, so the origin's velocity is a
5043    // centred difference at the motion's ends too.
5044    let rates = |s: f64| -> ([f64; 2], f64) {
5045        let h = 1e-6;
5046        let (pa, pb) = (pose(s - h).0, pose(s + h).0);
5047        ([(pb[0] - pa[0]) / (2.0 * h), (pb[1] - pa[1]) / (2.0 * h)], total * (t1 - t0))
5048    };
5049    // Ends where it starts: the same turn (mod 2π) and place.
5050    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
5051    let closes = corners.iter().all(|&c| {
5052        let (a, b) = (moved(t0, c), moved(t1, c));
5053        (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-9 * scale
5054    });
5055    if !closes {
5056        return Ok(None);
5057    }
5058    prism_region_sweep(&corners, from, to, origin, e1, e2, up, &pose, &rates, true).map(Some)
5059}
5060
5061/// Two turns driven by one parameter t: first by `rates[0]·t` about the
5062/// first axis (point, direction), then by `rates[1]·t` about the second; both
5063/// axes fixed in the world; t from `from` to `to`.
5064#[derive(Clone, Copy, Debug)]
5065pub struct TwoTurns {
5066    pub axes: [(Vec3, Vec3); 2],
5067    pub rates: [f64; 2],
5068    pub from: f64,
5069    pub to: f64,
5070}
5071
5072/// The whole sweep of a solid of revolution tumbled by two turns about skew
5073/// axes. The grazing loop moves on the tool (the instantaneous screw changes
5074/// with t), so the walls are lofted through exact samples. Where the tumble
5075/// passes over a point twice (the one-pass probe), the time is bisected into
5076/// spans each passing once, and the spans' sweeps are joined (consecutive
5077/// spans meet along a grazing loop; distant ones overlap).
5078pub fn sweep_solid_tumbled(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
5079    let solid = sweep_solid_tumbled_any_route(tool, motion)?;
5080    // A ring's sweep is recorded with its motion, so a boolean of two can
5081    // take the dedicated two-tube route (BREP_SWEEP_TUBE_BOOLEAN, default off).
5082    if crate::solid_sweep_tube::boolean::tube_boolean_on() {
5083        if let Some(tube) = ring_tube(tool, motion) {
5084            crate::solid_sweep_tube::boolean::record(&solid, tube);
5085        }
5086    }
5087    Ok(solid)
5088}
5089
5090fn sweep_solid_tumbled_any_route(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
5091    // A ring whose swept tube K bounds the solid outright, by the tube route
5092    // (BREP_SWEEP_TORUS_TUBE, default off); it declines anything else.
5093    if crate::solid_sweep_tube::torus_tube_on() {
5094        if let Some(tube) = ring_tube(tool, motion) {
5095            if let Ok(solid) = crate::solid_sweep_tube::sweep_torus_tube(&tube) {
5096                return Ok(solid);
5097            }
5098        }
5099    }
5100    let lofted = sweep_solid_tumbled_lofted(tool, motion);
5101    // A ring (a whole circle off its axis) the lofted walls refuse, by the
5102    // trim engine (BREP_SWEEP_RING_TRIM); the lofted refusal stands where it
5103    // refuses too. Rows the walls build are left to them.
5104    let Err(refusal) = lofted else {
5105        return lofted.map(|mut solid| {
5106            if cusp_first_on() {
5107                start_loops_at_cusps(&mut solid);
5108            }
5109            solid
5110        });
5111    };
5112    // A wall whose double curve reaches a corner: the trim route meets that
5113    // double curve's tip, which it does not yet write so a reader integrates
5114    // round it, and refuses after the work; declined before it.
5115    if !crate::solid_sweep_trim::ring_trim_on() || (refusal.to_string().contains(DOUBLE_CURVE_CORNER) && !crate::solid_sweep_trim::tip_splice_on()) {
5116        return Err(refusal);
5117    }
5118    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return Err(refusal) };
5119    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return Err(refusal) };
5120    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius) {
5121        return Err(refusal);
5122    }
5123    let (Ok(axis), Ok(d0), Ok(d1)) = (axis_direction.normalized(), motion.axes[0].1.normalized(), motion.axes[1].1.normalized()) else { return Err(refusal) };
5124    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
5125    let ring_centre = axis_origin.add(axis.scale(centre[1]));
5126    crate::solid_sweep_trim::sweep_ring_tumbled(ring_centre, axis, centre[0], *radius, &two, motion.from, motion.to).or(Err(refusal))
5127}
5128
5129/// `BREP_SWEEP_CUSP_FIRST` (on unless =0): each loop of a tumbled sweep starts
5130/// at its cusp corner, where it has one.
5131fn cusp_first_on() -> bool {
5132    crate::switch!("BREP_SWEEP_CUSP_FIRST", true)
5133}
5134
5135/// Each loop rotated to start at its cusp corner (a zero-angle corner: the
5136/// edge leaving it runs back along the edge arriving, within 0.05 rad), where
5137/// it has one; the sharpest such corner where it has several. Topology and
5138/// geometry are unchanged. A reader that places a loop on its surface by
5139/// inverting the edges' points, each edge seeded from the last one's end,
5140/// mislays a corner where an edge creeps into a cusp (its point all but still
5141/// while its parameters still move): from the cusp it starts clean.
5142pub(crate) fn start_loops_at_cusps(solid: &mut BrepSolid) {
5143    let ends: HashMap<u64, [(Vec3, Vec3); 2]> = solid
5144        .edges
5145        .iter()
5146        .filter_map(|e| {
5147            let span = e.t1 - e.t0;
5148            let at = |t: f64| e.curve.evaluate(t).ok();
5149            let (p0, p1) = (at(e.t0)?, at(e.t1)?);
5150            let (q0, q1) = (at(e.t0 + 1e-2 * span)?, at(e.t1 - 1e-2 * span)?);
5151            // (point, direction into the edge) at its start and at its end
5152            Some((e.id, [(p0, q0.sub(p0)), (p1, q1.sub(p1))]))
5153        })
5154        .collect();
5155    for face in solid.shells.iter_mut().flat_map(|s| s.faces.iter_mut()) {
5156        for l in face.loops.iter_mut() {
5157            let n = l.coedges.len();
5158            if n < 2 {
5159                continue;
5160            }
5161            let mut best: Option<(f64, usize)> = None;
5162            for k in 0..n {
5163                let (before, after) = (&l.coedges[(k + n - 1) % n], &l.coedges[k]);
5164                let (Some(b), Some(a)) = (ends.get(&before.edge_id), ends.get(&after.edge_id)) else { continue };
5165                // into the corner back along the edge arriving, and out along the edge leaving
5166                let back = if before.forward { b[1].1 } else { b[0].1 };
5167                let out = if after.forward { a[0].1 } else { a[1].1 };
5168                let (lb, lo) = (back.length(), out.length());
5169                if !(lb > 0.0 && lo > 0.0) {
5170                    continue;
5171                }
5172                let along = back.dot(out) / (lb * lo);
5173                if along > (0.05f64).cos() && best.map_or(true, |(x, _)| along > x) {
5174                    best = Some((along, k));
5175                }
5176            }
5177            if let Some((_, k)) = best {
5178                l.coedges.rotate_left(k);
5179            }
5180        }
5181    }
5182}
5183
5184/// The tube route's reading of a ring tool (a whole circle off its axis) under two turns.
5185fn ring_tube(tool: &SolidTool, motion: &TwoTurns) -> Option<crate::solid_sweep_tube::Tube> {
5186    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return None };
5187    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return None };
5188    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius && motion.from.is_finite() && motion.to > motion.from) {
5189        return None;
5190    }
5191    let (axis, d0, d1) = (axis_direction.normalized().ok()?, motion.axes[0].1.normalized().ok()?, motion.axes[1].1.normalized().ok()?);
5192    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
5193    crate::solid_sweep_tube::Tube::new(axis_origin.add(axis.scale(centre[1])), axis, centre[0], *radius, two, motion.from, motion.to)
5194}
5195
5196/// The lofted walls' refusal where a wall's double curve reaches a corner of
5197/// its grazing loop (the tumbled sweep reads it to skip the ring's trim route).
5198#[doc(hidden)]
5199pub const DOUBLE_CURVE_CORNER: &str = "the double curve of a wall reaches a corner of its grazing loop";
5200
5201/// The tumbled sweep by the lofted walls (a polyhedron by the trim engine).
5202fn sweep_solid_tumbled_lofted(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
5203    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
5204        return Err(input("range", "the motion's range must run forward".into()));
5205    }
5206    let mut points = [Vec3::new(0.0, 0.0, 0.0); 2];
5207    let mut directions = [Vec3::new(0.0, 0.0, 1.0); 2];
5208    for k in 0..2 {
5209        points[k] = motion.axes[k].0;
5210        directions[k] = motion.axes[k].1.normalized().map_err(|_| input("axis", "a turn's axis has no direction".into()))?;
5211    }
5212    let turns = Turns { points, directions, rates: motion.rates };
5213    // A convex polyhedron, by the trim engine (default off).
5214    if let SolidTool::Polyhedron { vertices, faces } = tool {
5215        if crate::solid_sweep_trim::trim_engine_on() {
5216            let two = crate::solid_sweep_trim::TwoTurnMotion { points, directions, rates: motion.rates };
5217            return crate::solid_sweep_trim::sweep_convex_tumbled(vertices, faces, &two, motion.from, motion.to);
5218        }
5219    }
5220    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
5221        return Err(refuse("tumble_tool", "a tumble sweeps a solid of revolution only".into()));
5222    };
5223    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
5224    let base = Screw {
5225        a: points[0],
5226        e: directions[0],
5227        omega: motion.rates[0].abs() + motion.rates[1].abs(),
5228        c: 0.0,
5229        c2: 0.0,
5230        t0: motion.from,
5231        t1: motion.to,
5232        frame: None,
5233        turns: Some(turns),
5234        frozen: None,
5235        loop_samples: LOFT_SAMPLES,
5236        extent: points[1].sub(points[0]).length(),
5237    };
5238    let span = |t0: f64, t1: f64| -> Result<BrepSolid, KernelRefusal> {
5239        let mut screw = base;
5240        screw.t0 = t0;
5241        screw.t1 = t1;
5242        let mut last = None;
5243        // The loop's sampling doubles while the walls' rows miss between
5244        // samples (a thin ring's loop bends sharply before it folds).
5245        'samples: while screw.loop_samples <= 16 * LOFT_SAMPLES {
5246            for k in 0..8 {
5247                let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
5248                match lofted(&screw, *axis_origin, axis, reference, meridian) {
5249                    // A bulge that crosses a seam high up reads on the next
5250                    // wall as a part held away from its end: other seams too.
5251                    Err(error) if matches!(refused_as(&error), Some("loft_structure") | Some("end_trim_corner") | Some("end_trim_deep")) => last = Some(error),
5252                    Err(error) if refused_as(&error) == Some("loft_rows") => {
5253                        last = Some(error);
5254                        screw.loop_samples *= 2;
5255                        continue 'samples;
5256                    }
5257                    other => return other,
5258                }
5259            }
5260            break;
5261        }
5262        Err(last.expect("tried"))
5263    };
5264    // Bisect where the sweep folds over itself.
5265    let mut pending = vec![(motion.from, motion.to, 0usize)];
5266    let mut spans: Vec<(f64, BrepSolid)> = Vec::new();
5267    while let Some((t0, t1, depth)) = pending.pop() {
5268        match span(t0, t1) {
5269            Ok(body) => spans.push((t0, body)),
5270            Err(error) if refused_as(&error) == Some("folds") && depth < 6 => {
5271                let middle = 0.5 * (t0 + t1);
5272                pending.push((middle, t1, depth + 1));
5273                pending.push((t0, middle, depth + 1));
5274            }
5275            Err(error) => return Err(error),
5276        }
5277    }
5278    spans.sort_by(|a, b| a.0.total_cmp(&b.0));
5279    let mut bodies: Vec<BrepSolid> = spans.into_iter().map(|(_, body)| body).collect();
5280    if bodies.len() == 1 {
5281        return Ok(bodies.pop().expect("one"));
5282    }
5283    crate::boolean_operation_nary(&bodies, crate::BooleanOperation::Union)
5284}
5285
5286/// A cap's pcurve for a lofted edge through the cap's exact chart (the edge
5287/// read back into the tool's frame at the cap's time).
5288fn charted_pcurve(chart: &Chart, screw: &Screw, t: f64, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
5289    let [d0, d1] = frag(curve.domain(), "domain")?;
5290    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
5291    let mut uv = Vec::with_capacity(ts.len());
5292    let mut poles = Vec::with_capacity(ts.len());
5293    for &tt in &ts {
5294        let x = screw.invert(t, frag(curve.evaluate(tt), "point")?);
5295        let [u, v] = chart.invert(x);
5296        uv.push(Vec3::new(u, v, 0.0));
5297        poles.push(chart.at_pole(x));
5298    }
5299    // Where the path crosses a span joint of the chart, one quintic through
5300    // it rings between samples (the parameter's second derivative jumps
5301    // there): by the run between joints instead (`BREP_SWEEP_PCURVE_JOINTS`).
5302    if pcurve_joints_on() && !poles.iter().any(|&p| p) {
5303        let (joints_u, joints_v) = chart.joints();
5304        let at = |tt: f64| -> Result<[f64; 2], KernelRefusal> { Ok(chart.invert(screw.invert(t, frag(curve.evaluate(tt), "point")?))) };
5305        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints_u, &joints_v, curve)? {
5306            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
5307        }
5308    }
5309    continue_pole_angles(&mut uv, &ts, &poles)?;
5310    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "charted_pcurve")?;
5311    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
5312}
5313
5314/// A surface's joints in each parameter: its interior knots that leave it C1
5315/// or less (a rational circle's spans meet at double knots), where a chart's
5316/// parameter bends.
5317fn surface_joints(surface: &NurbsSurface) -> (Vec<f64>, Vec<f64>) {
5318    let joints = |knots: &[f64], degree: usize| -> Vec<f64> {
5319        let (first, last) = (knots[0], knots[knots.len() - 1]);
5320        let mut out: Vec<f64> = Vec::new();
5321        for (i, &k) in knots.iter().enumerate() {
5322            if k > first && k < last && (i == 0 || knots[i - 1] != k) && knots.iter().filter(|&&x| x == k).count() + 1 >= degree {
5323                out.push(k);
5324            }
5325        }
5326        out
5327    };
5328    (joints(&surface.knots_u, surface.degree_u), joints(&surface.knots_v, surface.degree_v))
5329}
5330
5331thread_local! {
5332    /// Set while a split is read only for its curves and structure (a loft's
5333    /// interior times): its caps' pcurves are then never used.
5334    static PCURVES_SKIPPED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5335}
5336
5337/// The switch for skipping the cap pcurves of a loft's interior splits
5338/// (default on, `=0` fits them all; the body is the same either way).
5339fn loft_splits_lean_on() -> bool {
5340    crate::switch!("BREP_SWEEP_LOFT_SPLITS_LEAN", true)
5341}
5342
5343/// `action` with the split's cap pcurves read at their ends only: a split at
5344/// a loft's interior time is read for its curves, samples and structure, its
5345/// caps' pcurves never (only the end poses' caps are built).
5346fn with_pcurves_skipped<T>(action: impl FnOnce() -> T) -> T {
5347    // Restored on the way out, an unwind too, so a caught panic leaves no
5348    // later sweep on this thread building its end caps' pcurves as lines.
5349    struct Restore(bool);
5350    impl Drop for Restore {
5351        fn drop(&mut self) {
5352            PCURVES_SKIPPED.with(|cell| cell.set(self.0));
5353        }
5354    }
5355    let _restore = Restore(PCURVES_SKIPPED.with(|cell| cell.replace(true)));
5356    action()
5357}
5358
5359/// A grazing curve through its exact samples (quintic); in a split read only
5360/// for its curves' samples and structure ([`with_pcurves_skipped`]: a loft's
5361/// interior times), the line between its ends, never read as a curve.
5362fn fit_tool_curve(points: &[Vec3], params: &[f64]) -> Result<NurbsCurve, String> {
5363    if PCURVES_SKIPPED.with(|cell| cell.get()) && points.len() >= 2 && params.len() == points.len() {
5364        let (a, b) = (params[0], params[params.len() - 1]);
5365        return NurbsCurve::new(1, vec![a, a, b, b], vec![Vec4::from_point(points[0], 1.0), Vec4::from_point(points[points.len() - 1], 1.0)]);
5366    }
5367    crate::interpolate_curve(points, 5, params)
5368}
5369
5370/// A cap pcurve's stations: the whole set, or its two ends where the pcurve
5371/// is never used ([`with_pcurves_skipped`]).
5372fn pcurve_stations(d0: f64, d1: f64) -> Vec<f64> {
5373    if PCURVES_SKIPPED.with(|cell| cell.get()) {
5374        return vec![d0, d1];
5375    }
5376    (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect()
5377}
5378
5379/// The quintic through a cap pcurve's stations; through two (a skipped
5380/// pcurve), the line between its ends.
5381fn fit_pcurve(uv: &[Vec3], ts: &[f64]) -> Result<NurbsCurve, String> {
5382    if ts.len() == 2 {
5383        return NurbsCurve::new(1, vec![ts[0], ts[0], ts[1], ts[1]], uv.iter().map(|&p| Vec4::from_point(p, 1.0)).collect());
5384    }
5385    crate::interpolate_curve(uv, 5, ts)
5386}
5387
5388/// The switch for [`jointed_pcurve`] (default on; `=0` fits one quintic as before).
5389fn pcurve_joints_on() -> bool {
5390    crate::switch!("BREP_SWEEP_PCURVE_JOINTS", true)
5391}
5392
5393/// A cap's pcurve broken where its path crosses a span joint of its chart:
5394/// the edge's parameter at each crossing found by bisection (`at` reads the
5395/// path's chart parameters at an edge parameter), each run between them
5396/// sampled as densely as the whole and interpolated (quintic) on its own, the
5397/// runs joined C0 at the crossings, so each run interpolates a smooth function
5398/// and the trim keeps to its edge at the same parameter, not only at the
5399/// samples. `ts`, `uv`: the whole's samples; `edge`: the curve the path
5400/// reads (its own C1-or-less knots are cut too). None where the path crosses
5401/// no joint (the one quintic is smooth there).
5402fn jointed_pcurve(ts: &[f64], uv: &[Vec3], at: impl Fn(f64) -> Result<[f64; 2], KernelRefusal>, joints_u: &[f64], joints_v: &[f64], edge: &NurbsCurve) -> Result<Option<NurbsCurve>, KernelRefusal> {
5403    if ts.len() < 3 || ts.len() != uv.len() {
5404        return Ok(None);
5405    }
5406    let (d0, d1) = (ts[0], ts[ts.len() - 1]);
5407    // The edge's own joints: an interior knot that leaves it C1 or less (a
5408    // rational arc's spans) kinks its parameter, so the path's too.
5409    let mut cuts: Vec<f64> = Vec::new();
5410    for (index, &k) in edge.knots.iter().enumerate() {
5411        if k > d0 && k < d1 && (index == 0 || edge.knots[index - 1] != k) {
5412            let multiplicity = edge.knots.iter().filter(|&&x| x == k).count();
5413            if multiplicity + 1 >= edge.degree {
5414                cuts.push(k);
5415            }
5416        }
5417    }
5418    for j in 0..ts.len() - 1 {
5419        let (a, b) = (uv[j], uv[j + 1]);
5420        for (coord, joints) in [(0usize, joints_u), (1, joints_v)] {
5421            let (ca, cb) = if coord == 0 { (a.x, b.x) } else { (a.y, b.y) };
5422            for &k in joints {
5423                // A sample on the joint itself is the cut (a path that only
5424                // touches it is cut there too, harmlessly).
5425                if ca == k && j > 0 {
5426                    cuts.push(ts[j]);
5427                    continue;
5428                }
5429                if (ca - k) * (cb - k) < 0.0 {
5430                    // Bisect the edge's parameter for the crossing.
5431                    let (mut lo, mut hi) = (ts[j], ts[j + 1]);
5432                    let side = ca < k;
5433                    for _ in 0..80 {
5434                        let mid = 0.5 * (lo + hi);
5435                        if mid <= lo || mid >= hi {
5436                            break;
5437                        }
5438                        if (at(mid)?[coord] < k) == side { lo = mid } else { hi = mid }
5439                    }
5440                    cuts.push(0.5 * (lo + hi));
5441                }
5442            }
5443        }
5444    }
5445    if cuts.is_empty() {
5446        return Ok(None);
5447    }
5448    // Each run at least a millionth of the whole: a cut nearer an end or
5449    // another than that is dropped (its run would be too short to fit).
5450    let least = 1e-6 * (d1 - d0);
5451    cuts.sort_by(f64::total_cmp);
5452    let mut bounds = vec![d0];
5453    for c in cuts {
5454        if c - bounds[bounds.len() - 1] >= least && d1 - c >= least {
5455            bounds.push(c);
5456        }
5457    }
5458    if bounds.len() == 1 {
5459        return Ok(None);
5460    }
5461    bounds.push(d1);
5462    let samples = ts.len() - 1;
5463    let degree = 5;
5464    let mut knots: Vec<f64> = Vec::new();
5465    let mut poles: Vec<Vec4> = Vec::new();
5466    let runs = bounds.len() - 1;
5467    for (index, run) in bounds.windows(2).enumerate() {
5468        let (a, b) = (run[0], run[1]);
5469        let count = ((samples as f64 * (b - a) / (d1 - d0)).ceil() as usize).max(degree + 1);
5470        let params: Vec<f64> = (0..=count).map(|i| if i == count { b } else { a + (b - a) * i as f64 / count as f64 }).collect();
5471        let points: Vec<Vec3> = params.iter().map(|&tt| at(tt).map(|[u, v]| Vec3::new(u, v, 0.0))).collect::<Result<_, _>>()?;
5472        // A run that does not fit falls back to the one quintic, never a refusal.
5473        let Ok(piece) = crate::interpolate_curve(&points, degree, &params) else { return Ok(None) };
5474        if piece.degree != degree {
5475            return Ok(None);
5476        }
5477        let n = piece.knots.len();
5478        if index == 0 {
5479            knots.extend_from_slice(&piece.knots[..n - (degree + 1)]);
5480            poles.extend_from_slice(&piece.control_points);
5481        } else {
5482            // The joint: its parameter `degree` times (C0), this run's interior
5483            // knots; its first pole is the previous run's last.
5484            knots.extend(std::iter::repeat_n(a, degree));
5485            knots.extend_from_slice(&piece.knots[degree + 1..n - (degree + 1)]);
5486            poles.extend_from_slice(&piece.control_points[1..]);
5487        }
5488        if index + 1 == runs {
5489            knots.extend(std::iter::repeat_n(b, degree + 1));
5490        }
5491    }
5492    Ok(NurbsCurve::new(degree, knots, poles).ok())
5493}
5494
5495/// An edge through its surface's pole (a ball carried square to its own
5496/// axis: every grazing circle runs pole to pole) has no angle there, and the
5497/// inverse returns any. Each sample at a pole (`poles`) takes the first
5498/// parameter its neighbours run to, continued in a line.
5499fn continue_pole_angles(uv: &mut [Vec3], ts: &[f64], poles: &[bool]) -> Result<(), KernelRefusal> {
5500    for j in 0..uv.len() {
5501        if !poles[j] {
5502            continue;
5503        }
5504        let near = if j + 2 < uv.len() && !poles[j + 1] && !poles[j + 2] {
5505            [j + 1, j + 2]
5506        } else if j >= 2 && !poles[j - 1] && !poles[j - 2] {
5507            [j - 1, j - 2]
5508        } else {
5509            return Err(refuse("cap_pole", "a lofted edge stays on its cap's pole".into()));
5510        };
5511        let (a, b) = (uv[near[0]].x, uv[near[1]].x);
5512        uv[j].x = a + (a - b) * (ts[j] - ts[near[0]]) / (ts[near[0]] - ts[near[1]]);
5513    }
5514    Ok(())
5515}
5516
5517/// A cap's pcurve for a lofted edge: its dense image on the cap's surface.
5518fn projected_pcurve(surface: &NurbsSurface, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
5519    let [d0, d1] = frag(curve.domain(), "domain")?;
5520    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
5521    let mut uv = Vec::with_capacity(ts.len());
5522    let mut poles = Vec::with_capacity(ts.len());
5523    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5524    let step = 1e-3 * (u1 - u0);
5525    for &t in &ts {
5526        let x = frag(curve.evaluate(t), "point")?;
5527        let foot = frag(crate::project_point_to_surface(surface, x), "project")?;
5528        if foot.distance > 1e-6 * (1.0 + x.length()) {
5529            return Err(refuse("loft_cap", format!("a lofted edge leaves its cap by {} at {x:?}", foot.distance)));
5530        }
5531        uv.push(Vec3::new(foot.u, foot.v, 0.0));
5532        // A pole of the surface: its points do not move with the first
5533        // parameter there.
5534        let aside = if foot.u + step <= u1 { foot.u + step } else { foot.u - step };
5535        let moved = frag(surface.evaluate(aside, foot.v), "point")?.sub(frag(surface.evaluate(foot.u, foot.v), "point")?).length();
5536        poles.push(moved <= 1e-9 * (1.0 + x.length()));
5537    }
5538    continue_pole_angles(&mut uv, &ts, &poles)?;
5539    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "projected_pcurve")?;
5540    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
5541}
5542
5543type Signature = (Vec<(usize, usize, bool)>, Vec<(bool, Vec<(usize, bool)>)>, Vec<(usize, bool)>);
5544
5545fn signature(split: &Split) -> Result<Signature, KernelRefusal> {
5546    Ok((
5547        split.curves.iter().map(|c| (c.start, c.end, c.degenerate)).collect(),
5548        split.caps.iter().map(|cap| (cap.front, cap.coedges.iter().map(|&(c, f, _)| (c, f)).collect())).collect(),
5549        split.grazing()?,
5550    ))
5551}
5552
5553fn lofted(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<BrepSolid, KernelRefusal> {
5554    let split_at = |t: f64| -> Result<Split, KernelRefusal> {
5555        let mut frozen = *screw;
5556        frozen.frozen = Some(t);
5557        split_revolved(&frozen, origin, axis, radial, meridian)
5558    };
5559    let mut lambdas: Vec<f64> = (0..=LOFT_SAMPLES).map(|i| i as f64 / LOFT_SAMPLES as f64).collect();
5560    // World samples of grazing curve c at time t, in the wall's direction.
5561    let samples_of = |split: &Split, c: usize, back_forward: bool, t: f64| -> Result<Vec<Vec3>, KernelRefusal> {
5562        let Some(list) = &split.curves[c].samples else {
5563            return Err(refuse("loft_samples", "a grazing curve has no exact samples to loft".into()));
5564        };
5565        let mut world: Vec<Vec3> = list.iter().map(|&x| screw.apply(t, x)).collect();
5566        if back_forward {
5567            world.reverse();
5568        }
5569        Ok(world)
5570    };
5571    // Time breaks start even and are refined only in the spans whose middle
5572    // misses, by the quintic's h^6 error: a smooth stretch of the motion keeps
5573    // its long spans (doubling everywhere tripled the wall for one bend).
5574    let mut fractions: Vec<f64> = (0..=15).map(|j| j as f64 / 15.0).collect();
5575    loop {
5576        let count = fractions.len() - 1;
5577        // The walls' second parameter runs 0 -> 1 over the motion.
5578        let times: Vec<f64> = fractions.iter().map(|&f| if f == 1.0 { screw.t1 } else { screw.t0 + (screw.t1 - screw.t0) * f }).collect();
5579        // Only the end poses' caps are built: the interior splits are read
5580        // for their curves and structure, their caps' pcurves skipped
5581        // (`BREP_SWEEP_LOFT_SPLITS_LEAN`).
5582        let lean = loft_splits_lean_on();
5583        let splits: Vec<Split> = times
5584            .iter()
5585            .enumerate()
5586            .map(|(j, &t)| if lean && j != 0 && j != count { with_pcurves_skipped(|| split_at(t)) } else { split_at(t) })
5587            .collect::<Result<_, _>>()?;
5588        if splits.iter().any(|split| !split.slides.is_empty() || !split.slide_sides.is_empty()) {
5589            return Err(refuse("loft_structure", "a flat end that slides within its own plane is not lofted".into()));
5590        }
5591        let shape = signature(&splits[0])?;
5592        for split in &splits[1..] {
5593            if signature(split)? != shape {
5594                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5595            }
5596        }
5597        let grazing = shape.2.clone();
5598        if grazing.is_empty() {
5599            return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
5600        }
5601        let scale = splits[0].scale + screw.extent;
5602        let target = LOFT_TARGET * scale;
5603        // Walls: per grazing curve, rows along it at each time, then across time.
5604        let mut walls = Vec::with_capacity(grazing.len());
5605        // Every wall's exact samples at every time.
5606        let mut sampled: Vec<Vec<Vec<Vec3>>> = Vec::with_capacity(grazing.len());
5607        for &(c, back_forward) in &grazing {
5608            let mut at_times = Vec::with_capacity(times.len());
5609            for (j, split) in splits.iter().enumerate() {
5610                let points = samples_of(split, c, back_forward, times[j])?;
5611                if points.len() != lambdas.len() {
5612                    if points.len() < 13 || points.len() % 2 == 0 {
5613                        return Err(refuse("loft_samples", "a grazing curve's exact samples cannot be lofted".into()));
5614                    }
5615                    lambdas = (0..points.len()).map(|i| i as f64 / (points.len() - 1) as f64).collect();
5616                }
5617                at_times.push(points);
5618            }
5619            sampled.push(at_times);
5620        }
5621        // A row through every `stride`-th sample: its worst miss at the
5622        // samples it leaves out, over every wall and time.
5623        let thinned = |stride: usize| -> Result<f64, KernelRefusal> {
5624            let coarse_lambdas: Vec<f64> = lambdas.iter().step_by(stride).copied().collect();
5625            let mut worst = 0.0f64;
5626            for at_times in &sampled {
5627                for points in at_times {
5628                    let coarse_points: Vec<Vec3> = points.iter().step_by(stride).copied().collect();
5629                    let coarse = frag(crate::interpolate_curve(&coarse_points, 5, &coarse_lambdas), "loft_row")?;
5630                    for (i, x) in points.iter().enumerate().filter(|(i, _)| i % stride != 0) {
5631                        worst = worst.max(frag(coarse.evaluate(lambdas[i]), "loft_row")?.sub(*x).length());
5632                    }
5633                }
5634            }
5635            Ok(worst)
5636        };
5637        // Each wall's rows pass through as few of its samples as hold every
5638        // exact sample within a quarter of the target, at every time (a loop
5639        // smooth but for one sharp bend needs its samples only there, and the
5640        // wall's size is what the solid's users pay for): from every 16th,
5641        // a stretch that misses at a sample it leaves out gets its middle one.
5642        let spans = lambdas.len() - 1;
5643        let mut kept: Vec<Vec<usize>> = Vec::with_capacity(sampled.len());
5644        for at_times in &sampled {
5645            let coarsest = if spans % 16 == 0 && spans >= 96 { 16 } else { 1 };
5646            let mut subset: Vec<usize> = (0..=spans).step_by(coarsest).collect();
5647            loop {
5648                let subset_lambdas: Vec<f64> = subset.iter().map(|&i| lambdas[i]).collect();
5649                let mut misses = vec![0.0f64; subset.len() - 1];
5650                for points in at_times {
5651                    let row_points: Vec<Vec3> = subset.iter().map(|&i| points[i]).collect();
5652                    let row = frag(crate::interpolate_curve(&row_points, 5, &subset_lambdas), "loft_row")?;
5653                    for k in 0..subset.len() - 1 {
5654                        for i in subset[k] + 1..subset[k + 1] {
5655                            misses[k] = misses[k].max(frag(row.evaluate(lambdas[i]), "loft_row")?.sub(points[i]).length());
5656                        }
5657                    }
5658                }
5659                let mut refined = Vec::with_capacity(2 * subset.len());
5660                for k in 0..subset.len() - 1 {
5661                    refined.push(subset[k]);
5662                    if misses[k] > 0.25 * target {
5663                        refined.push((subset[k] + subset[k + 1]) / 2);
5664                    }
5665                }
5666                refined.push(spans);
5667                if refined.len() == subset.len() {
5668                    break;
5669                }
5670                subset = refined;
5671            }
5672            kept.push(subset);
5673        }
5674        // Where a wall keeps neighbouring samples there is none left out
5675        // between them to measure at: a row passes through its samples, and
5676        // between them it is as good as the loop is smooth at that spacing.
5677        // Its miss there is estimated from the rows through every other
5678        // sample, scaled by the quintic's 2^-6.
5679        let dense = kept.iter().any(|subset| subset.windows(2).any(|pair| pair[1] == pair[0] + 1));
5680        let between = if dense { thinned(2)? / 64.0 } else { 0.0 };
5681        for (index, &(c, back_forward)) in grazing.iter().enumerate() {
5682            let row_lambdas: Vec<f64> = kept[index].iter().map(|&i| lambdas[i]).collect();
5683            let mut rows: Vec<NurbsCurve> = Vec::with_capacity(times.len());
5684            for points in &sampled[index] {
5685                let row_points: Vec<Vec3> = kept[index].iter().map(|&i| points[i]).collect();
5686                rows.push(frag(crate::interpolate_curve(&row_points, 5, &row_lambdas), "loft_row")?);
5687            }
5688            let knots_u = rows[0].knots.clone();
5689            let mut net: Vec<Vec<Vec4>> = Vec::with_capacity(rows[0].control_points.len());
5690            let mut knots_v = Vec::new();
5691            for k in 0..rows[0].control_points.len() {
5692                let column: Vec<Vec3> = rows.iter().map(|row| row.control_points[k].point()).collect::<Result<_, _>>().map_err(|e| refuse("loft", e))?;
5693                let across = frag(crate::interpolate_curve(&column, 5, &fractions), "loft_column")?;
5694                knots_v = across.knots.clone();
5695                net.push(across.control_points.clone());
5696            }
5697            let surface = frag(NurbsSurface::new(5, 5, knots_u, knots_v, net), "loft_wall")?;
5698            walls.push((c, back_forward, surface, rows.first().cloned().expect("rows"), rows.last().cloned().expect("rows")));
5699        }
5700        if between > target {
5701            return Err(refuse("loft_rows", format!("the lofted wall's rows stay about {between:e} off the grazing loop between its samples")));
5702        }
5703        // Against the exact loop in the middle of each span, every sample.
5704        let mut misses = vec![0.0f64; count];
5705        for j in 0..count {
5706            let t = 0.5 * (times[j] + times[j + 1]);
5707            let fraction = 0.5 * (fractions[j] + fractions[j + 1]);
5708            let split = if lean { with_pcurves_skipped(|| split_at(t))? } else { split_at(t)? };
5709            if signature(&split)? != shape {
5710                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5711            }
5712            for (c, back_forward, surface, _, _) in &walls {
5713                let exact = samples_of(&split, *c, *back_forward, t)?;
5714                for (i, x) in exact.iter().enumerate() {
5715                    misses[j] = misses[j].max(frag(surface.evaluate(lambdas[i], fraction), "loft_check")?.sub(*x).length());
5716                }
5717            }
5718        }
5719        let worst = misses.iter().copied().fold(0.0f64, f64::max);
5720        if worst > target {
5721            if count > 2000 {
5722                return Err(refuse("loft_accuracy", format!("the lofted wall stays {worst:e} off the grazing loop")));
5723            }
5724            // A span missing by more than half the target is cut into
5725            // ceil((e / (target / 4))^(1/6)) pieces; the rest stay.
5726            let mut refined = Vec::with_capacity(2 * fractions.len());
5727            for j in 0..count {
5728                let pieces = if misses[j] > 0.5 * target { ((misses[j] / (0.25 * target)).powf(1.0 / 6.0).ceil() as usize).max(2) } else { 1 };
5729                for k in 0..pieces {
5730                    refined.push(fractions[j] + (fractions[j + 1] - fractions[j]) * k as f64 / pieces as f64);
5731                }
5732            }
5733            refined.push(1.0);
5734            fractions = refined;
5735            continue;
5736        }
5737        // Each K corner's path through the sample times.
5738        let mut paths: HashMap<usize, Vec<Vec3>> = HashMap::new();
5739        for &(c, _) in &grazing {
5740            for r in [splits[0].curves[c].start, splits[0].curves[c].end] {
5741                paths.entry(r).or_insert_with(|| splits.iter().zip(&times).map(|(split, &t)| screw.apply(t, split.points[r])).collect());
5742            }
5743        }
5744        return assemble_lofted(screw, &splits[0], &splits[count], &walls, &fractions, &paths, target);
5745    }
5746}
5747
5748/// Refuse a lofted wall with an edge of regression: across one the wall's
5749/// normal turns over, and the band beside it lies inside nearby poses (the
5750/// sweep folds within a few degrees of the motion, which no probe walk is
5751/// dense enough to be sure of seeing). Normals are compared between
5752/// neighbours on every time row and between rows, outside what the end trims
5753/// take away (`removed`, chart rings) and a few columns off its edge (a fold
5754/// line meets the end at the cut's own ends). `fit`: how near the wall keeps
5755/// to its exact loop (a length).
5756fn wall_regular(surface: &NurbsSurface, fractions: &[f64], removed: &[&[[f64; 2]]], fit: f64) -> Result<(), KernelRefusal> {
5757    const COLUMNS: usize = 4 * LOFT_SAMPLES;
5758    let mut rows: Vec<f64> = Vec::with_capacity(2 * fractions.len());
5759    for j in 0..fractions.len() {
5760        rows.push(fractions[j]);
5761        if j + 1 < fractions.len() {
5762            rows.push(0.5 * (fractions[j] + fractions[j + 1]));
5763        }
5764    }
5765    let normal = |u: f64, v: f64| -> Result<Option<Vec3>, KernelRefusal> {
5766        let h = 1e-6;
5767        let (ua, ub, va, vb) = ((u - h).max(0.0), (u + h).min(1.0), (v - h).max(0.0), (v + h).min(1.0));
5768        let du = frag(surface.evaluate(ub, v), "regular")?.sub(frag(surface.evaluate(ua, v), "regular")?).scale(1.0 / (ub - ua));
5769        let dv = frag(surface.evaluate(u, vb), "regular")?.sub(frag(surface.evaluate(u, va), "regular")?).scale(1.0 / (vb - va));
5770        // Where the wall's two directions all but line up, or it is no
5771        // wider than its own fit's ripple (a corner it pinches to), it has
5772        // no normal to speak of: the fit's noise would turn it.
5773        let cross = du.cross(dv);
5774        if cross.length() <= 1e-6 * du.length() * dv.length() || du.length().min(dv.length()) <= 1e3 * fit {
5775            return Ok(None);
5776        }
5777        Ok(cross.normalized().ok())
5778    };
5779    // Each trimmed-away ring's box, grown by the reach of `near_ring` and a hair: a point
5780    // outside it is neither inside the ring (a closed polygon) nor that near it, so the box
5781    // answers for it as the ring's own tests would.
5782    let reach = 4.0 / COLUMNS as f64;
5783    let boxes: Vec<[f64; 4]> = removed
5784        .iter()
5785        .map(|ring| {
5786            let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
5787            for p in ring.iter() {
5788                lo = [lo[0].min(p[0]), lo[1].min(p[1])];
5789                hi = [hi[0].max(p[0]), hi[1].max(p[1])];
5790            }
5791            let pad = reach * (1.0 + 1e-9) + 1e-12;
5792            [lo[0] - pad, hi[0] + pad, lo[1] - pad, hi[1] + pad]
5793        })
5794        .collect();
5795    let mut previous: Option<Vec<Option<Vec3>>> = None;
5796    for &v in &rows {
5797        // What a trim takes away is not part of the body.
5798        let row: Vec<Option<Vec3>> = (0..=COLUMNS)
5799            .map(|i| {
5800                let u = i as f64 / COLUMNS as f64;
5801                let taken = removed.iter().zip(&boxes).any(|(ring, b)| {
5802                    !(u < b[0] || u > b[1] || v < b[2] || v > b[3]) && (inside_ring(ring, [u, v]) || near_ring(ring, [u, v], reach))
5803                });
5804                if taken { Ok(None) } else { normal(u, v) }
5805            })
5806            .collect::<Result<_, _>>()?;
5807        for i in 0..COLUMNS {
5808            if let (Some(a), Some(b)) = (row[i], row[i + 1]) {
5809                if a.dot(b) < -0.5 {
5810                    return Err(refuse("wall_folds", format!("a lofted wall turns over (an edge of regression near parameter ({:.4}, {v:.4})); the sweep folds onto itself", i as f64 / COLUMNS as f64)));
5811                }
5812            }
5813            if let Some(Some(Some(a))) = previous.as_ref().map(|p| p.get(i).copied()) {
5814                if let Some(b) = row[i] {
5815                    if a.dot(b) < -0.5 {
5816                        return Err(refuse("wall_folds", format!("a lofted wall turns over (an edge of regression near parameter ({:.4}, {v:.4})); the sweep folds onto itself", i as f64 / COLUMNS as f64)));
5817                    }
5818                }
5819            }
5820        }
5821        previous = Some(row);
5822    }
5823    Ok(())
5824}
5825
5826/// A stretch of a wall's row at v, from u = a to u = b, as an edge's curve.
5827fn row_piece(wall: &NurbsSurface, v: f64, a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
5828    let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5829    let along: Vec<Vec3> = ts.iter().map(|&s| frag(wall.evaluate((a + (b - a) * s).clamp(0.0, 1.0), v), "wall")).collect::<Result<_, _>>()?;
5830    frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
5831}
5832
5833/// A wall's end row in pieces around its trims and breaks (one more than the
5834/// spans), at v.
5835fn row_pieces(wall: &NurbsSurface, v: f64, spans: &[TrimSpan]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
5836    let mut pieces = Vec::with_capacity(spans.len() + 1);
5837    let mut from = 0.0;
5838    for span in spans {
5839        pieces.push(row_piece(wall, v, from, span.lambdas[0])?);
5840        from = span.lambdas[1];
5841    }
5842    pieces.push(row_piece(wall, v, from, 1.0)?);
5843    Ok(pieces)
5844}
5845
5846/// The wall over u ∈ [a, b] only, in the same parameters.
5847/// Can `pcurve` (in a wall's chart) meet the split segment u = tip.u, v in
5848/// [v_lo, v_hi], anywhere but at the tip itself? A pcurve that ENDS at the
5849/// tip (a side of the double curve) touches it there: a short stub at that end
5850/// must leave the tip into one side of the line or away from the segment, and
5851/// the rest is tested. Every other piece is decided on the convex hull of its
5852/// control points (positive weights), halved where a hull straddles the
5853/// segment; one still straddling after 24 halvings counts as meeting it.
5854fn hull_meets_segment(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64) -> Result<bool, KernelRefusal> {
5855    let uv = |p: &Vec4| [p.x / p.w, p.y / p.w];
5856    let near_tip = |p: [f64; 2]| (p[0] - tip[0]).abs() <= 1e-9 && (p[1] - tip[1]).abs() <= 1e-9;
5857    let (first, last) = (uv(&pcurve.control_points[0]), uv(&pcurve.control_points[pcurve.control_points.len() - 1]));
5858    if !(near_tip(first) || near_tip(last)) {
5859        return hull_straddles(pcurve, tip, v_lo, v_hi, 0);
5860    }
5861    if near_tip(first) && near_tip(last) {
5862        return Ok(true);
5863    }
5864    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5865    let at = if near_tip(first) { d0 + 1e-3 * (d1 - d0) } else { d1 - 1e-3 * (d1 - d0) };
5866    let (a, b) = frag(pcurve.split(at), "split")?;
5867    let (stub, rest) = if near_tip(first) { (a, b) } else { (b, a) };
5868    let side: Vec<f64> = stub.control_points.iter().map(|p| uv(p)[0] - tip[0]).collect();
5869    let one_side = side.iter().all(|d| *d >= -1e-12) || side.iter().all(|d| *d <= 1e-12);
5870    // The segment runs from the tip towards the far row: away is the other way.
5871    let segment_below = v_lo < tip[1] - 1e-12;
5872    let away = stub.control_points.iter().all(|p| if segment_below { uv(p)[1] >= tip[1] - 1e-9 } else { uv(p)[1] <= tip[1] + 1e-9 });
5873    if !(one_side || away) {
5874        return Ok(true);
5875    }
5876    hull_straddles(&rest, tip, v_lo, v_hi, 0)
5877}
5878
5879fn hull_straddles(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64, depth: usize) -> Result<bool, KernelRefusal> {
5880    let points: Vec<[f64; 2]> = pcurve.control_points.iter().map(|p| [p.x / p.w, p.y / p.w]).collect();
5881    let (u_min, u_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[0]), hi.max(p[0])));
5882    let (w_min, w_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[1]), hi.max(p[1])));
5883    if u_min > tip[0] + 1e-12 || u_max < tip[0] - 1e-12 || w_min > v_hi + 1e-12 || w_max < v_lo - 1e-12 {
5884        return Ok(false);
5885    }
5886    if depth >= 24 {
5887        return Ok(true);
5888    }
5889    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5890    match pcurve.split(0.5 * (d0 + d1)) {
5891        Ok((a, b)) => Ok(hull_straddles(&a, tip, v_lo, v_hi, depth + 1)? || hull_straddles(&b, tip, v_lo, v_hi, depth + 1)?),
5892        // Too short to halve: count it as meeting the segment.
5893        Err(_) => Ok(true),
5894    }
5895}
5896
5897/// `BREP_SWEEP_SPLIT_CROSSING` (default on; `=0` off): a lofted wall that
5898/// turns over near one end is split at its swallowtail's point whenever the
5899/// split segment to the far row crosses no trim curve, not only where the
5900/// trimmed row keeps to its side of the tip's u; otherwise the wall stays one
5901/// face carrying its double curve as a slot (one edge used twice), which
5902/// meshes poorly at the slot's tip.
5903fn split_crossing_on() -> bool {
5904    crate::switch!("BREP_SWEEP_SPLIT_CROSSING", true)
5905}
5906
5907fn restrict_u(surface: &NurbsSurface, a: f64, b: f64) -> Result<NurbsSurface, KernelRefusal> {
5908    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5909    if a <= u0 + 1e-12 && b >= u1 - 1e-12 {
5910        return Ok(surface.clone());
5911    }
5912    let columns = surface.control_points[0].len();
5913    let mut knots = Vec::new();
5914    let mut net: Vec<Vec<Vec4>> = Vec::new();
5915    for j in 0..columns {
5916        let line: Vec<Vec4> = surface.control_points.iter().map(|row| row[j]).collect();
5917        let mut curve = frag(NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), line), "restrict")?;
5918        if b < u1 - 1e-12 {
5919            curve = frag(curve.split(b), "restrict")?.0;
5920        }
5921        if a > u0 + 1e-12 {
5922            curve = frag(curve.split(a), "restrict")?.1;
5923        }
5924        if j == 0 {
5925            knots = curve.knots.clone();
5926            net = vec![Vec::with_capacity(columns); curve.control_points.len()];
5927        }
5928        for (i, point) in curve.control_points.iter().enumerate() {
5929            net[i].push(*point);
5930        }
5931    }
5932    frag(NurbsSurface::new(surface.degree_u, surface.degree_v, knots, surface.knots_v.clone(), net), "restrict")
5933}
5934
5935/// One place a wall is cut back where an end pose bulges past it: the wall
5936/// parameter range [λa, λb] along the grazing loop where the trim leaves and
5937/// rejoins it, the cut (from the point at λa to the point at λb, on both the
5938/// wall and the pose), the wall's side of the trim from λa to λb (`chain`),
5939/// the double curve and its swallowtail point if the trim follows one, and
5940/// the part of the wall's chart it takes away (`removed`, (u, v) points
5941/// around it).
5942struct TrimSpan {
5943    lambdas: [f64; 2],
5944    points: [Vec3; 2],
5945    /// None: no cut at all, only a break in the end's row at λa = λb (where
5946    /// a line splitting the wall lands on it).
5947    cut: Option<NurbsCurve>,
5948    chain: Vec<(TrimPiece, bool, NurbsCurve)>,
5949    slot: Option<(NurbsCurve, Vec3)>,
5950    /// The swallowtail's point in the wall's chart (u, v), where the trim
5951    /// follows a double curve.
5952    tip: Option<[f64; 2]>,
5953    removed: Vec<[f64; 2]>,
5954}
5955
5956/// Every place an end pose bulges past one wall, in order along the loop, and
5957/// the loop's pieces around them (one more than the spans).
5958struct EndTrim {
5959    spans: Vec<TrimSpan>,
5960    pieces: Vec<NurbsCurve>,
5961}
5962
5963/// Which edge a piece of a trimmed wall's end runs on: the cut it shares with
5964/// the cap, or the wall's own double curve (both of the slot's sides).
5965#[derive(Clone, Copy, PartialEq, Eq, Debug)]
5966enum TrimPiece {
5967    Cut,
5968    Slot,
5969}
5970
5971/// The cut of a lofted wall (u along the grazing loop, v the motion's time
5972/// fraction) by the pose at its end (`end` 0: v = 0, 1: v = 1), if the pose
5973/// bulges past it, else None.
5974///
5975/// The wall meets the pose along K and leaves it to second order (K grazes),
5976/// so with ε the time fraction from the end, f = d / ε² (d the pose's signed
5977/// distance) is smooth up to the end. The part of the wall inside the pose is
5978/// where f < 0; its boundary is traced as the curve f = 0 from the end and back
5979/// to it. It need not be a graph over u: a tongue of it may run on past where
5980/// it left the end.
5981///
5982/// `fit`: how near the wall keeps to the exact loop (a length).
5983fn end_trim(screw: &Screw, split: &Split, t: f64, wall: &NurbsSurface, end: usize, fit: f64) -> Result<Option<EndTrim>, KernelRefusal> {
5984    let v_of = |e: f64| if end == 1 { 1.0 - e } else { e };
5985    let at = |u: f64, e: f64| -> Result<Vec3, KernelRefusal> { frag(wall.evaluate(u.clamp(0.0, 1.0), v_of(e)), "wall") };
5986    let f = |u: f64, e: f64| -> Result<f64, KernelRefusal> { Ok(split.distance(screw.invert(t, at(u, e)?)) / (e * e)) };
5987    // Below `floor` the walls' fit swamps d / ε².
5988    let floor = 1e-3;
5989    // How far into the motion (as a fraction of it) a trim may reach (a fold
5990    // band can run most of a span); past that the end pose meets a distant
5991    // part of the sweep (`end_trim_deep`).
5992    let window = 0.6;
5993    let noise = 2.0 * fit / (floor * floor);
5994    // Where the wall dips into the pose just off the end.
5995    let n = 2000;
5996    let edge: Vec<f64> = (0..=n).map(|i| f(i as f64 / n as f64, floor)).collect::<Result<_, _>>()?;
5997    // Inside: the stretches where f is negative, those that dip below the
5998    // fit's noise somewhere (a stretch that never does is the fit's own).
5999    let mut inside: Vec<bool> = edge.iter().map(|&x| x < 0.0).collect();
6000    let mut i = 0;
6001    while i <= n {
6002        if !inside[i] {
6003            i += 1;
6004            continue;
6005        }
6006        let mut j = i;
6007        while j < n && inside[j + 1] {
6008            j += 1;
6009        }
6010        if edge[i..=j].iter().all(|&x| x >= -noise) {
6011            for flag in &mut inside[i..=j] {
6012                *flag = false;
6013            }
6014        }
6015        i = j + 1;
6016    }
6017    if !inside.iter().any(|&x| x) {
6018        // Nothing near the end; a pocket deeper in is caught below.
6019        return pierced(&f, floor, window, noise, &[]);
6020    }
6021    if inside[0] || inside[n] || inside[1] || inside[n - 1] {
6022        return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6023    }
6024    // Crossings of the floor line, by bisection between samples of either sign.
6025    let mut crossings: Vec<f64> = Vec::new();
6026    for i in 0..n {
6027        if inside[i] != inside[i + 1] {
6028            let (mut a, mut b) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
6029            let a_inside = inside[i];
6030            for _ in 0..60 {
6031                let mid = 0.5 * (a + b);
6032                if (f(mid, floor)? < 0.0) == a_inside { a = mid } else { b = mid }
6033            }
6034            crossings.push(0.5 * (a + b));
6035        }
6036    }
6037    if crossings.len() % 2 != 0 || crossings.is_empty() {
6038        return Err(refuse("end_trim", "an end pose's bulges past a wall do not pair up".into()));
6039    }
6040    // Trace f = 0 from the first crossing of each pair into the wall until it
6041    // returns to the floor; it must come back at the pair's other crossing.
6042    let gradient = |u: f64, e: f64| -> Result<[f64; 2], KernelRefusal> {
6043        let h = 1e-6;
6044        Ok([(f(u + h, e)? - f(u - h, e)?) / (2.0 * h), (f(u, e + h)? - f(u, e - h)?) / (2.0 * h)])
6045    };
6046    let settle = |mut p: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
6047        for _ in 0..30 {
6048            let value = f(p[0], p[1])?;
6049            let g = gradient(p[0], p[1])?;
6050            let norm = g[0] * g[0] + g[1] * g[1];
6051            if norm == 0.0 {
6052                return Err(refuse("end_trim", "the cut of an end pose has a flat point".into()));
6053            }
6054            p = [p[0] - value * g[0] / norm, p[1] - value * g[1] / norm];
6055            if value.abs() * p[1] * p[1] < 1e-14 * split.scale {
6056                break;
6057            }
6058        }
6059        Ok(p)
6060    };
6061    let step = 1e-3;
6062    let mut cuts: Vec<Vec<[f64; 2]>> = Vec::new();
6063    // Each cut starts at the lowest crossing not yet used and ends at the
6064    // unused one it comes back to.
6065    let mut unused: Vec<f64> = crossings.clone();
6066    while !unused.is_empty() {
6067        let start = unused.remove(0);
6068        let mut points: Vec<[f64; 2]> = vec![[start, floor]];
6069        let mut heading = [0.0, 1.0];
6070        loop {
6071            let last = *points.last().expect("points");
6072            let g = gradient(last[0], last[1])?;
6073            let length = g[0].hypot(g[1]);
6074            let mut tangent = [-g[1] / length, g[0] / length];
6075            if tangent[0] * heading[0] + tangent[1] * heading[1] < 0.0 {
6076                tangent = [-tangent[0], -tangent[1]];
6077            }
6078            let next = settle([last[0] + step * tangent[0], last[1] + step * tangent[1]])?;
6079            if next[1] < floor {
6080                break;
6081            }
6082            if next[0] <= 1e-3 || next[0] >= 1.0 - 1e-3 {
6083                return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6084            }
6085            if next[1] > window {
6086                return Err(refuse("end_trim_deep", "an end pose holds a deep part of a wall".into()));
6087            }
6088            if points.len() > 20_000 {
6089                return Err(refuse("end_trim", "the cut of an end pose does not close".into()));
6090            }
6091            heading = [next[0] - last[0], next[1] - last[1]];
6092            points.push(next);
6093        }
6094        let back = *points.last().expect("points");
6095        let Some(at_end) = unused.iter().position(|&c| (back[0] - c).abs() <= 2.0 * step) else {
6096            return Err(refuse("end_trim", "the cut of an end pose does not come back where it should".into()));
6097        };
6098        let back_at = unused.remove(at_end);
6099        // A dip that never rises off the floor and comes straight back is
6100        // the fit's noise at the end, not a bulge.
6101        if points.len() == 1 && (back_at - start).abs() <= step {
6102            continue;
6103        }
6104        points.push([back_at, floor]);
6105        // Down to the end itself along the cut's direction at the floor (taken
6106        // from the first point clearly above it).
6107        let to_end = |p: [f64; 2], rest: &[[f64; 2]], reversed: bool| -> Result<[f64; 2], KernelRefusal> {
6108            // Along the cut's own tangent there (across the gradient of f), so
6109            // the run to the end continues it smoothly.
6110            let g = gradient(p[0], p[1])?;
6111            if g[0].abs() > 1e-3 * g[1].abs() {
6112                return Ok([p[0] + g[1] / g[0] * p[1], 0.0]);
6113            }
6114            let clear = |q: &&[f64; 2]| q[1] - p[1] > 0.25 * step;
6115            let found = if reversed { rest.iter().rev().find(clear) } else { rest.iter().find(clear) };
6116            Ok(match found {
6117                Some(q) => [p[0] - (q[0] - p[0]) / (q[1] - p[1]) * p[1], 0.0],
6118                None => [p[0], 0.0],
6119            })
6120        };
6121        let count = points.len();
6122        let (first, last) = (to_end(points[0], &points[1..], false)?, to_end(points[count - 1], &points[..count - 1], true)?);
6123        if [first[0], last[0]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
6124            return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6125        }
6126        points.insert(0, first);
6127        points.push(last);
6128        if points[0][0] > points[points.len() - 1][0] {
6129            points.reverse();
6130        }
6131        cuts.push(points);
6132    }
6133    let rings: Vec<&[[f64; 2]]> = cuts.iter().map(|c| c.as_slice()).collect();
6134    pierced(&f, floor, window, noise, &rings)?;
6135    let chart = |p: [f64; 2]| [p[0], v_of(p[1])];
6136    // A curve on the wall through chart points and its pcurve, both on the
6137    // given parameters (normalized to [0, 1]); chart-length parameters by
6138    // default (the wall's own speed collapses near an edge of regression, so
6139    // 3D chord lengths would bunch them).
6140    let chart_lengths = |chart_points: &[[f64; 2]]| -> Vec<f64> {
6141        let mut params = vec![0.0];
6142        for k in 1..chart_points.len() {
6143            let gap = (chart_points[k][0] - chart_points[k - 1][0]).hypot(chart_points[k][1] - chart_points[k - 1][1]);
6144            params.push(params[k - 1] + gap.max(1e-15));
6145        }
6146        params
6147    };
6148    // Returns the curve, its pcurve, and how far the pcurve's image strays
6149    // from the curve between the points.
6150    let curve_through = |chart_points: &[[f64; 2]], params: &[f64], what: &'static str| -> Result<(NurbsCurve, NurbsCurve, f64), KernelRefusal> {
6151        let total = *params.last().expect("params");
6152        let params: Vec<f64> = params.iter().map(|x| x / total).collect();
6153        let world: Vec<Vec3> = chart_points.iter().map(|p| at(p[0], p[1])).collect::<Result<_, _>>()?;
6154        let uv: Vec<Vec3> = chart_points.iter().map(|p| Vec3::new(p[0], v_of(p[1]), 0.0)).collect();
6155        let (curve, pcurve) = (frag(crate::interpolate_curve(&world, 5, &params), what)?, frag(crate::interpolate_curve(&uv, 5, &params), what)?);
6156        // Between the points too: the pcurve's image stays on the curve.
6157        let mut worst = 0.0f64;
6158        for k in 0..params.len() - 1 {
6159            let s = 0.5 * (params[k] + params[k + 1]);
6160            let q = frag(pcurve.evaluate(s), "pcurve")?;
6161            let e = if end == 1 { 1.0 - q.y } else { q.y };
6162            worst = worst.max(at(q.x, e)?.sub(frag(curve.evaluate(s), "curve")?).length());
6163        }
6164        Ok((curve, pcurve, worst))
6165    };
6166    // A trim curve is refined until its pcurve's image is within `fine` of
6167    // it, and taken as near as it gets if within `loose` (a double curve has
6168    // a cusp at its swallowtail's point, where no finer trace helps; a
6169    // tighter bar costs a thin tool many rounds and buys no reader anything).
6170    let (fine, loose) = (1e-7 * split.scale, 1e-7 * split.scale);
6171    let missed = |what: &str| refuse("end_trim", format!("the {what}'s pcurve leaves it between its points however finely it is traced"));
6172    // The cut, refined where its fit misses: a settled point between each
6173    // pair of traced ones (on the stretches run straight to the end, their
6174    // middles).
6175    let cut_through = |mut chart_points: Vec<[f64; 2]>| -> Result<(NurbsCurve, NurbsCurve), KernelRefusal> {
6176        let mut best: Option<(NurbsCurve, NurbsCurve, f64)> = None;
6177        for _ in 0..7 {
6178            let fitted = curve_through(&chart_points, &chart_lengths(&chart_points), "cut")?;
6179            let done = fitted.2 <= fine;
6180            if best.as_ref().map_or(true, |b| fitted.2 < b.2) {
6181                best = Some(fitted);
6182            }
6183            if done {
6184                break;
6185            }
6186            let mut finer = Vec::with_capacity(2 * chart_points.len());
6187            for k in 0..chart_points.len() - 1 {
6188                finer.push(chart_points[k]);
6189                let (p, q) = (chart_points[k], chart_points[k + 1]);
6190                let middle = [0.5 * (p[0] + q[0]), 0.5 * (p[1] + q[1])];
6191                // Below the floor the cut runs straight to the end: split it there as a line.
6192                finer.push(if p[1] >= floor && q[1] >= floor { settle(middle)? } else { middle });
6193            }
6194            finer.push(chart_points[chart_points.len() - 1]);
6195            chart_points = finer;
6196        }
6197        match best {
6198            Some((curve, pcurve, worst)) if worst <= loose => Ok((curve, pcurve)),
6199            _ => Err(missed("cut")),
6200        }
6201    };
6202    let piece = |a: f64, b: f64| -> Result<NurbsCurve, KernelRefusal> {
6203        let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
6204        let along: Vec<Vec3> = ts.iter().map(|&s| at(a + (b - a) * s, 0.0)).collect::<Result<_, _>>()?;
6205        frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
6206    };
6207    // Where the wall turns over near the end (a swallowtail), the cut passes
6208    // through a point of the end's own loop K a second time, on the wall's far
6209    // sheet: there the wall's double curve starts, and the trim follows it to
6210    // the swallowtail's point and back instead of the cut's first stretch.
6211    let span_of = |points: &Vec<[f64; 2]>| -> Result<TrimSpan, KernelRefusal> {
6212        if let Some((k, ua, b)) = double_start(&at, points, floor)? {
6213            // The double curve, traced more finely while its fit misses.
6214            let mut traced: Option<(Vec<[f64; 2]>, Vec<[f64; 2]>, NurbsCurve, NurbsCurve, NurbsCurve, f64)> = None;
6215            for round in 0..5 {
6216                let (a_side, b_side) = double_curve(&at, [ua, 0.0], b, window, 2e-3 / f64::from(1u32 << round))?;
6217                // Both sides on the continuation's own arc length, so the double
6218                // curve and its two pcurves share one parameter.
6219                let mut sigma = vec![0.0];
6220                for k in 1..a_side.len() {
6221                    let step = (a_side[k][0] - a_side[k - 1][0]).hypot(a_side[k][1] - a_side[k - 1][1]).hypot((b_side[k][0] - b_side[k - 1][0]).hypot(b_side[k][1] - b_side[k - 1][1]));
6222                    sigma.push(sigma[k - 1] + step.max(1e-15));
6223                }
6224                let ((slot, pa, miss_a), (_, pb, miss_b)) = (curve_through(&a_side, &sigma, "double_curve")?, curve_through(&b_side, &sigma, "double_curve")?);
6225                let worst = miss_a.max(miss_b);
6226                if traced.as_ref().map_or(true, |t| worst < t.5) {
6227                    traced = Some((a_side, b_side, slot, pa, pb, worst));
6228                }
6229                if worst <= fine {
6230                    break;
6231                }
6232            }
6233            let Some((a_side, b_side, slot, pa, pb, _)) = traced.filter(|t| t.5 <= loose) else { return Err(missed("double curve")) };
6234            // The cut keeps the stretch from the far sheet's point to its end away
6235            // from where the double curve leaves K.
6236            let low = ua < points[0][0];
6237            if !low && ua <= points[points.len() - 1][0] {
6238                return Err(refuse("end_trim", "the double curve of a wall leaves its end inside the cut".into()));
6239            }
6240            let mut kept: Vec<[f64; 2]> = if low { points[k..].to_vec() } else { points[..=k].to_vec() };
6241            if low { kept[0] = b } else { *kept.last_mut().expect("kept") = b }
6242            let (cut, cut_pcurve) = cut_through(kept.clone())?;
6243            let tip = at(a_side[a_side.len() - 1][0], a_side[a_side.len() - 1][1])?;
6244            // The wall's side of the trim from the low end to the high one.
6245            let chain = if low {
6246                vec![(TrimPiece::Slot, true, pa), (TrimPiece::Slot, false, frag(pb.reversed(), "reversed")?), (TrimPiece::Cut, true, cut_pcurve)]
6247            } else {
6248                vec![(TrimPiece::Cut, true, cut_pcurve), (TrimPiece::Slot, true, pb), (TrimPiece::Slot, false, frag(pa.reversed(), "reversed")?)]
6249            };
6250            let lambdas = if low { [ua, points[points.len() - 1][0]] } else { [points[0][0], ua] };
6251            let mut removed: Vec<[f64; 2]> = Vec::new();
6252            if low {
6253                removed.extend(a_side.iter().map(|&p| chart(p)));
6254                removed.extend(b_side.iter().rev().map(|&p| chart(p)));
6255                removed.extend(kept.iter().map(|&p| chart(p)));
6256            } else {
6257                removed.extend(kept.iter().map(|&p| chart(p)));
6258                removed.extend(b_side.iter().map(|&p| chart(p)));
6259                removed.extend(a_side.iter().rev().map(|&p| chart(p)));
6260            }
6261            // Everything the end pose holds must be in what goes.
6262            let dropped: Vec<[f64; 2]> = if low { points[..k].to_vec() } else { points[k + 1..].to_vec() };
6263            for p in dropped.iter().filter(|p| p[1] > 2.0 * floor && (p[0] - b[0]).hypot(p[1] - b[1]) > 5e-3) {
6264                if !inside_ring(&removed, chart(*p)) {
6265                    return Err(refuse("end_trim", "the cut of an end pose leaves the part of the wall its double curve takes away".into()));
6266                }
6267            }
6268            let points3 = [at(lambdas[0], 0.0)?, at(lambdas[1], 0.0)?];
6269            // The double curve's sides part about its end: one keeps to
6270            // each side of the swallowtail's point along the loop, so a
6271            // line through that point splits the wall between them.
6272            let tip_chart = chart(a_side[a_side.len() - 1]);
6273            let side = |points: &[[f64; 2]]| points.iter().map(|q| q[0] - tip_chart[0]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| (lo.min(d), hi.max(d)));
6274            let ((a_lo, a_hi), (b_lo, b_hi)) = (side(&a_side), side(&b_side));
6275            let parted = (a_lo >= -1e-9 && b_hi <= 1e-9) || (a_hi <= 1e-9 && b_lo >= -1e-9);
6276            if !parted {
6277                return Err(refuse("end_trim", "the two sides of a wall's double curve do not keep to either side of its end".into()));
6278            }
6279            return Ok(TrimSpan { lambdas, points: points3, cut: Some(cut), chain, slot: Some((slot, tip)), tip: Some(tip_chart), removed });
6280        }
6281        let (cut, wall_pcurve) = cut_through(points.clone())?;
6282        let (la, lb) = (points[0][0], points[points.len() - 1][0]);
6283        let removed: Vec<[f64; 2]> = points.iter().map(|&p| chart(p)).collect();
6284        Ok(TrimSpan { lambdas: [la, lb], points: [at(la, 0.0)?, at(lb, 0.0)?], cut: Some(cut), chain: vec![(TrimPiece::Cut, true, wall_pcurve)], slot: None, tip: None, removed })
6285    };
6286    if cuts.is_empty() {
6287        return pierced(&f, floor, window, noise, &[]);
6288    }
6289    let mut spans = Vec::with_capacity(cuts.len());
6290    for points in &cuts {
6291        spans.push(span_of(points)?);
6292    }
6293    spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
6294    // A trim wholly inside what another takes away adds nothing (a bulge of
6295    // the end pose inside a swallowtail's slot).
6296    let edge_row = v_of(0.0);
6297    let within = |inner: &TrimSpan, outer: &TrimSpan| -> bool {
6298        inner.lambdas[0] >= outer.lambdas[0]
6299            && inner.lambdas[1] <= outer.lambdas[1]
6300            && inner.removed.iter().filter(|p| (p[1] - edge_row).abs() > floor).all(|&p| inside_ring(&outer.removed, p) || near_ring(&outer.removed, p, 1e-3))
6301    };
6302    let mut k = 0;
6303    while k < spans.len() {
6304        if (0..spans.len()).any(|j| j != k && within(&spans[k], &spans[j])) {
6305            spans.remove(k);
6306        } else {
6307            k += 1;
6308        }
6309    }
6310    for pair in spans.windows(2) {
6311        if pair[0].lambdas[1] >= pair[1].lambdas[0] {
6312            return Err(refuse("end_trim", "an end pose's trims of a wall overlap".into()));
6313        }
6314    }
6315    let mut pieces = Vec::with_capacity(spans.len() + 1);
6316    let mut from = 0.0;
6317    for span in &spans {
6318        pieces.push(piece(from, span.lambdas[0])?);
6319        from = span.lambdas[1];
6320    }
6321    pieces.push(piece(from, 1.0)?);
6322    Ok(Some(EndTrim { spans, pieces }))
6323}
6324
6325
6326
6327/// Is q within `reach` of the closed polygon `ring`'s sides?
6328fn near_ring(ring: &[[f64; 2]], q: [f64; 2], reach: f64) -> bool {
6329    (0..ring.len()).any(|k| {
6330        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6331        let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
6332        let length = dx * dx + dy * dy;
6333        let s = if length > 0.0 { (((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / length).clamp(0.0, 1.0) } else { 0.0 };
6334        (q[0] - a[0] - s * dx).hypot(q[1] - a[1] - s * dy) < reach
6335    })
6336}
6337
6338/// Is q inside the closed polygon `ring` (its last point joins its first)?
6339fn inside_ring(ring: &[[f64; 2]], q: [f64; 2]) -> bool {
6340    let mut crossings = 0;
6341    for k in 0..ring.len() {
6342        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6343        if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
6344            crossings += 1;
6345        }
6346    }
6347    crossings % 2 == 1
6348}
6349
6350/// The point of an end pose's cut (chart points (u, ε), ε the time fraction
6351/// from the end) that lies on the end's own loop K a second time, away from
6352/// the cut's ends: (its index along the cut, the loop parameter u of the point
6353/// of K it meets, and the refined (u, ε) on the cut), if there is one.
6354fn double_start(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, points: &[[f64; 2]], floor: f64) -> Result<Option<(usize, f64, [f64; 2])>, KernelRefusal> {
6355    let n = 4000;
6356    let row: Vec<Vec3> = (0..=n).map(|i| at(i as f64 / n as f64, 0.0)).collect::<Result<_, _>>()?;
6357    let scale = row.iter().fold(0.0f64, |m, p| m.max(p.sub(row[0]).length())).max(1e-300);
6358    let mut best: Option<(f64, usize, usize)> = None;
6359    for (k, p) in points.iter().enumerate() {
6360        if p[1] < 4.0 * floor {
6361            continue;
6362        }
6363        let x = at(p[0], p[1])?;
6364        let (i, d) = row.iter().enumerate().map(|(i, q)| (i, q.sub(x).length())).fold((0, f64::INFINITY), |a, b| if b.1 < a.1 { b } else { a });
6365        // The cut nears K at its own ends in proportion to ε; the second
6366        // meeting is where that ratio drops to nothing.
6367        if best.map_or(true, |b| d / p[1] < b.0 / points[b.1][1]) {
6368            best = Some((d, k, i));
6369        }
6370    }
6371    let Some((distance, k, i)) = best else { return Ok(None) };
6372    // Coarse: the cut's points are a few thousandths of the chart apart.
6373    if distance > 5e-3 * scale {
6374        return Ok(None);
6375    }
6376    // Newton on at(b) = at(u, 0) for (b_u, b_ε, u).
6377    let mut x = [points[k][0], points[k][1], i as f64 / n as f64];
6378    let h = 1e-7;
6379    for _ in 0..40 {
6380        let g = at(x[0], x[1])?.sub(at(x[2], 0.0)?);
6381        if g.length() < 1e-13 * scale {
6382            // Not the trivial meeting of the end row with itself.
6383            if x[1] < 2.0 * floor || !(0.0..=1.0).contains(&x[0]) || !(0.0..=1.0).contains(&x[2]) {
6384                return Ok(None);
6385            }
6386            return Ok(Some((k, x[2], [x[0], x[1]])));
6387        }
6388        let c0 = at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h);
6389        let c1 = at(x[0], x[1] + h)?.sub(at(x[0], x[1] - h)?).scale(0.5 / h);
6390        let c2 = at(x[2] + h, 0.0)?.sub(at(x[2] - h, 0.0)?).scale(-0.5 / h);
6391        let det = c0.dot(c1.cross(c2));
6392        if det.abs() < 1e-300 {
6393            break;
6394        }
6395        // Cramer's rule for [c0 c1 c2] d = -g.
6396        let r = g.scale(-1.0);
6397        let d = [r.dot(c1.cross(c2)) / det, c0.dot(r.cross(c2)) / det, c0.dot(c1.cross(r)) / det];
6398        x = [x[0] + d[0], x[1] + d[1], x[2] + d[2]];
6399    }
6400    if distance < 1e-6 * scale {
6401        return Err(refuse("end_trim", "an end pose's cut meets its own loop, but not exactly enough to follow".into()));
6402    }
6403    Ok(None)
6404}
6405
6406/// The double curve of a wall from where it leaves the end (a, on the end's
6407/// loop) and its partner b on the far sheet, traced by continuation of
6408/// at(a) = at(b) in (u, ε) for both, to the swallowtail point where the two
6409/// sides meet. Returns both sides' chart points, ending at the same point.
6410fn double_curve(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, a: [f64; 2], b: [f64; 2], window: f64, step: f64) -> Result<(Vec<[f64; 2]>, Vec<[f64; 2]>), KernelRefusal> {
6411    let h = 1e-7;
6412    let scale = at(0.0, 0.0)?.sub(at(1.0, 0.0)?).length().max(at(0.5, 0.0)?.sub(at(0.0, 0.0)?).length()).max(1e-300);
6413    let jacobian = |x: [f64; 4]| -> Result<[Vec3; 4], KernelRefusal> {
6414        Ok([
6415            at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h),
6416            at(x[0], x[1] + h)?.sub(at(x[0], (x[1] - h).max(0.0))?).scale(1.0 / (h + x[1].min(h))),
6417            at(x[2] + h, x[3])?.sub(at(x[2] - h, x[3])?).scale(-0.5 / h),
6418            at(x[2], x[3] + h)?.sub(at(x[2], (x[3] - h).max(0.0))?).scale(-1.0 / (h + x[3].min(h))),
6419        ])
6420    };
6421    let residual = |x: [f64; 4]| -> Result<Vec3, KernelRefusal> { Ok(at(x[0], x[1])?.sub(at(x[2], x[3])?)) };
6422    // The null direction of the 3x4 Jacobian: its signed 3x3 minors.
6423    let null = |j: &[Vec3; 4]| -> [f64; 4] {
6424        let minor = |p: usize, q: usize, r: usize| j[p].dot(j[q].cross(j[r]));
6425        let n = [minor(1, 2, 3), -minor(0, 2, 3), minor(0, 1, 3), -minor(0, 1, 2)];
6426        let length = n.iter().map(|x| x * x).sum::<f64>().sqrt().max(1e-300);
6427        [n[0] / length, n[1] / length, n[2] / length, n[3] / length]
6428    };
6429    // Minimum-norm Newton back onto at(a) = at(b).
6430    let correct = |mut x: [f64; 4]| -> Result<Option<[f64; 4]>, KernelRefusal> {
6431        for _ in 0..30 {
6432            let g = residual(x)?;
6433            if g.length() < 1e-13 * scale {
6434                return Ok(Some(x));
6435            }
6436            let j = jacobian(x)?;
6437            // J Jᵀ y = -g, step = Jᵀ y.
6438            let mut m = [[0.0; 3]; 3];
6439            let rows = [[j[0].x, j[1].x, j[2].x, j[3].x], [j[0].y, j[1].y, j[2].y, j[3].y], [j[0].z, j[1].z, j[2].z, j[3].z]];
6440            for p in 0..3 {
6441                for q in 0..3 {
6442                    m[p][q] = (0..4).map(|c| rows[p][c] * rows[q][c]).sum();
6443                }
6444            }
6445            let det = 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]);
6446            if det.abs() < 1e-300 {
6447                return Ok(None);
6448            }
6449            let r = [-g.x, -g.y, -g.z];
6450            let solve = |col: usize| -> f64 {
6451                let mut a = m;
6452                for p in 0..3 {
6453                    a[p][col] = r[p];
6454                }
6455                (a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])) / det
6456            };
6457            let y = [solve(0), solve(1), solve(2)];
6458            for c in 0..4 {
6459                x[c] += (0..3).map(|p| rows[p][c] * y[p]).sum::<f64>();
6460            }
6461        }
6462        Ok(None)
6463    };
6464    let mut x = [a[0], a[1], b[0], b[1]];
6465    let mut a_side = vec![a];
6466    let mut b_side = vec![b];
6467    let mut heading: Option<[f64; 4]> = None;
6468    loop {
6469        let separation = (x[0] - x[2]).hypot(x[1] - x[3]);
6470        if separation < 3.0 * step && a_side.len() > 2 {
6471            let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6472            a_side.push(tip);
6473            b_side.push(tip);
6474            return Ok((a_side, b_side));
6475        }
6476        let mut t = null(&jacobian(x)?);
6477        let reference = heading.unwrap_or([0.0, 1.0, 0.0, 0.0]);
6478        if (0..4).map(|c| t[c] * reference[c]).sum::<f64>() < 0.0 {
6479            t = [-t[0], -t[1], -t[2], -t[3]];
6480        }
6481        let mut next = None;
6482        let mut length = step;
6483        for _ in 0..6 {
6484            let guess = [x[0] + length * t[0], x[1] + length * t[1], x[2] + length * t[2], x[3] + length * t[3]];
6485            if let Some(y) = correct(guess)? {
6486                next = Some(y);
6487                break;
6488            }
6489            length *= 0.5;
6490        }
6491        let Some(y) = next else {
6492            // Near the swallowtail's point the two sheets turn tangent and
6493            // Newton gives out; close there if the sides are that near.
6494            if separation < 2e-2 && a_side.len() > 2 {
6495                let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6496                a_side.push(tip);
6497                b_side.push(tip);
6498                return Ok((a_side, b_side));
6499            }
6500            return Err(refuse("end_trim", format!("the double curve of a wall cannot be followed (sides {separation:e} apart)")));
6501        };
6502        if [y[0], y[2]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
6503            return Err(refuse("end_trim_corner", DOUBLE_CURVE_CORNER.into()));
6504        }
6505        if y[1] > window || y[3] > window || y[1] < 0.0 || y[3] < 0.0 {
6506            return Err(refuse("end_trim_deep", format!("the double curve of a wall runs deep into the motion or back past its end (its sides at time fractions {:.4} and {:.4} from the end, {} points in)", y[1], y[3], a_side.len())));
6507        }
6508        if a_side.len() > 20_000 {
6509            return Err(refuse("end_trim", "the double curve of a wall does not close".into()));
6510        }
6511        heading = Some([y[0] - x[0], y[1] - x[1], y[2] - x[2], y[3] - x[3]]);
6512        x = y;
6513        a_side.push([x[0], x[1]]);
6514        b_side.push([x[2], x[3]]);
6515    }
6516}
6517
6518/// Refuse a wall the end pose holds a part of that no cut encloses: a pocket
6519/// of the wall inside the pose away from the end.
6520fn pierced(
6521    f: &dyn Fn(f64, f64) -> Result<f64, KernelRefusal>,
6522    floor: f64,
6523    window: f64,
6524    noise: f64,
6525    cuts: &[&[[f64; 2]]],
6526) -> Result<Option<EndTrim>, KernelRefusal> {
6527    let enclosed = |q: [f64; 2]| -> bool { cuts.iter().any(|ring| inside_ring(ring, q)) };
6528    for i in 1..200 {
6529        for j in 1..=40 {
6530            let (u, e) = (i as f64 / 200.0, floor + (window - floor) * (j as f64 / 40.0).powi(2));
6531            // d itself against the fit's noise: f grows as 1 / ε² near the end.
6532            if f(u, e)? * e * e < -noise * floor * floor && !enclosed([u, e]) {
6533                return Err(refuse("end_trim_deep", "an end pose holds a part of a wall away from its end".into()));
6534            }
6535        }
6536    }
6537    Ok(None)
6538}
6539
6540#[allow(clippy::too_many_arguments)]
6541fn assemble_lofted(
6542    screw: &Screw,
6543    first: &Split,
6544    last: &Split,
6545    walls: &[(usize, bool, NurbsSurface, NurbsCurve, NurbsCurve)],
6546    times: &[f64],
6547    paths: &HashMap<usize, Vec<Vec3>>,
6548    fit: f64,
6549) -> Result<BrepSolid, KernelRefusal> {
6550    let mut shell = Shell::new();
6551    let ends = [(first, screw.t0), (last, screw.t1)];
6552    // Where an end pose bulges past a wall near its grazing loop (a saddle side
6553    // curving past the wall it touches), cut the wall back to where it
6554    // re-enters the pose and carry the end cap across the loop to there.
6555    let mut trims: HashMap<(usize, usize), EndTrim> = HashMap::new();
6556    // Walls split into strips along lines through their swallowtails' points.
6557    let mut split_walls: std::collections::HashSet<usize> = std::collections::HashSet::new();
6558    for (index, (_, _, surface, _, _)) in walls.iter().enumerate() {
6559        for end in 0..2 {
6560            if let Some(trim) = end_trim(screw, ends[end].0, ends[end].1, surface, end, fit)? {
6561                trims.insert((index, end), trim);
6562            }
6563        }
6564        let removed: Vec<&[[f64; 2]]> = (0..2).filter_map(|end| trims.get(&(index, end))).flat_map(|trim| trim.spans.iter().map(|span| span.removed.as_slice())).collect();
6565        wall_regular(surface, times, &removed, fit)?;
6566        // A trim along a double curve has that curve as one edge on both its
6567        // sides: on one face its two uses could not be told apart from its
6568        // 3D curve alone (the wall passes through it twice). The wall is split
6569        // along the parameter line from each swallowtail's point to the far
6570        // end's row, which that row is broken at.
6571        let tips_at = |end: usize| -> Vec<[f64; 2]> { trims.get(&(index, end)).map(|trim| trim.spans.iter().filter_map(|span| span.tip).collect()).unwrap_or_default() };
6572        let (tips0, tips1) = (tips_at(0), tips_at(1));
6573        if !tips0.is_empty() && !tips1.is_empty() {
6574            return Err(refuse("wall_split", "a wall turns over near both its ends".into()));
6575        }
6576        let (far, tips) = if tips0.is_empty() { (0usize, tips1) } else { (1usize, tips0) };
6577        // A straight split line serves only where the trimmed row keeps to
6578        // its own side of it: all that comes before the swallowtail's point
6579        // along the row at or below its u, all after at or above. (A cut
6580        // that bulges across it would be crossed by the line; such a wall
6581        // stays one face.)
6582        let straight = |trim: &EndTrim| -> Result<bool, KernelRefusal> {
6583            for (k, span) in trim.spans.iter().enumerate() {
6584                let Some(tip) = span.tip else { continue };
6585                let first_slot = span.chain.iter().position(|piece| piece.0 == TrimPiece::Slot).unwrap_or(0);
6586                for (j, other) in trim.spans.iter().enumerate() {
6587                    for (n, (_, _, pcurve)) in other.chain.iter().enumerate() {
6588                        let before = j < k || (j == k && n <= first_slot);
6589                        let [d0, d1] = frag(pcurve.domain(), "domain")?;
6590                        for i in 0..=32 {
6591                            let u = frag(pcurve.evaluate(d0 + (d1 - d0) * i as f64 / 32.0), "pcurve")?.x;
6592                            if (before && u > tip[0] + 1e-9) || (!before && u < tip[0] - 1e-9) {
6593                                return Ok(false);
6594                            }
6595                        }
6596                    }
6597                }
6598            }
6599            Ok(true)
6600        };
6601        // Or, where the trimmed row strays across the tip's u only beyond the
6602        // tip (near its own end), the split segment itself: from the tip to
6603        // the far row, crossed by none of either end's trim curves. Each strip
6604        // then lies on the wall over the u its own pcurves span.
6605        let crossing_free = |trim_near: &EndTrim| -> Result<bool, KernelRefusal> {
6606            let v_far = far as f64;
6607            for tip in &tips {
6608                let (v_lo, v_hi) = if v_far < tip[1] { (v_far, tip[1]) } else { (tip[1], v_far) };
6609                let ends = [Some(trim_near), trims.get(&(index, far))];
6610                for trim in ends.into_iter().flatten() {
6611                    for span in &trim.spans {
6612                        for (_, _, pcurve) in &span.chain {
6613                            if hull_meets_segment(pcurve, tip, v_lo, v_hi)? {
6614                                return Ok(false);
6615                            }
6616                        }
6617                    }
6618                }
6619            }
6620            Ok(true)
6621        };
6622        let split_here = !tips.is_empty()
6623            && match trims.get(&(index, 1 - far)) {
6624                Some(trim) => straight(trim)? || (split_crossing_on() && crossing_free(trim)?),
6625                None => false,
6626            };
6627        if split_here {
6628            split_walls.insert(index);
6629            let v_far = far as f64;
6630            let mut spans = trims.remove(&(index, far)).map(|trim| trim.spans).unwrap_or_default();
6631            for tip in &tips {
6632                if spans.iter().any(|span| tip[0] > span.lambdas[0] - 1e-9 && tip[0] < span.lambdas[1] + 1e-9) || tip[0] <= 1e-9 || tip[0] >= 1.0 - 1e-9 {
6633                    return Err(refuse("wall_split", "a wall's split line lands in a trim of its far end".into()));
6634                }
6635                let point = frag(surface.evaluate(tip[0], v_far), "wall")?;
6636                spans.push(TrimSpan { lambdas: [tip[0], tip[0]], points: [point, point], cut: None, chain: Vec::new(), slot: None, tip: None, removed: Vec::new() });
6637            }
6638            spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
6639            let pieces = row_pieces(surface, v_far, &spans)?;
6640            trims.insert((index, far), EndTrim { spans, pieces });
6641        }
6642    }
6643    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
6644    let mut vertex = |shell: &mut Shell, end: usize, p: usize| -> u64 {
6645        *vertex_at.entry((end, p)).or_insert_with(|| shell.vertex(screw.apply(ends[end].1, ends[end].0.points[p])))
6646    };
6647    let grazing: HashMap<usize, usize> = walls.iter().enumerate().map(|(index, w)| (w.0, index)).collect();
6648    // Edges at each end: K curves from the walls' end rows (in the tool
6649    // curve's direction), the rest the end split's own curves moved.
6650    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
6651    let mut edge_curve: HashMap<(usize, usize), NurbsCurve> = HashMap::new();
6652    // Per trimmed wall end: the loop's piece edges, and each span's cut and
6653    // double-curve edges (u64::MAX where a span has none).
6654    let mut trim_edges: HashMap<(usize, usize), (Vec<u64>, Vec<[u64; 2]>)> = HashMap::new();
6655    // Per trimmed wall end and span: the vertex at its low end, and at the
6656    // swallowtail's point where it has one.
6657    let mut trim_vertices: HashMap<(usize, usize), Vec<(u64, Option<u64>)>> = HashMap::new();
6658    for end in 0..2 {
6659        let (split, t) = ends[end];
6660        for (c, tool_curve) in split.curves.iter().enumerate() {
6661            let used = split.caps.iter().any(|cap| cap.front == (end == 1) && cap.coedges.iter().any(|e| e.0 == c));
6662            if !used {
6663                continue;
6664            }
6665            if let Some(&index) = grazing.get(&c) {
6666                if let Some(trim) = trims.get(&(index, end)) {
6667                    // Pieces in the wall's direction: K up to the cut, the cut, K after it.
6668                    let back_forward = walls[index].1;
6669                    let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6670                    let (vf, vt) = (vertex(&mut shell, end, from), vertex(&mut shell, end, to));
6671                    let mut piece_edges = Vec::with_capacity(trim.pieces.len());
6672                    let mut span_edges = Vec::with_capacity(trim.spans.len());
6673                    let mut start = vf;
6674                    let mut span_vertices = Vec::with_capacity(trim.spans.len());
6675                    for (span, piece) in trim.spans.iter().zip(&trim.pieces) {
6676                        let va = shell.vertex(span.points[0]);
6677                        piece_edges.push(shell.edge(piece.clone(), start, va, false)?);
6678                        let Some(cut_curve) = &span.cut else {
6679                            // A break only: the row goes on from the same vertex.
6680                            span_edges.push([u64::MAX, u64::MAX]);
6681                            span_vertices.push((va, None));
6682                            start = va;
6683                            continue;
6684                        };
6685                        let vb = shell.vertex(span.points[1]);
6686                        let cut = shell.edge(cut_curve.clone(), va, vb, false)?;
6687                        // The double curve runs from where it leaves K (at
6688                        // the low end of the span if its chain starts with
6689                        // it) to the swallowtail's point.
6690                        let (slot, tip_vertex) = match &span.slot {
6691                            Some((curve, tip)) => {
6692                                let from = if span.chain[0].0 == TrimPiece::Slot { va } else { vb };
6693                                let tip = shell.vertex(*tip);
6694                                (shell.edge(curve.clone(), from, tip, false)?, Some(tip))
6695                            }
6696                            None => (u64::MAX, None),
6697                        };
6698                        span_edges.push([cut, slot]);
6699                        span_vertices.push((va, tip_vertex));
6700                        start = vb;
6701                    }
6702                    trim_vertices.insert((index, end), span_vertices);
6703                    piece_edges.push(shell.edge(trim.pieces[trim.pieces.len() - 1].clone(), start, vt, false)?);
6704                    trim_edges.insert((index, end), (piece_edges, span_edges));
6705                    continue;
6706                }
6707            }
6708            let curve = match grazing.get(&c) {
6709                Some(&index) => {
6710                    let (_, back_forward, _, row0, row1) = &walls[index];
6711                    let row = if end == 0 { row0 } else { row1 };
6712                    if *back_forward { frag(row.reversed(), "reversed")? } else { row.clone() }
6713                }
6714                None => screw.move_curve(t, &tool_curve.curve)?,
6715            };
6716            let (a, b) = (vertex(&mut shell, end, tool_curve.start), vertex(&mut shell, end, tool_curve.end));
6717            let edge = shell.edge(curve.clone(), a, b, tool_curve.degenerate)?;
6718            edge_at.insert((end, c), edge);
6719            edge_curve.insert((end, c), curve);
6720        }
6721    }
6722    for end in 0..2 {
6723        let (split, t) = ends[end];
6724        for cap in split.caps.iter().filter(|cap| cap.front == (end == 1)) {
6725            let surface = screw.move_surface(t, &cap.surface)?;
6726            let mut coedges = Vec::with_capacity(cap.coedges.len());
6727            for (c, forward, pcurve) in &cap.coedges {
6728                if let Some(&index) = grazing.get(c) {
6729                    if let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) {
6730                        let Some(chart) = cap.chart.as_ref() else {
6731                            return Err(refuse("end_trim", "an end pose bulges past a wall beside a cap without a chart".into()));
6732                        };
6733                        // The cap runs the tool's curve forward or back; the
6734                        // pieces run the wall's way: loop piece, cut, loop
6735                        // piece, ... loop piece.
6736                        let along = *forward != walls[index].1;
6737                        let mut pieces: Vec<(u64, &NurbsCurve)> = Vec::with_capacity(2 * trim.pieces.len());
6738                        for (k, piece) in trim.pieces.iter().enumerate() {
6739                            pieces.push((piece_edges[k], piece));
6740                            if let Some(cut) = trim.spans.get(k).and_then(|span| span.cut.as_ref()) {
6741                                pieces.push((span_edges[k][0], cut));
6742                            }
6743                        }
6744                        if !along {
6745                            pieces.reverse();
6746                        }
6747                        for (edge, curve) in pieces {
6748                            coedges.push((edge, along, charted_pcurve(chart, screw, t, curve, along)?));
6749                        }
6750                        continue;
6751                    }
6752                }
6753                let pcurve = if grazing.contains_key(c) && cap.chart.is_some() {
6754                    charted_pcurve(cap.chart.as_ref().expect("chart"), screw, t, &edge_curve[&(end, *c)], *forward)?
6755                } else if grazing.contains_key(c) {
6756                    match projected_pcurve(&surface, &edge_curve[&(end, *c)], *forward) {
6757                        Ok(p) => p,
6758                        Err(error) => {
6759                            // Which: the exact samples themselves, or the row between them?
6760                            let samples = split.curves[*c].samples.as_ref().map(|list| {
6761                                list.iter()
6762                                    .map(|&x| crate::project_point_to_surface(&surface, screw.apply(t, x)).map(|f| f.distance).unwrap_or(f64::NAN))
6763                                    .fold(0.0f64, f64::max)
6764                            });
6765                            let line = split.curves[*c].curve.degree;
6766                            return Err(KernelRefusal::unsupported(
6767                                KernelStage::Classify,
6768                                "loft_cap",
6769                                format!("{} (curve {c} of degree {line}, end {end}, its exact samples off the cap by {samples:?}, cap degrees {}x{})", error.message, surface.degree_u, surface.degree_v),
6770                            ));
6771                        }
6772                    }
6773                } else {
6774                    pcurve.clone()
6775                };
6776                coedges.push((edge_at[&(end, *c)], *forward, pcurve));
6777            }
6778            shell.face(surface, coedges);
6779        }
6780    }
6781    // Orbits of K's corners: interpolated through the sample times as the
6782    // walls' end columns are.
6783    let mut orbits: HashMap<usize, u64> = HashMap::new();
6784    let mut keys: Vec<usize> = paths.keys().copied().collect();
6785    keys.sort_unstable();
6786    for r in keys {
6787        let curve = frag(crate::interpolate_curve(&paths[&r], 5, times), "orbit")?;
6788        let (a, b) = (vertex(&mut shell, 0, r), vertex(&mut shell, 1, r));
6789        orbits.insert(r, shell.edge(curve, a, b, false)?);
6790    }
6791    // One piece of a wall's end row in the direction of u: (edge, traversed
6792    // forward?, pcurve that way), and where a split line meets the row right
6793    // after it: (u, v, vertex).
6794    type RowPiece = (u64, bool, NurbsCurve, Option<(f64, f64, u64)>);
6795    for (index, (c, back_forward, surface, _, _)) in walls.iter().enumerate() {
6796        let tool_curve = &first.curves[*c];
6797        let (from, to) = if *back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6798        let row = |end: usize| -> Result<Vec<RowPiece>, KernelRefusal> {
6799            let v = end as f64;
6800            let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) else {
6801                return Ok(vec![(edge_at[&(end, *c)], !*back_forward, uv_line([0.0, v], [1.0, v])?, None)]);
6802            };
6803            let vertices = &trim_vertices[&(index, end)];
6804            let mut list: Vec<RowPiece> = Vec::new();
6805            let mut at = 0.0;
6806            for (k, span) in trim.spans.iter().enumerate() {
6807                let broken = if span.cut.is_none() { Some((span.lambdas[0], v, vertices[k].0)) } else { None };
6808                list.push((piece_edges[k], true, uv_line([at, v], [span.lambdas[0], v])?, broken));
6809                for (n, (piece, forward, pcurve)) in span.chain.iter().enumerate() {
6810                    let edge = if *piece == TrimPiece::Cut { span_edges[k][0] } else { span_edges[k][1] };
6811                    // The swallowtail's point lies between the double curve's two uses.
6812                    let between = *piece == TrimPiece::Slot && span.chain.get(n + 1).is_some_and(|next| next.0 == TrimPiece::Slot);
6813                    let tip = match (span.tip, vertices[k].1) {
6814                        (Some(tip), Some(vertex)) if between && split_walls.contains(&index) => Some((tip[0], tip[1], vertex)),
6815                        _ => None,
6816                    };
6817                    list.push((edge, *forward, pcurve.clone(), tip));
6818                }
6819                at = span.lambdas[1];
6820            }
6821            list.push((piece_edges[trim.spans.len()], true, uv_line([at, v], [1.0, v])?, None));
6822            Ok(list)
6823        };
6824        let (bottom, top) = (row(0)?, row(1)?);
6825        let (low, high): (Vec<(f64, f64, u64)>, Vec<(f64, f64, u64)>) = (bottom.iter().filter_map(|piece| piece.3).collect(), top.iter().filter_map(|piece| piece.3).collect());
6826        if low.len() != high.len() || low.iter().zip(&high).any(|(a, b)| (a.0 - b.0).abs() > 1e-9) {
6827            return Err(refuse("wall_split", "a wall's split lines do not run from one end's row to the other's".into()));
6828        }
6829        // The split lines, each from its lower point to its upper.
6830        let mut lines: Vec<(u64, f64, f64, f64)> = Vec::with_capacity(low.len());
6831        for (below, above) in low.iter().zip(&high) {
6832            let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
6833            let along: Vec<Vec3> = ts.iter().map(|&s| frag(surface.evaluate(below.0, below.1 + (above.1 - below.1) * s), "wall")).collect::<Result<_, _>>()?;
6834            let edge = shell.edge(frag(crate::interpolate_curve(&along, 5, &ts), "split_line")?, below.2, above.2, false)?;
6835            lines.push((edge, below.0, below.1, above.1));
6836        }
6837        // Each row in the stretches between the split lines.
6838        let stretches = |list: Vec<RowPiece>| -> Vec<Vec<(u64, bool, NurbsCurve)>> {
6839            let mut out = vec![Vec::new()];
6840            for (edge, forward, pcurve, cut) in list {
6841                out.last_mut().expect("stretch").push((edge, forward, pcurve));
6842                if cut.is_some() {
6843                    out.push(Vec::new());
6844                }
6845            }
6846            out
6847        };
6848        let (bottoms, tops) = (stretches(bottom), stretches(top));
6849        // A strip between two split lines (or the wall's sides): along the
6850        // start row, up its far side, back along the end row, down its near
6851        // side; on the wall over its own stretch of u only.
6852        for j in 0..=lines.len() {
6853            let mut coedges = bottoms[j].clone();
6854            match lines.get(j) {
6855                Some(&(edge, u, v0, v1)) => coedges.push((edge, true, uv_line([u, v0], [u, v1])?)),
6856                None => coedges.push((orbits[&to], true, uv_line([1.0, 0.0], [1.0, 1.0])?)),
6857            }
6858            for (edge, forward, pcurve) in tops[j].iter().rev() {
6859                coedges.push((*edge, !*forward, frag(pcurve.reversed(), "reversed")?));
6860            }
6861            match j.checked_sub(1).map(|k| lines[k]) {
6862                Some((edge, u, v0, v1)) => coedges.push((edge, false, uv_line([u, v1], [u, v0])?)),
6863                None => coedges.push((orbits[&from], false, uv_line([0.0, 1.0], [0.0, 0.0])?)),
6864            }
6865            let (mut ua, mut ub) = (if j == 0 { 0.0 } else { lines[j - 1].1 }, lines.get(j).map_or(1.0, |line| line.1));
6866            // A strip whose trim strays past its split line (beyond the tip)
6867            // takes the wall over that u too: the parameters are the wall's.
6868            if lines.len() > 0 && split_crossing_on() {
6869                // Its control points bound each pcurve (positive weights).
6870                for (_, _, pcurve) in &coedges {
6871                    for point in &pcurve.control_points {
6872                        let u = point.x / point.w;
6873                        if u < ua - 1e-9 {
6874                            ua = u.max(0.0);
6875                        }
6876                        if u > ub + 1e-9 {
6877                            ub = u.min(1.0);
6878                        }
6879                    }
6880                }
6881            }
6882            shell.face(restrict_u(surface, ua, ub)?, coedges);
6883        }
6884    }
6885    let body = shell.solid();
6886    let issues = body.validate();
6887    if !issues.is_empty() {
6888        // Name the faces whose coedges stray: their pcurves' ends on the surface
6889        // against their edges' ends.
6890        let mut notes = Vec::new();
6891        for face in body.shells.iter().flat_map(|s| &s.faces) {
6892            for coedge in &face.loops[0].coedges {
6893                let edge = body.edges.iter().find(|e| e.id == coedge.edge_id).expect("edge");
6894                let [p0, p1] = frag(coedge.pcurve.domain(), "domain")?;
6895                let a = frag(coedge.pcurve.evaluate(p0), "uv")?;
6896                let on = frag(face.surface.evaluate_extended(a.x, a.y), "on")?;
6897                let at = frag(edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }), "at")?;
6898                if on.sub(at).length() > 1e-6 {
6899                    notes.push(format!("face {} (degrees {}x{}) coedge on edge {} starts {:?} on the surface, its edge {:?}", face.id, face.surface.degree_u, face.surface.degree_v, edge.id, on, at));
6900                }
6901                let _ = p1;
6902            }
6903        }
6904        return Err(refuse("assembly", format!("the lofted sweep is not valid: {:?}; {}", issues.first(), notes.iter().take(4).cloned().collect::<Vec<_>>().join("; "))));
6905    }
6906    check_single_pass(screw, first, &body, &std::collections::HashSet::new())?;
6907    Ok(body)
6908}
6909
6910/// Is the world point y inside the moving tool at some time of the motion?
6911/// Steps t by the distance over a bound on the speed of any tool point near y.
6912fn covered(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6913    // A ball carried by a frame along a cubic: the question read off the cubic
6914    // (`BREP_SWEEP_BALL_COVER`, default on; its check mode walks as well).
6915    if crate::solid_sweep_one_pass::ball_cover_on() {
6916        if let (Some(frame), None, Shape::Revolved { origin, axis, meridian }) = (&screw.frame, &screw.turns, &split.shape) {
6917            if let Some((centre, r)) = crate::solid_sweep_one_pass::ball_of_revolved(*origin, *axis, meridian) {
6918                let offset = centre.sub(screw.a).length();
6919                if let Some(answer) = crate::solid_sweep_one_pass::ball_on_cubic_covered(frame.control, screw.t0, screw.t1, offset, r, y, margin) {
6920                    if !crate::solid_sweep_one_pass::ball_cover_check_on() {
6921                        return Ok(answer);
6922                    }
6923                    let walked = covered_walk(screw, split, reach, y, normal, margin)?;
6924                    crate::solid_sweep_one_pass::ball_cover_check_record(walked == answer);
6925                    return Ok(walked);
6926                }
6927            }
6928        }
6929    }
6930    covered_walk(screw, split, reach, y, normal, margin)
6931}
6932
6933/// [`covered`] by walking the motion.
6934fn covered_walk(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6935    if reach.is_some_and(|reach| reach.never_inside(screw, y, normal, margin)) {
6936        return Ok(false);
6937    }
6938    if let Some(found) = reach.and_then(|reach| reach.turn_about_parallel_axis(screw, y, margin)) {
6939        return found;
6940    }
6941    let speed = preimage_speed_bound(screw, split, y);
6942    let floor = (screw.t1 - screw.t0) * 1e-7;
6943    let glide = Glide::of(screw, y);
6944    let mut t = screw.t0;
6945    let mut steps = 0usize;
6946    loop {
6947        let p = screw.invert(t, y);
6948        let d = split.distance(p);
6949        if d < -margin {
6950            return Ok(true);
6951        }
6952        if t >= screw.t1 {
6953            return Ok(false);
6954        }
6955        if steps > 2_000_000 {
6956            return Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into()));
6957        }
6958        let first = (d.abs() + margin) / speed;
6959        let second = glide.as_ref().map_or(0.0, |glide| glide.step(split, p, t, d, margin, speed, screw.t1 - t));
6960        let second = if second.is_finite() { second } else { 0.0 };
6961        t = (t + first.max(second).max(floor)).min(screw.t1);
6962        steps += 1;
6963    }
6964}
6965
6966/// The preimage of a probe under a plain screw, as an explicit curve: with
6967/// `u` the probe's offset from the axis square to it and `v = e × u`,
6968/// `p(t) = a + (e·(y − a) − advance(t))·e + cos(ωt)·u − sin(ωt)·v`. Its
6969/// second derivative is no longer than `ω²·|u| + 2|c₂|` (`curve`).
6970///
6971/// The walk in time steps by the tool's distance over the preimage's speed:
6972/// beside a wall the tool grazes (a thread's flank, a ball's groove) the
6973/// distance stays the probe's tiny offset through the whole contact and the
6974/// walk crawls, some π·√(2R/δ) steps a probe. Where the path runs along the
6975/// tool rather than into it, its tangent line stays clear of the tool for
6976/// far longer, and the path leaves that line by no more than `curve·h²/2`:
6977/// the second-order step is the longest `h` the tool's distance from the
6978/// tangent segment, less that, keeps above −margin. It is never shorter than
6979/// the first-order step, and skips no time the probe is deeper than the margin.
6980struct Glide {
6981    e: Vec3,
6982    u: Vec3,
6983    v: Vec3,
6984    omega: f64,
6985    c: f64,
6986    c2: f64,
6987    curve: f64,
6988    /// Under `frame_glide_on`, a frame riding a curve: the probe's preimage
6989    /// `a + R(−θ(t))(y − P(t))` read through the frame (frame, y).
6990    riding: Option<(Frame, Vec3)>,
6991    /// Under `turns_glide_on`, two turns about fixed axes: the probe's preimage under them (turns, y).
6992    turning: Option<(Turns, Vec3)>,
6993    /// Under `frame_windows_on`, the bound on |p''| over each of equal windows
6994    /// of the motion (start, width, bounds), each no looser than `curve`.
6995    windows: Option<(f64, f64, Vec<f64>)>,
6996}
6997
6998/// The riding frame's |p''| bound read window by window (default on; `=0`
6999/// keeps one bound over the whole motion). Either is a bound; a window's is
7000/// read where the step stays within it, so steps lengthen where the curve
7001/// bends gently.
7002fn frame_windows_on() -> bool {
7003    crate::switch!("BREP_SWEEP_FRAME_WINDOWS", true)
7004}
7005
7006/// The second-order step for two turns about fixed axes (`BREP_SWEEP_TURNS_GLIDE`, default on;
7007/// `=0` restores the first-order walk).
7008fn turns_glide_on() -> bool {
7009    crate::switch!("BREP_SWEEP_TURNS_GLIDE", true)
7010}
7011
7012/// The second-order step for frames riding a curve (default on; `=0` restores the first-order walk).
7013fn frame_glide_on() -> bool {
7014    crate::switch!("BREP_SWEEP_FRAME_GLIDE", true)
7015}
7016
7017impl Glide {
7018    fn of(screw: &Screw, y: Vec3) -> Option<Glide> {
7019        if let (Some(frame), None, true) = (&screw.frame, &screw.turns, frame_glide_on()) {
7020            return Glide::riding(screw, frame, y);
7021        }
7022        if let (Some(turns), true) = (&screw.turns, turns_glide_on()) {
7023            return Glide::turning(turns, y);
7024        }
7025        if screw.frame.is_some() || screw.turns.is_some() {
7026            return None;
7027        }
7028        let r = y.sub(screw.a);
7029        let u = r.sub(screw.e.scale(r.dot(screw.e)));
7030        let curve = screw.omega * screw.omega * u.length() + 2.0 * screw.c2.abs();
7031        // A bound rounded to nothing, or below the normal range, is not one:
7032        // only a slide (no turn, no rise) is straight.
7033        let straight = screw.omega == 0.0 && screw.c2 == 0.0;
7034        if !straight && !(curve >= f64::MIN_POSITIVE && curve.is_finite()) {
7035            return None;
7036        }
7037        Some(Glide { e: screw.e, u, v: screw.e.cross(u), omega: screw.omega, c: screw.c, c2: screw.c2, curve, riding: None, turning: None, windows: None })
7038    }
7039
7040    /// A frame riding a planar cubic: the preimage `p = a + R(−θ) q`,
7041    /// `q = y − P(t)`, turns about `up`, and its second derivative is
7042    /// `R(−θ)(θ'² up×(up×q) − θ'' up×q + 2θ' up×P' − P'')`, so
7043    /// `|p''| ≤ (θ'² + |θ''|)·|q| + 2|θ'|·|P'| + |P''|`. Over the motion's
7044    /// span |P'| and |P''| are bounded by their control polygons and |P'''|
7045    /// is a constant; `θ' = up·(P'×P'')/|P'|²` and θ'' are bounded through a
7046    /// lower bound on |P'| (its samples less |P''| times half their spacing;
7047    /// no glide where that is not positive); `|q| ≤ |y − P(t₀)| + |P'|·span`.
7048    fn riding(screw: &Screw, frame: &Frame, y: Vec3) -> Option<Glide> {
7049        let [p0, p1, p2, p3] = frame.control;
7050        let first = [p1.sub(p0), p2.sub(p1), p3.sub(p2)].map(|d| d.scale(3.0).length()).into_iter().fold(0.0f64, f64::max);
7051        let second = [p2.sub(p1.scale(2.0)).add(p0), p3.sub(p2.scale(2.0)).add(p1)].map(|d| d.scale(6.0).length()).into_iter().fold(0.0f64, f64::max);
7052        let third = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(6.0).length();
7053        let (t0, t1) = (screw.t0, screw.t1);
7054        let n = 256;
7055        let slowest = (0..=n).map(|k| frame.first(t0 + (t1 - t0) * k as f64 / n as f64).length()).fold(f64::INFINITY, f64::min);
7056        let floor = slowest - second * 0.5 * (t1 - t0) / n as f64;
7057        if !(floor > 0.0) {
7058            return None;
7059        }
7060        let w1 = first * second / (floor * floor);
7061        let w2 = third * first / (floor * floor) + 2.0 * first * first * second * second / floor.powi(4);
7062        let q = y.sub(frame.point(t0)).length() + first * (t1 - t0);
7063        let curve = (w1 * w1 + w2) * q + 2.0 * w1 * first + second;
7064        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
7065            return None;
7066        }
7067        // Window by window: |P'| by the hull of its quadratic over the window,
7068        // |P''| (linear) at the window's ends, the floor on |P'| from eight
7069        // samples less |P''| times half their spacing, |q| from the window's
7070        // start; each bound kept no looser than the whole motion's.
7071        let windows = frame_windows_on().then(|| {
7072            let count = 32usize;
7073            let width = (t1 - t0) / count as f64;
7074            let bounds = (0..count)
7075                .map(|i| {
7076                    let (a, b) = (t0 + width * i as f64, t0 + width * (i + 1) as f64);
7077                    let (da, db) = (frame.first(a), frame.first(b));
7078                    let middle = da.add(frame.second(a).scale(0.5 * (b - a)));
7079                    let first_w = da.length().max(db.length()).max(middle.length());
7080                    let second_w = frame.second(a).length().max(frame.second(b).length());
7081                    let m = 8;
7082                    let slow = (0..=m).map(|j| frame.first(a + (b - a) * j as f64 / m as f64).length()).fold(f64::INFINITY, f64::min);
7083                    let floor_w = slow - second_w * 0.5 * (b - a) / m as f64;
7084                    if !(floor_w > 0.0) {
7085                        return curve;
7086                    }
7087                    let w1 = first_w * second_w / (floor_w * floor_w);
7088                    let w2 = third * first_w / (floor_w * floor_w) + 2.0 * first_w * first_w * second_w * second_w / floor_w.powi(4);
7089                    let q_w = y.sub(frame.point(a)).length() + first_w * (b - a);
7090                    let c = (w1 * w1 + w2) * q_w + 2.0 * w1 * first_w + second_w;
7091                    if c.is_finite() && c >= f64::MIN_POSITIVE { c.min(curve) } else { curve }
7092                })
7093                .collect::<Vec<f64>>();
7094            (t0, width, bounds)
7095        });
7096        let zero = Vec3::new(0.0, 0.0, 0.0);
7097        Some(Glide { e: frame.up, u: zero, v: zero, omega: 0.0, c: 0.0, c2: 0.0, curve, riding: Some((*frame, y)), turning: None, windows })
7098    }
7099
7100    /// Two turns about fixed axes (unit `d₀`, `d₁` through `P₀`, `P₁` at rates `r₀`, `r₁`): the
7101    /// preimage `p = P₀ + R₀(−r₀t)(x − P₀)`, `x = P₁ + R₁(−r₁t)(y − P₁)`. With `x' = −r₁ d₁×(x − P₁)`
7102    /// and `x'' = −r₁ d₁×x'`, `p'' = R₀(x'') − 2r₀ d₀×R₀(x') + r₀² d₀×(d₀×(p − P₀))`, so
7103    /// `|p''| ≤ (r₁² + 2|r₀ r₁|)·|y − P₁| + r₀²·(|y − P₁| + |P₁ − P₀|)` (rotations keep lengths).
7104    fn turning(turns: &Turns, y: Vec3) -> Option<Glide> {
7105        let a = y.sub(turns.points[1]).length();
7106        let d = a + turns.points[1].sub(turns.points[0]).length();
7107        let (r0, r1) = (turns.rates[0].abs(), turns.rates[1].abs());
7108        let curve = (r1 * r1 + 2.0 * r0 * r1) * a + r0 * r0 * d;
7109        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
7110            return None;
7111        }
7112        let zero = Vec3::new(0.0, 0.0, 0.0);
7113        Some(Glide { e: zero, u: zero, v: zero, omega: 0.0, c: 0.0, c2: 0.0, curve, riding: None, turning: Some((*turns, y)), windows: None })
7114    }
7115
7116    /// The bound on |p''| over [t, t + h]: the most of the windows it meets,
7117    /// or the whole motion's.
7118    fn curve_over(&self, t: f64, h: f64) -> f64 {
7119        match &self.windows {
7120            Some((t0, width, bounds)) => {
7121                let last = bounds.len() - 1;
7122                let index = |x: f64| -> usize {
7123                    let k = ((x - t0) / width).floor();
7124                    if k.is_nan() || k <= 0.0 { 0 } else { (k as usize).min(last) }
7125                };
7126                bounds[index(t)..=index(t + h)].iter().fold(0.0f64, |a, &b| a.max(b))
7127            }
7128            None => self.curve,
7129        }
7130    }
7131
7132    /// `p'(t)`.
7133    fn velocity(&self, t: f64) -> Vec3 {
7134        if let Some((turns, y)) = &self.turning {
7135            let (p0, p1) = (turns.points[0], turns.points[1]);
7136            let (d0, d1) = (turns.directions[0], turns.directions[1]);
7137            let (r0, r1) = (turns.rates[0], turns.rates[1]);
7138            let arm1 = y.sub(p1).rotate_about(d1, -r1 * t);
7139            let x_rate = d1.cross(arm1).scale(-r1);
7140            let arm0 = p1.add(arm1).sub(p0).rotate_about(d0, -r0 * t);
7141            return x_rate.rotate_about(d0, -r0 * t).sub(d0.cross(arm0).scale(r0));
7142        }
7143        if let Some((frame, y)) = &self.riding {
7144            // p' = R(−θ)(−θ' up×q − P'), q = y − P(t).
7145            let q = y.sub(frame.point(t));
7146            let inner = frame.up.cross(q).scale(-frame.angle_rate(t)).sub(frame.first(t));
7147            return inner.rotate_about(frame.up, -frame.angle(t));
7148        }
7149        let (sin, cos) = (self.omega * t).sin_cos();
7150        self.e
7151            .scale(-(self.c + 2.0 * self.c2 * t))
7152            .sub(self.u.scale(self.omega * sin))
7153            .sub(self.v.scale(self.omega * cos))
7154    }
7155
7156    /// The second-order step from `t`, where the preimage is `p` at the
7157    /// tool's distance `d` (at most `left`; 0 when it finds none).
7158    #[allow(clippy::too_many_arguments)]
7159    fn step(&self, split: &Split, p: Vec3, t: f64, d: f64, margin: f64, speed: f64, left: f64) -> f64 {
7160        let velocity = self.velocity(t);
7161        // (the planes' root is read in closed form under one bound: the
7162        // windows' over the rest of the motion)
7163        let m = if self.windows.is_some() { self.curve_over(t, left) } else { self.curve };
7164        match &split.shape {
7165            // Each face's plane alone bounds the distance from below:
7166            // g(t + h) ≥ g + g'·h − m·h²/2, held above −margin up to the root.
7167            Shape::Planes(planes) => {
7168                let mut best = 0.0f64;
7169                for (n, offset) in planes {
7170                    let g = n.dot(p) - offset;
7171                    if g + margin <= 0.0 {
7172                        continue;
7173                    }
7174                    let slope = n.dot(velocity);
7175                    // The root, in the form that neither overflows nor cancels.
7176                    let h = if m > 0.0 {
7177                        let root = slope.hypot((2.0 * m * (g + margin)).sqrt());
7178                        if slope >= 0.0 { (slope + root) / m } else { 2.0 * (g + margin) / (root - slope) }
7179                    } else if slope >= 0.0 {
7180                        left
7181                    } else {
7182                        (g + margin) / -slope
7183                    };
7184                    if h.is_finite() {
7185                        best = best.max(h);
7186                    }
7187                }
7188                best.min(left)
7189            }
7190            // In the meridian plane: the path (ρ, z) about the tool's axis and
7191            // its tangent segment, whose distance from the outline is bounded
7192            // below piece by piece; the path leaves the segment by at most
7193            // m₂·h²/2, m₂ = 2m + speed²/ρ_min (the radius' bend), ρ_min > 0.
7194            Shape::Revolved { origin, axis, meridian } => {
7195                if d < 0.0 {
7196                    return 0.0;
7197                }
7198                let r = p.sub(*origin);
7199                let z = r.dot(*axis);
7200                let flat = r.sub(axis.scale(z));
7201                let rho = flat.length();
7202                if rho <= 0.0 {
7203                    return 0.0;
7204                }
7205                let dz = velocity.dot(*axis);
7206                let dflat = velocity.sub(axis.scale(dz));
7207                let drho = flat.dot(dflat) / rho;
7208                let q = [rho, z];
7209                let walk_sqrt = walk_sqrt_on();
7210                let mut best = 0.0f64;
7211                let mut h = (d + margin) / speed;
7212                for _ in 0..64 {
7213                    h *= 2.0;
7214                    if h > left {
7215                        h = left;
7216                    }
7217                    // Under the windows, the speed over [t, t + h] by the
7218                    // step's own: |p'| ≤ |p'(t)| + m·h, no more than `speed`.
7219                    let (m, speed) = if self.windows.is_some() {
7220                        let m = self.curve_over(t, h);
7221                        (m, (velocity.length() + m * h).min(speed))
7222                    } else {
7223                        (m, speed)
7224                    };
7225                    let low = rho - speed * h;
7226                    if low <= 0.0 {
7227                        break;
7228                    }
7229                    let bend = 2.0 * m + speed * speed / low;
7230                    let end = [rho + drho * h, z + dz * h];
7231                    let clear = if walk_sqrt {
7232                        meridian.iter().map(|piece| segment_clearance_sqrt(piece, q, end)).fold(f64::INFINITY, f64::min)
7233                    } else {
7234                        meridian.iter().map(|piece| segment_clearance(piece, q, end)).fold(f64::INFINITY, f64::min)
7235                    };
7236                    // A segment that touches the outline may enter the tool: no bound.
7237                    let held = clear - 0.5 * bend * h * h;
7238                    if !held.is_finite() || clear <= 0.0 || held < -margin {
7239                        break;
7240                    }
7241                    best = h;
7242                    if h >= left {
7243                        break;
7244                    }
7245                }
7246                best
7247            }
7248        }
7249    }
7250}
7251
7252/// A lower bound on the distance between the segment `a`–`b` and a meridian
7253/// piece: a line piece's exact distance (0 where they cross), an arc's from
7254/// its whole circle.
7255fn segment_clearance(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
7256    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
7257    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
7258    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
7259    let to_segment = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
7260        let d = sub(e, s);
7261        let len2 = dot(d, d);
7262        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
7263        let foot = [s[0] + d[0] * w, s[1] + d[1] * w];
7264        let gap = sub(x, foot);
7265        gap[0].hypot(gap[1])
7266    };
7267    match *piece {
7268        OutlinePiece::Line { from, to } => {
7269            let (d1, d2) = (sub(b, a), sub(to, from));
7270            let denom = cross(d1, d2);
7271            if denom != 0.0 {
7272                let w = sub(from, a);
7273                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
7274                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
7275                    return 0.0;
7276                }
7277            }
7278            to_segment(a, from, to).min(to_segment(b, from, to)).min(to_segment(from, a, b)).min(to_segment(to, a, b))
7279        }
7280        OutlinePiece::Arc { centre, radius, .. } => {
7281            let near = to_segment(centre, a, b);
7282            let far = { let (x, y) = (sub(a, centre), sub(b, centre)); x[0].hypot(x[1]).max(y[0].hypot(y[1])) };
7283            (near - radius).max(radius - far).max(0.0)
7284        }
7285        // no bound read for an ellipse: zero is one
7286        OutlinePiece::Ellipse { .. } => 0.0,
7287    }
7288}
7289
7290/// The switch for [`segment_clearance_sqrt`] in the walk's second-order step
7291/// (default on; `=0` reads `segment_clearance`).
7292fn walk_sqrt_on() -> bool {
7293    crate::switch!("BREP_SWEEP_WALK_SQRT", true)
7294}
7295
7296/// [`segment_clearance`] without `hypot`: a line piece's least squared gap,
7297/// one square root; an arc's lengths by `sqrt` (within a rounding of `hypot`).
7298/// A square outside the range where squaring is exact to a rounding (below
7299/// 1e-290, which takes in an underflow to zero, or above 1e290) reads the
7300/// piece by `segment_clearance` instead.
7301fn segment_clearance_sqrt(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
7302    let in_range = |x: f64| (1e-290..=1e290).contains(&x);
7303    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
7304    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
7305    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
7306    let to_segment_squared = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
7307        let d = sub(e, s);
7308        let len2 = dot(d, d);
7309        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
7310        let gap = sub(x, [s[0] + d[0] * w, s[1] + d[1] * w]);
7311        dot(gap, gap)
7312    };
7313    match *piece {
7314        OutlinePiece::Line { from, to } => {
7315            let (d1, d2) = (sub(b, a), sub(to, from));
7316            let denom = cross(d1, d2);
7317            if denom != 0.0 {
7318                let w = sub(from, a);
7319                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
7320                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
7321                    return 0.0;
7322                }
7323            }
7324            let least = to_segment_squared(a, from, to)
7325                .min(to_segment_squared(b, from, to))
7326                .min(to_segment_squared(from, a, b))
7327                .min(to_segment_squared(to, a, b));
7328            if !in_range(least) {
7329                return segment_clearance(piece, a, b);
7330            }
7331            least.sqrt()
7332        }
7333        OutlinePiece::Arc { centre, radius, .. } => {
7334            let near = to_segment_squared(centre, a, b);
7335            let (x, y) = (sub(a, centre), sub(b, centre));
7336            let far = dot(x, x).max(dot(y, y));
7337            if !(in_range(near) && in_range(far)) {
7338                return segment_clearance(piece, a, b);
7339            }
7340            (near.sqrt() - radius).max(radius - far.sqrt()).max(0.0)
7341        }
7342        OutlinePiece::Ellipse { .. } => 0.0,
7343    }
7344}
7345
7346/// A bound on how fast the tool-frame preimage `screw.invert(t, y)` of the
7347/// world point `y` moves per unit `t`; the tool's distance (1-Lipschitz)
7348/// changes no faster along it.
7349///
7350/// A plain screw about one fixed axis carries the preimage round that axis at
7351/// its distance from it, `ρ`, and along it at the advance's rate, two motions
7352/// square to each other: no faster than `hypot(|ω|·ρ, rate)`. A point near the axis barely moves, so a probe beside
7353/// a tool point on the axis (a coin turned about a line through its rim) walks
7354/// the motion in a few long steps, not millions of floor-sized ones. A riding
7355/// frame or two turns keep the coarser bound through `a`.
7356fn preimage_speed_bound(screw: &Screw, split: &Split, y: Vec3) -> f64 {
7357    let speed = if screw.frame.is_none() && screw.turns.is_none() {
7358        let r = y.sub(screw.a);
7359        let rho = r.sub(screw.e.scale(r.dot(screw.e))).length();
7360        (screw.omega.abs() * rho).hypot(screw.rate_bound())
7361    } else {
7362        let reach = y.sub(screw.a).length() + split.scale + screw.extent;
7363        screw.omega.abs() * reach + screw.rate_bound()
7364    };
7365    speed.max(1e-300)
7366}
7367
7368/// How far a revolved tool reaches about a plain screw's axis: its axial
7369/// coordinate `e·(x − a)` lies within `axial` and its distance from the axis
7370/// within `radial`, for every tool point `x` (bounds, not extremes: a meridian
7371/// line is bounded at its ends, an arc by its whole circle).
7372///
7373/// A plain screw keeps each point's distance from its axis and shifts its
7374/// axial coordinate only by the advance (a slide keeps every coordinate across
7375/// its direction), so a point `y` whose preimage stays outside these bounds
7376/// all through the motion is never inside the tool, and `covered` need not
7377/// walk the motion to say so. Without this a probe beside a face the tool runs
7378/// along all through the motion (the flat top of a coin turned about a line
7379/// through its rim, the floor of an end mill's pass) creeps through it in
7380/// steps of its own tiny distance from the tool.
7381struct ToolReach {
7382    /// The tool's revolution: its origin less the screw's point, its unit axis
7383    /// and its meridian (radius, height along the axis).
7384    base: Vec3,
7385    axis: Vec3,
7386    meridian: Vec<OutlinePiece>,
7387    axial: [f64; 2],
7388    radial: [f64; 2],
7389}
7390
7391/// The largest of |m₀|·p + m₁·q over a meridian (p ≥ 0): a line at its ends,
7392/// an arc by its circle (Cauchy–Schwarz on the offset from its centre).
7393fn meridian_most(meridian: &[OutlinePiece], p: f64, q: f64) -> f64 {
7394    meridian
7395        .iter()
7396        .map(|piece| match *piece {
7397            OutlinePiece::Line { from, to } => (from[0].abs() * p + from[1] * q).max(to[0].abs() * p + to[1] * q),
7398            OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() * p + centre[1] * q + radius * p.hypot(q),
7399            // within the circle of its larger semi-axis
7400            OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() * p + centre[1] * q + semi[0].max(semi[1]) * p.hypot(q),
7401        })
7402        .fold(f64::NEG_INFINITY, f64::max)
7403}
7404
7405impl ToolReach {
7406    fn of(screw: &Screw, split: &Split) -> Option<ToolReach> {
7407        if screw.frame.is_some() || screw.turns.is_some() {
7408            return None;
7409        }
7410        let Shape::Revolved { origin, axis, meridian } = &split.shape else { return None };
7411        let e = screw.e;
7412        // x − a = (origin − a) + m₁·axis + m₀·(unit vector ⊥ axis).
7413        let base = origin.sub(screw.a);
7414        let along = axis.dot(e);
7415        let across = axis.cross(e).length();
7416        let middle = base.dot(e);
7417        let top = middle + meridian_most(meridian, across, along);
7418        let bottom = middle - meridian_most(meridian, across, -along);
7419        // Off the axis: within |(origin − a)⊥| ± (|m₀| + |m₁|·|axis⊥e|).
7420        let off = base.sub(e.scale(middle)).length();
7421        let spread = meridian
7422            .iter()
7423            .map(|piece| match *piece {
7424                OutlinePiece::Line { from, to } => (from[0].abs() + from[1].abs() * across).max(to[0].abs() + to[1].abs() * across),
7425                OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() + centre[1].abs() * across + radius * (1.0 + across * across).sqrt(),
7426                OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() + centre[1].abs() * across + semi[0].max(semi[1]) * (1.0 + across * across).sqrt(),
7427            })
7428            .fold(f64::NEG_INFINITY, f64::max);
7429        let reach = ToolReach { base, axis: *axis, meridian: meridian.clone(), axial: [bottom, top], radial: [off - spread, off + spread] };
7430        (top.is_finite() && bottom.is_finite() && spread.is_finite()).then_some(reach)
7431    }
7432
7433    /// `covered` for a turn (no advance) about an axis along the tool's own,
7434    /// walked in the tool's radius instead of in time; `None` when the motion
7435    /// is not such a turn.
7436    ///
7437    /// The preimage keeps its height along the tool's axis, and its distance
7438    /// from that axis is `ρ_w² = ρ² + s² − 2·ρ·s·cos(θ − θ_W)`, `ρ` its own
7439    /// distance from the turn's axis, `s` the tool axis' and `θ − θ_W` the
7440    /// angle between them, which the turn sweeps through an interval. So the
7441    /// preimage takes every radius between the least and the most `ρ_w` over
7442    /// that interval, and no other: it is ever deeper than the margin inside
7443    /// the tool if and only if some radius in that range is, at that height.
7444    /// The meridian's distance is 1-Lipschitz in the radius, so the range is
7445    /// walked by it. Each radius is met once, where the walk in time crawls
7446    /// past a probe the tool grazes (by the probe's own tiny offset over the
7447    /// turn's speed at each step).
7448    fn turn_about_parallel_axis(&self, screw: &Screw, y: Vec3, margin: f64) -> Option<Result<bool, KernelRefusal>> {
7449        if screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 || self.axis.cross(screw.e).length() != 0.0 {
7450            return None;
7451        }
7452        let e = screw.e;
7453        let r = y.sub(screw.a);
7454        // From the tool's origin to the probe, and its height along the tool's
7455        // axis (the turn keeps it).
7456        let from_tool = r.sub(self.base);
7457        let height = from_tool.dot(self.axis);
7458        // In the plane square to the axis, from the turn's axis: the probe `P`
7459        // and the tool's axis `W`, and the probe from the tool's axis, `P − W`
7460        // (formed as one difference, not as two far points less each other).
7461        let flat = |x: Vec3| x.sub(e.scale(x.dot(e)));
7462        let (probe, tool, apart) = (flat(r), flat(self.base), flat(from_tool));
7463        let (rho, s) = (probe.length(), tool.length());
7464        // Rounding of the coordinates read here, a few ulps of the largest: past
7465        // a quarter of the margin, the walk in time decides instead.
7466        let slack = 64.0 * f64::EPSILON * (r.length() + self.base.length() + height.abs());
7467        if slack > 0.25 * margin {
7468            return None;
7469        }
7470        // The preimage at time t is R(−ω·t)·P: its distance from the tool's axis
7471        // is |R(φ)·(P − W) + (R(φ) − I)·W|, with R(φ) − I = −2 sin²(φ/2) + sin φ·(e ×).
7472        let radius = |phi: f64| -> f64 {
7473            let half = (0.5 * phi).sin();
7474            let turned = apart.rotate_about(e, phi).add(tool.scale(-2.0 * half * half)).add(e.cross(tool).scale(phi.sin()));
7475            turned.length()
7476        };
7477        let (phi0, phi1) = (-screw.omega * screw.t0, -screw.omega * screw.t1);
7478        // The angle from W to P; R(φ)·P lies along W at start + φ ≡ 0 and opposite it at ≡ π.
7479        let start = if rho == 0.0 || s == 0.0 { 0.0 } else { e.dot(tool.cross(probe)).atan2(tool.dot(probe)) };
7480        let (lo, hi) = ((start + phi0).min(start + phi1), (start + phi0).max(start + phi1));
7481        // Does [lo, hi] hold an angle ≡ `at` (mod 2π)?
7482        let holds = |at: f64| (lo - at).div_euclid(TAU) != (hi - at).div_euclid(TAU) || (lo - at).rem_euclid(TAU) == 0.0;
7483        let ends = [radius(phi0), radius(phi1)];
7484        // | |P| − |W| | as |(P − W)·(P + W)| / (|P| + |W|): no cancellation.
7485        let nearest = if rho + s > 0.0 { apart.dot(probe.add(tool)).abs() / (rho + s) } else { 0.0 };
7486        let mut least = if holds(0.0) { nearest } else { ends[0].min(ends[1]) };
7487        let mut most = if holds(PI) { rho + s } else { ends[0].max(ends[1]) };
7488        least = (least - slack).max(0.0);
7489        most += slack;
7490        let mut at = least;
7491        // No floor on the step (it is never less than the margin): a floor
7492        // could step over a wall thinner than itself.
7493        let mut steps = 0usize;
7494        loop {
7495            let d = outline_signed_distance(&self.meridian, [at, height]);
7496            if d < -margin {
7497                return Some(Ok(true));
7498            }
7499            if at >= most {
7500                return Some(Ok(false));
7501            }
7502            if steps > 2_000_000 {
7503                return Some(Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into())));
7504            }
7505            at = (at + d.abs() + margin).min(most);
7506            steps += 1;
7507        }
7508    }
7509
7510    /// A bound on `u·(x − a)` over the tool, `u` a unit direction.
7511    fn support(&self, u: Vec3) -> f64 {
7512        let along = u.dot(self.axis);
7513        let across = u.sub(self.axis.scale(along)).length();
7514        u.dot(self.base) + meridian_most(&self.meridian, across, along)
7515    }
7516
7517    /// Is `y`'s preimage outside the tool's reach, or within half the margin
7518    /// of its edge, at every time of the motion? Then the tool's boundary is
7519    /// within half the margin of every preimage inside (straight out of the
7520    /// bound), and none is deeper than the margin. `normal`: the probe's face
7521    /// normal, across which a slide is also tried.
7522    fn never_inside(&self, screw: &Screw, y: Vec3, normal: Vec3, margin: f64) -> bool {
7523        let r = y.sub(screw.a);
7524        let z = r.dot(screw.e);
7525        let rho = r.sub(screw.e.scale(z)).length();
7526        let mut advances = vec![screw.advance(screw.t0), screw.advance(screw.t1)];
7527        if screw.c2 != 0.0 {
7528            let vertex = -screw.c / (2.0 * screw.c2);
7529            if vertex > screw.t0 && vertex < screw.t1 {
7530                advances.push(screw.advance(vertex));
7531            }
7532        }
7533        let low = advances.iter().copied().fold(f64::INFINITY, f64::min);
7534        let high = advances.iter().copied().fold(f64::NEG_INFINITY, f64::max);
7535        // Half the margin, less what rounding may have cost the coordinates
7536        // and bounds compared (a few ulps of the largest of them).
7537        let size = r.length() + low.abs().max(high.abs()) + self.base.length() + self.radial[1].abs() + self.axial[0].abs().max(self.axial[1].abs());
7538        let half = 0.5 * margin - 1e-13 * size;
7539        if half <= 0.0 {
7540            return false;
7541        }
7542        if z - high >= self.axial[1] - half || z - low <= self.axial[0] + half {
7543            return true;
7544        }
7545        if rho >= self.radial[1] - half || (self.radial[0] > 0.0 && rho <= self.radial[0] + half) {
7546            return true;
7547        }
7548        // A slide carries the preimage along its direction only. `u` is meant
7549        // across it, but whatever of `e` rounding leaves in it moves `u·r`
7550        // with the advance: take the least `u·r` reaches over the motion.
7551        if screw.omega == 0.0 {
7552            if let Ok(u) = normal.sub(screw.e.scale(normal.dot(screw.e))).normalized() {
7553                let drift = u.dot(screw.e);
7554                let least = u.dot(r) - (drift * low).max(drift * high);
7555                if least >= self.support(u) - half {
7556                    return true;
7557                }
7558            }
7559        }
7560        false
7561    }
7562}
7563
7564/// Refuse a sweep that covers points just outside its own faces.
7565///
7566/// `sliding`: faces the tool slides within all through the motion. A probe
7567/// just off one stays that near the tool the whole way, and the walk's step
7568/// is that distance: it stands a thousand times further off them (whatever
7569/// of the tool rides higher than that over such a face is still found).
7570fn check_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7571    let (on, check) = (parallel_turn_one_pass_on(), parallel_turn_one_pass_check_on());
7572    if (on || check) && parallel_turn_one_pass(screw, split) {
7573        if !check {
7574            return Ok(());
7575        }
7576        let walked = walk_single_pass(screw, split, body, sliding);
7577        PARALLEL_TURN_CHECK.with(|cell| {
7578            let (n, bad) = cell.get();
7579            cell.set((n + 1, bad + u64::from(walked.is_err())));
7580        });
7581        return walked;
7582    }
7583    walk_single_pass(screw, split, body, sliding)
7584}
7585
7586/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS` (default on, `=0` walks): the one-pass check
7587/// answered in closed form for a solid of revolution turned (no advance)
7588/// about an axis parallel to its own, `D` from it, whose every section square
7589/// to the axes is one disc of radius `r(z) <= r_max < D`. A point's
7590/// distance from the turn's axis stays fixed; the disc at its height covers,
7591/// of the circle it runs on, one arc of half-angle at most `asin(r_max / D)`
7592/// centred on the tool's axis, and that arc moves round with the turn. The
7593/// point is inside over one interval of the turn unless the arc comes round
7594/// to it again: never while the turn is short of `2π − 2 asin(r_max / D)`.
7595/// The sampled walk is then not needed.
7596pub(crate) fn parallel_turn_one_pass_on() -> bool {
7597    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS", true)
7598}
7599
7600/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK` (default off): where the closed
7601/// form says one pass, the walk runs too and decides; the tally counts the
7602/// walks that refused ([`parallel_turn_one_pass_check_take`]).
7603fn parallel_turn_one_pass_check_on() -> bool {
7604    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK", false)
7605}
7606
7607thread_local! {
7608    static PARALLEL_TURN_CHECK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
7609}
7610
7611/// (closed-form one-pass answers walked, walks that refused) on this thread
7612/// since the last call.
7613pub fn parallel_turn_one_pass_check_take() -> (u64, u64) {
7614    PARALLEL_TURN_CHECK.with(|cell| cell.replace((0, 0)))
7615}
7616
7617/// Whether the closed form above proves the sweep one pass.
7618fn parallel_turn_one_pass(screw: &Screw, split: &Split) -> bool {
7619    if screw.frame.is_some() || screw.turns.is_some() || screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 {
7620        return false;
7621    }
7622    let Shape::Revolved { origin, axis, meridian } = &split.shape else { return false };
7623    if axis.cross(screw.e).length() > 1e-12 {
7624        return false;
7625    }
7626    let apart = origin.sub(screw.a);
7627    let d = apart.sub(screw.e.scale(apart.dot(screw.e))).length();
7628    // Every section one disc: the outline less its pieces on the axis is one
7629    // run whose axial coordinate never turns back (lines; arcs without a
7630    // turning point inside), and its largest radius.
7631    // On the axis exactly: a wall any way off it is a bore, however thin.
7632    let on_axis = |p: [f64; 2]| p[0] == 0.0;
7633    let axial: Vec<bool> = meridian.iter().map(|piece| matches!(*piece, OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to))).collect();
7634    let changes = (0..axial.len()).filter(|&k| axial[k] != axial[(k + 1) % axial.len()]).count();
7635    if changes != 2 {
7636        return false; // the pieces on the axis are not one run of them
7637    }
7638    let mut direction = 0i32;
7639    let mut r_max = 0.0f64;
7640    let mut agree = |sign: i32| -> bool {
7641        if sign == 0 {
7642            return true;
7643        }
7644        if direction == 0 {
7645            direction = sign;
7646        }
7647        direction == sign
7648    };
7649    for piece in meridian {
7650        match *piece {
7651            OutlinePiece::Line { from, to } => {
7652                if on_axis(from) && on_axis(to) {
7653                    continue;
7654                }
7655                if from[0] < -1e-12 || to[0] < -1e-12 {
7656                    return false;
7657                }
7658                r_max = r_max.max(from[0]).max(to[0]);
7659                let rise = to[1] - from[1];
7660                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7661                    return false;
7662                }
7663            }
7664            OutlinePiece::Arc { centre, radius, start, end } => {
7665                let (lo, hi) = (start.min(end), start.max(end));
7666                if !(hi > lo) || !(radius > 0.0) {
7667                    return false;
7668                }
7669                // Turning points of the axial coordinate (cos a = 0) strictly inside.
7670                let first = ((lo - FRAC_PI_2) / PI).floor() as i64 + 1;
7671                if FRAC_PI_2 + first as f64 * PI < hi - 1e-12 {
7672                    return false;
7673                }
7674                // Its radial reach: the ends, and a = 0 (mod 2π) inside.
7675                let reach = |a: f64| centre[0] + radius * a.cos();
7676                r_max = r_max.max(reach(start)).max(reach(end));
7677                if (lo / TAU).ceil() * TAU < hi {
7678                    r_max = r_max.max(centre[0] + radius);
7679                }
7680                if centre[0] - radius < -1e-12 && (lo..hi).contains(&PI) {
7681                    return false;
7682                }
7683                let mid = 0.5 * (start + end);
7684                let rise = radius * mid.cos() * (end - start).signum();
7685                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7686                    return false;
7687                }
7688            }
7689            _ => return false,
7690        }
7691    }
7692    if !(r_max > 0.0 && r_max < d * (1.0 - 1e-9)) {
7693        return false;
7694    }
7695    let turn = (screw.omega * (screw.t1 - screw.t0)).abs();
7696    turn + 2.0 * (r_max / d).asin() < TAU * (1.0 - 1e-9)
7697}
7698
7699fn walk_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7700    let margin = 1e-9 * split.scale;
7701    let reach = ToolReach::of(screw, split);
7702    for face in body.shells.iter().flat_map(|s| &s.faces) {
7703        let step = if sliding.contains(&face.id) { 1e-3 * split.scale } else { 1e-6 * split.scale };
7704        let surface = &face.surface;
7705        // Probe inside the face: towards each corner of its loop from the
7706        // average of its corners (caps are convex in their parameters), and on
7707        // a grid for the four-sided walls.
7708        let mut corners: Vec<[f64; 2]> = Vec::new();
7709        for coedge in &face.loops[0].coedges {
7710            let domain = frag(coedge.pcurve.domain(), "domain")?;
7711            for k in 0..4 {
7712                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 4.0), "pcurve")?;
7713                corners.push([p.x, p.y]);
7714            }
7715        }
7716        let middle = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
7717        let middle = [middle[0] / corners.len() as f64, middle[1] / corners.len() as f64];
7718        let mut probes: Vec<[f64; 2]> = vec![middle];
7719        for c in &corners {
7720            for w in [0.25, 0.5, 0.75, 0.9, 0.99] {
7721                probes.push([middle[0] + (c[0] - middle[0]) * w, middle[1] + (c[1] - middle[1]) * w]);
7722            }
7723        }
7724        if surface.degree_v == 5 {
7725            let [u0, u1] = frag(surface.domain_u(), "domain")?;
7726            for i in 1..8 {
7727                for j in 1..64 {
7728                    probes.push([u0 + (u1 - u0) * i as f64 / 8.0, j as f64 / 64.0]);
7729                }
7730            }
7731        }
7732        let ([u0, u1], [v0, v1]) = (frag(surface.domain_u(), "domain")?, frag(surface.domain_v(), "domain")?);
7733        // Keep the probes inside the face's own loop (a face under a grazing
7734        // curve that dips is not convex in its parameters).
7735        let mut ring: Vec<[f64; 2]> = Vec::new();
7736        for coedge in &face.loops[0].coedges {
7737            let domain = frag(coedge.pcurve.domain(), "domain")?;
7738            for k in 0..32 {
7739                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 32.0), "pcurve")?;
7740                ring.push([p.x, p.y]);
7741            }
7742        }
7743        let (lo, hi) = ring.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), q| ([lo[0].min(q[0]), lo[1].min(q[1])], [hi[0].max(q[0]), hi[1].max(q[1])]));
7744        for i in 1..12 {
7745            for j in 1..12 {
7746                probes.push([lo[0] + (hi[0] - lo[0]) * i as f64 / 12.0, lo[1] + (hi[1] - lo[1]) * j as f64 / 12.0]);
7747            }
7748        }
7749        let inside = |q: [f64; 2]| -> bool {
7750            let mut crossings = 0;
7751            for k in 0..ring.len() {
7752                let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
7753                if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
7754                    crossings += 1;
7755                }
7756            }
7757            crossings % 2 == 1
7758        };
7759        for [u, v] in probes.into_iter().filter(|&q| inside(q)) {
7760            let p = frag(surface.evaluate(u, v), "probe")?;
7761            let (hu, hv) = (1e-6 * (u1 - u0), 1e-6 * (v1 - v0));
7762            // Derivatives, not raw differences: their cross product is
7763            // measured against an absolute zero.
7764            let (ua, ub, va, vb) = ((u - hu).max(u0), (u + hu).min(u1), (v - hv).max(v0), (v + hv).min(v1));
7765            let du = frag(surface.evaluate(ub, v), "probe")?.sub(frag(surface.evaluate(ua, v), "probe")?).scale(1.0 / (ub - ua));
7766            let dv = frag(surface.evaluate(u, vb), "probe")?.sub(frag(surface.evaluate(u, va), "probe")?).scale(1.0 / (vb - va));
7767            let Ok(n) = du.cross(dv).normalized() else { continue };
7768            let n = if face.same_sense { n } else { n.scale(-1.0) };
7769            if covered(screw, split, reach.as_ref(), p.add(n.scale(step)), n, margin)? {
7770                return Err(refuse("folds", format!("the sweep passes over a point twice (just outside its own face at {p:?}); not one pass")));
7771            }
7772        }
7773    }
7774    Ok(())
7775}
7776
7777
7778#[path = "solid_sweep_ring_fold.rs"]
7779mod ring_fold;
7780
7781#[path = "solid_sweep_ball_screw.rs"]
7782mod ball_screw;
7783
7784#[path = "solid_sweep_cone_across.rs"]
7785mod cone_across;
7786
7787
7788