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
77/// The lofted walls' refusal of a ring whose grazing curves turn too fast.
78const GRAZING_TURNS_TOO_FAST: &str = "the ring's grazing curves turn too fast";
79
80fn refuse(what: &'static str, message: String) -> KernelRefusal {
81    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
82}
83
84/// The stable slug of an unsupported-geometry refusal of this module.
85fn refused_as(error: &KernelRefusal) -> Option<&str> {
86    match &error.class {
87        crate::RefusalClass::UnsupportedGeometry { what } => Some(what.as_str()),
88        _ => None,
89    }
90}
91
92fn input(what: &'static str, message: String) -> KernelRefusal {
93    KernelRefusal::input(KernelStage::Collect, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
94}
95
96fn frag<T>(result: Result<T, String>, what: &'static str) -> Result<T, KernelRefusal> {
97    result.or_refuse(KernelStage::Fragment, what)
98}
99
100/// The motion `x ↦ a + R(ω t)(x − a) + (c t + c₂ t²) e`: a screw (c₂ = 0;
101/// a turn has c = 0, a slide ω = 0), or a turn whose rise grows as it turns.
102#[derive(Clone, Copy, Debug)]
103pub struct Screw {
104    pub a: Vec3,
105    pub e: Vec3,
106    pub omega: f64,
107    pub c: f64,
108    pub c2: f64,
109    pub t0: f64,
110    pub t1: f64,
111    /// A frame riding a curve instead (then `a` is the curve's start, `e` the
112    /// frame's fixed up direction, `omega` a bound on its turning rate and `c`
113    /// on its speed).
114    pub frame: Option<Frame>,
115    /// Two turns about fixed axes instead (then `a` is the first axis' point).
116    pub turns: Option<Turns>,
117    /// The time whose velocity field splits the tool (default: the middle).
118    pub frozen: Option<f64>,
119    /// How many spans a ring's grazing loop is sampled over, per half of the
120    /// ring (`LOFT_SAMPLES` unless a loft found its rows too coarse).
121    pub loop_samples: usize,
122    /// How far the frame's origin travels from `a` (for speed bounds).
123    pub extent: f64,
124}
125
126/// Two turns driven by one parameter: first `rates[0]·t` about the first
127/// axis, then `rates[1]·t` about the second; both axes fixed in the world.
128#[derive(Clone, Copy, Debug)]
129pub struct Turns {
130    points: [Vec3; 2],
131    directions: [Vec3; 2],
132    rates: [f64; 2],
133}
134
135impl Turns {
136    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
137        let y = self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t));
138        self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t))
139    }
140    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
141        let x = self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], -self.rates[1] * t));
142        self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], -self.rates[0] * t))
143    }
144    /// Velocity of the tool point x at t, read back in the tool's frame.
145    fn velocity(&self, t: f64, x: Vec3) -> Vec3 {
146        let first = x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t);
147        let y = self.points[0].add(first);
148        let moved = y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t);
149        let inner = self.directions[0].cross(first).scale(self.rates[0]);
150        let world = self.directions[1].cross(moved).scale(self.rates[1]).add(inner.rotate_about(self.directions[1], self.rates[1] * t));
151        world.rotate_about(self.directions[1], -self.rates[1] * t).rotate_about(self.directions[0], -self.rates[0] * t)
152    }
153}
154
155/// A frame riding a planar cubic Bézier curve: origin on the curve, first
156/// axis along its tangent, a fixed up direction square to its plane.
157#[derive(Clone, Copy, Debug)]
158pub struct Frame {
159    pub control: [Vec3; 4],
160    pub up: Vec3,
161    /// The tangent's direction at the start.
162    pub start_tangent: Vec3,
163}
164
165impl Frame {
166    fn point(&self, s: f64) -> Vec3 {
167        let [p0, p1, p2, p3] = self.control;
168        let r = 1.0 - s;
169        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))
170    }
171    fn first(&self, s: f64) -> Vec3 {
172        let [p0, p1, p2, p3] = self.control;
173        let r = 1.0 - s;
174        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))
175    }
176    fn second(&self, s: f64) -> Vec3 {
177        let [p0, p1, p2, p3] = self.control;
178        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))
179    }
180    /// The frame's turn from its start, about `up`.
181    fn angle(&self, s: f64) -> f64 {
182        let t = self.first(s);
183        self.up.dot(self.start_tangent.cross(t)).atan2(self.start_tangent.dot(t))
184    }
185    fn angle_rate(&self, s: f64) -> f64 {
186        let (d1, d2) = (self.first(s), self.second(s));
187        self.up.dot(d1.cross(d2)) / d1.dot(d1)
188    }
189}
190
191/// A turn about an axis whose rise along it grows as it turns: turned by t
192/// (radians, right-handed about `axis_direction`) the tool has risen
193/// `rise[0] t + rise[1] t²`, for t from `from` to `to` (a variable-lead
194/// screw).
195#[derive(Clone, Copy, Debug)]
196pub struct RisingTurn {
197    pub axis_origin: Vec3,
198    pub axis_direction: Vec3,
199    pub rise: [f64; 2],
200    pub from: f64,
201    pub to: f64,
202}
203
204impl Screw {
205    pub fn from_motion(motion: &SolidMotion) -> Result<Self, KernelRefusal> {
206        let [step] = motion.steps.as_slice() else {
207            return Err(refuse("motion_steps", "only a single screw, turn or slide is swept whole here".into()));
208        };
209        let e = step
210            .axis_direction
211            .normalized()
212            .map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
213        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
214            return Err(input("range", "the motion's range must run forward".into()));
215        }
216        if step.turn == 0.0 && step.advance == 0.0 {
217            return Err(input("still", "the motion does not move".into()));
218        }
219        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,
220        loop_samples: LOFT_SAMPLES, extent: 0.0 })
221    }
222
223    fn from_rising(motion: &RisingTurn) -> Result<Self, KernelRefusal> {
224        let e = motion.axis_direction.normalized().map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
225        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
226            return Err(input("range", "the motion's range must run forward".into()));
227        }
228        // The rise's rate must keep one sign, or the tool's front and back swap.
229        let rate = |t: f64| motion.rise[0] + 2.0 * motion.rise[1] * t;
230        if rate(motion.from) * rate(motion.to) <= 0.0 {
231            return Err(refuse("rise_turns", "the rise stops or turns back within the motion".into()));
232        }
233        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,
234        loop_samples: LOFT_SAMPLES, extent: 0.0 })
235    }
236
237    fn advance(&self, t: f64) -> f64 {
238        self.c * t + self.c2 * t * t
239    }
240
241    /// The fastest the motion advances along its axis.
242    fn rate_bound(&self) -> f64 {
243        (self.c + 2.0 * self.c2 * self.t0).abs().max((self.c + 2.0 * self.c2 * self.t1).abs())
244    }
245
246    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
247        if let Some(turns) = &self.turns {
248            return turns.apply(t, x);
249        }
250        if let Some(frame) = &self.frame {
251            return frame.point(t).add(x.sub(self.a).rotate_about(frame.up, frame.angle(t)));
252        }
253        self.a.add(x.sub(self.a).rotate_about(self.e, self.omega * t)).add(self.e.scale(self.advance(t)))
254    }
255
256    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
257        if let Some(turns) = &self.turns {
258            return turns.invert(t, y);
259        }
260        if let Some(frame) = &self.frame {
261            return self.a.add(y.sub(frame.point(t)).rotate_about(frame.up, -frame.angle(t)));
262        }
263        self.a.add(y.sub(self.e.scale(self.advance(t))).sub(self.a).rotate_about(self.e, -self.omega * t))
264    }
265
266    /// Velocity, in the tool's frame, of the tool point x (the same at every t
267    /// for a screw; for a growing rise, at the middle of the motion; the split
268    /// it gives is checked against both ends).
269    pub fn velocity(&self, x: Vec3) -> Vec3 {
270        self.velocity_at(self.frozen.unwrap_or(0.5 * (self.t0 + self.t1)), x)
271    }
272
273    fn velocity_at(&self, t: f64, x: Vec3) -> Vec3 {
274        if let Some(turns) = &self.turns {
275            return turns.velocity(t, x);
276        }
277        if let Some(frame) = &self.frame {
278            // In the riding frame: the speed along the start tangent and the
279            // turn about up through the frame's origin.
280            return frame.start_tangent.scale(frame.first(t).length()).add(frame.up.cross(x.sub(self.a)).scale(frame.angle_rate(t)));
281        }
282        self.e.cross(x.sub(self.a)).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t))
283    }
284
285    /// Value, first and second t-derivative of the path of the tool point x.
286    fn jet(&self, t: f64, x: Vec3) -> (Vec3, Vec3, Vec3) {
287        let r = x.sub(self.a).rotate_about(self.e, self.omega * t);
288        let axial = self.e.scale(r.dot(self.e));
289        let radial = r.sub(axial);
290        let value = self.a.add(r).add(self.e.scale(self.advance(t)));
291        let first = self.e.cross(radial).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t));
292        let second = radial.scale(-self.omega * self.omega).add(self.e.scale(2.0 * self.c2));
293        (value, first, second)
294    }
295
296    fn move_point(&self, t: f64, p: &Vec4) -> Result<Vec4, KernelRefusal> {
297        let x = frag(p.point(), "control_point")?;
298        Ok(Vec4::from_point(self.apply(t, x), p.w))
299    }
300
301    fn move_curve(&self, t: f64, curve: &NurbsCurve) -> Result<NurbsCurve, KernelRefusal> {
302        let points = curve.control_points.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?;
303        frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "moved_curve")
304    }
305
306    fn move_surface(&self, t: f64, surface: &NurbsSurface) -> Result<NurbsSurface, KernelRefusal> {
307        let mut rows = Vec::with_capacity(surface.control_points.len());
308        for row in &surface.control_points {
309            rows.push(row.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?);
310        }
311        frag(
312            NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), rows),
313            "moved_surface",
314        )
315    }
316}
317
318/// The motion's times at the ends of its rows: each row of wall turns at most
319/// a quarter turn (long thin faces cost every later reading, and the cut).
320fn row_times(screw: &Screw) -> Vec<f64> {
321    let turned = (screw.omega * (screw.t1 - screw.t0)).abs();
322    let rows = ((turned / (0.5 * PI)).ceil() as usize).max(1);
323    // Breaks off the round fractions of the range, where a caller's workpiece
324    // faces tend to lie (a precaution: an edge lying in a face makes a
325    // degenerate cut).
326    let at = |k: usize| match k {
327        0 => screw.t0,
328        k if k == rows => screw.t1,
329        k => screw.t0 + (screw.t1 - screw.t0) * (k as f64 - 0.381966011250105) / rows as f64,
330    };
331    (0..=rows).map(at).collect()
332}
333
334/// Spans of the quintic carry over [ta, tb]: 48 per turn (error ≈ r·h⁶/46080
335/// ≈ 1e-10·r), at least 4.
336fn carry_segments(screw: &Screw, ta: f64, tb: f64) -> usize {
337    let turned = (screw.omega * (tb - ta)).abs();
338    ((turned / TAU * 48.0).ceil() as usize).max(4)
339}
340
341/// Knots of the C² quintic carry on [0, 1].
342fn carry_knots(segments: usize) -> Vec<f64> {
343    let mut knots = vec![0.0; 6];
344    for k in 1..segments {
345        knots.extend([k as f64 / segments as f64; 3]);
346    }
347    knots.extend([1.0; 6]);
348    knots
349}
350
351/// Control points of the C² quintic spline through the exact path of the tool
352/// point x, its first and second derivatives at `segments + 1` times. Affine
353/// in x, so carrying a rational curve's control points carries the curve.
354fn carry_points(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Vec<Vec3> {
355    let h = (tb - ta) / segments as f64;
356    let at = |k: usize| screw.jet(ta + h * k as f64, x);
357    let piece = |k: usize| {
358        let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
359        [
360            f0,
361            f0.add(d0.scale(h / 5.0)),
362            f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
363            f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
364            f1.sub(d1.scale(h / 5.0)),
365            f1,
366        ]
367    };
368    let mut points = Vec::with_capacity(3 * segments + 3);
369    let first = piece(0);
370    points.extend_from_slice(&first[..3]);
371    for k in 0..segments - 1 {
372        let (here, next) = (piece(k), piece(k + 1));
373        points.push(here[3]);
374        points.push(here[4].scale(2.0).sub(here[3]));
375        points.push(next[2]);
376    }
377    let last = piece(segments - 1);
378    points.extend_from_slice(&last[3..]);
379    points
380}
381
382fn carry_curve(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Result<NurbsCurve, KernelRefusal> {
383    frag(
384        NurbsCurve::new(5, carry_knots(segments), carry_points(screw, x, ta, tb, segments).into_iter().map(|p| Vec4::from_point(p, 1.0)).collect()),
385        "carry_curve",
386    )
387}
388
389/// A boundary curve of the tool (in its own frame), from point `start` to
390/// point `end` along its parameter.
391struct ToolCurve {
392    curve: NurbsCurve,
393    start: usize,
394    end: usize,
395    degenerate: bool,
396    /// Exact points at `LOFT_SAMPLES + 1` even steps of a natural parameter
397    /// from start to end (meridian place, angle), where a grazing curve
398    /// moves on the tool and its wall is lofted through time.
399    samples: Option<Vec<Vec3>>,
400}
401
402/// Steps of a grazing curve's exact samples for a lofted wall.
403pub const LOFT_SAMPLES: usize = 128;
404
405/// How near a lofted wall keeps to its exact grazing loop, as a fraction of
406/// the sweep's size: every exact sample of the loop, in the middle of every
407/// time span, is within this of the wall.
408///
409/// It was 5e-10. A wall that tight is heavy (a quintic's miss falls as the
410/// sixth power of its span, so each tenfold costs half again as many spans
411/// each way), and whoever reads the solid pays for every span. The measures
412/// do not need it: an interpolant's miss changes sign from span to span and
413/// all but cancels in a volume or an area. Over this hundredfold the lofted
414/// cases' volumes and areas moved by 2e-10 or less.
415const LOFT_TARGET: f64 = 5e-8;
416
417/// A face of the tool after the split along K: its exact surface (normal
418/// outward), its side, and its loop (curve, traversed forward?, pcurve in the
419/// direction of traversal).
420struct Cap {
421    surface: NurbsSurface,
422    front: bool,
423    coedges: Vec<(usize, bool, NurbsCurve)>,
424    /// The surface's exact parameters of a point (in the tool's frame), where
425    /// known: a lofted edge's pcurve is then its exact image.
426    chart: Option<Chart>,
427}
428
429/// How a cap's surface is parameterized, to invert it exactly.
430#[derive(Clone, Copy, Debug)]
431enum Chart {
432    /// `plane_patch(origin, u, v, …)`: (x − origin)·u, (x − origin)·v.
433    Plane { origin: Vec3, u: Vec3, v: Vec3 },
434    /// `make_revolution(origin, w, generatrix, theta)` with the generatrix in the
435    /// meridian half-plane at angle `alpha` (from u1 towards u2).
436    Revolution { origin: Vec3, w: Vec3, u1: Vec3, u2: Vec3, alpha: f64, theta: f64, spans_u: usize, meridian: MeridianChart },
437}
438
439#[derive(Clone, Copy, Debug)]
440enum MeridianChart {
441    /// A segment from m0 to m1 in (ρ, z), parameter 0 -> 1.
442    Line { m0: [f64; 2], m1: [f64; 2] },
443    /// An arc about `centre` in (ρ, z) from angle `start` through `sweep`, as
444    /// `make_revolution` of a point makes it (`spans` arcs).
445    Arc { centre: [f64; 2], start: f64, sweep: f64, spans: usize },
446}
447
448impl Chart {
449    /// Is `x` on the chart's own axis, where its first parameter (the angle
450    /// about the axis) is not defined? A ball's pole.
451    fn at_pole(&self, x: Vec3) -> bool {
452        match *self {
453            Chart::Plane { .. } => false,
454            Chart::Revolution { origin, w, .. } => {
455                let r = x.sub(origin);
456                r.sub(w.scale(r.dot(w))).length() <= 1e-6 * r.length()
457            }
458        }
459    }
460
461    /// The chart's span joints in each parameter (`make_revolution`'s arcs
462    /// in equal spans of [0, 1]), where its parameter's second derivative
463    /// jumps along the surface.
464    fn joints(&self) -> (Vec<f64>, Vec<f64>) {
465        let inner = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
466        match *self {
467            Chart::Plane { .. } => (Vec::new(), Vec::new()),
468            Chart::Revolution { spans_u, meridian, .. } => (
469                inner(spans_u),
470                match meridian {
471                    MeridianChart::Arc { spans, .. } => inner(spans),
472                    MeridianChart::Line { .. } => Vec::new(),
473                },
474            ),
475        }
476    }
477
478    fn invert(&self, x: Vec3) -> [f64; 2] {
479        match *self {
480            Chart::Plane { origin, u, v } => {
481                let d = x.sub(origin);
482                [d.dot(u), d.dot(v)]
483            }
484            Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u, meridian } => {
485                let r = x.sub(origin);
486                let z = r.dot(w);
487                let rho = r.sub(w.scale(z)).length();
488                let mid = alpha + 0.5 * theta;
489                let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
490                let u = crate::circle_angle_to_parameter(spans_u, theta, psi - alpha);
491                let v = match meridian {
492                    MeridianChart::Line { m0, m1 } => {
493                        let (a, b) = (m1[0] - m0[0], m1[1] - m0[1]);
494                        ((rho - m0[0]) * a + (z - m0[1]) * b) / (a * a + b * b)
495                    }
496                    MeridianChart::Arc { centre, start, sweep, spans } => {
497                        let mid = start + 0.5 * sweep;
498                        let angle = mid + ((z - centre[1]).atan2(rho - centre[0]) - mid + PI).rem_euclid(TAU) - PI;
499                        crate::circle_angle_to_parameter(spans, sweep, angle - start)
500                    }
501                };
502                [u, v]
503            }
504        }
505    }
506}
507
508/// The spans `make_revolution` gives a sweep of `theta`.
509fn spans_of(surface_knots_u: &[f64]) -> usize {
510    (surface_knots_u.len() - 6) / 2 + 1
511}
512
513/// The tool's boundary split along K, in the tool's own frame.
514struct Split {
515    points: Vec<Vec3>,
516    curves: Vec<ToolCurve>,
517    caps: Vec<Cap>,
518    /// Flat ends that slide within their own plane all through the motion.
519    slides: Vec<SlideDisc>,
520    /// Cylinders that slide along their own generators all through it.
521    slide_sides: Vec<SlideSide>,
522    scale: f64,
523    shape: Shape,
524}
525
526/// A flat end about the tool's axis whose every point moves within the
527/// end's own plane (a turn about a parallel axis, a slide across the tool's
528/// axis): neither front nor back. What it sweeps is one face of the sweep in
529/// that plane, bounded by the rim's arcs beside back faces where the motion
530/// starts, its arcs beside front faces where it stops, and the paths of the
531/// points between them. `rim`: the rim's arcs counter-clockwise about the
532/// outward normal `u × v`, each with its direction of traversal.
533struct SlideDisc {
534    centre: Vec3,
535    u: Vec3,
536    v: Vec3,
537    rim: Vec<(usize, bool)>,
538}
539
540/// A cylinder about the tool's axis slid along that axis: every point moves
541/// along its own generator. What it sweeps is the cylinder from one rim where
542/// that rim's neighbour sits (back at the start, front at the end) to the
543/// other rim where its neighbour sits. `patches`: per stretch between two
544/// seam angles, (the angle it starts at, its sweep, the start rim's arc, the
545/// end rim's arc, the rim points at the start angle: start rim, end rim).
546struct SlideSide {
547    origin: Vec3,
548    w: Vec3,
549    patches: Vec<(f64, f64, usize, usize, [usize; 2])>,
550}
551
552/// What the membership oracle measures.
553enum Shape {
554    Planes(Vec<(Vec3, f64)>),
555    Revolved { origin: Vec3, axis: Vec3, meridian: Vec<OutlinePiece> },
556}
557
558impl Split {
559    /// Signed distance to the tool in its own frame (negative inside).
560    fn distance(&self, x: Vec3) -> f64 {
561        match &self.shape {
562            Shape::Planes(planes) => planes.iter().map(|(n, d)| n.dot(x) - d).fold(f64::NEG_INFINITY, f64::max),
563            Shape::Revolved { origin, axis, meridian } => {
564                let r = x.sub(*origin);
565                let z = r.dot(*axis);
566                let rho = r.sub(axis.scale(z)).length();
567                outline_signed_distance(meridian, [rho, z])
568            }
569        }
570    }
571
572    /// K: each curve with a front cap on one side and a back cap on the
573    /// other, with the direction in which the back cap runs along it (the back
574    /// on its left seen from outside).
575    fn grazing(&self) -> Result<Vec<(usize, bool)>, KernelRefusal> {
576        let mut uses: HashMap<usize, Vec<(bool, bool)>> = HashMap::new();
577        for cap in &self.caps {
578            for &(curve, forward, _) in &cap.coedges {
579                uses.entry(curve).or_default().push((forward, cap.front));
580            }
581        }
582        let mut grazing = Vec::new();
583        for (curve, list) in uses {
584            if self.curves[curve].degenerate {
585                continue;
586            }
587            // A sliding end's rim carries no wall: it moves within the end's plane.
588            if list.len() == 1
589                && (self.slides.iter().any(|slide| slide.rim.iter().any(|&(c, _)| c == curve))
590                    || self.slide_sides.iter().any(|side| side.patches.iter().any(|patch| patch.2 == curve || patch.3 == curve)))
591            {
592                continue;
593            }
594            match list.as_slice() {
595                [(fa, front_a), (fb, front_b)] => {
596                    if fa == fb {
597                        return Err(refuse("split_topology", "two caps run one boundary curve the same way".into()));
598                    }
599                    if front_a != front_b {
600                        grazing.push((curve, if *front_a { *fb } else { *fa }));
601                    }
602                }
603                _ => return Err(refuse("split_topology", format!("a boundary curve is used {} times", list.len()))),
604            }
605        }
606        grazing.sort_unstable();
607        Ok(grazing)
608    }
609}
610
611fn uv_line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
612    frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "pcurve")
613}
614
615/// The plane through `origin` with in-plane axes u, v (u × v outward), as a
616/// patch covering `points`; and the map to its parameters.
617fn plane_patch(origin: Vec3, u: Vec3, v: Vec3, points: &[Vec3]) -> Result<NurbsSurface, KernelRefusal> {
618    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
619    for p in points {
620        let q = [p.sub(origin).dot(u), p.sub(origin).dot(v)];
621        for k in 0..2 {
622            lo[k] = lo[k].min(q[k]);
623            hi[k] = hi[k].max(q[k]);
624        }
625    }
626    let at = |s: f64, t: f64| Vec4::from_point(origin.add(u.scale(s)).add(v.scale(t)), 1.0);
627    frag(
628        NurbsSurface::new(
629            1,
630            1,
631            vec![lo[0], lo[0], hi[0], hi[0]],
632            vec![lo[1], lo[1], hi[1], hi[1]],
633            vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]],
634        ),
635        "plane_surface",
636    )
637}
638
639/// A curve lying in the plane (origin, u, v), as a pcurve of that plane:
640/// its control points projected, weights kept (exact, the map is affine).
641fn plane_pcurve(origin: Vec3, u: Vec3, v: Vec3, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
642    let mut points = Vec::with_capacity(curve.control_points.len());
643    for p in &curve.control_points {
644        let x = frag(p.point(), "control_point")?.sub(origin);
645        points.push(Vec4::from_point(Vec3::new(x.dot(u), x.dot(v), 0.0), p.w));
646    }
647    let pcurve = frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "plane_pcurve")?;
648    if forward { Ok(pcurve) } else { frag(pcurve.reversed(), "plane_pcurve") }
649}
650
651fn split_polyhedron(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<Split, KernelRefusal> {
652    if vertices.len() < 4 || faces.len() < 4 {
653        return Err(input("polyhedron", "a polyhedron needs at least four corners and four faces".into()));
654    }
655    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);
656    let scale = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max).max(1e-300);
657    let tolerance = 1e-12 * scale.max(screw.a.sub(centroid).length());
658    let mut loops: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
659    let mut planes = Vec::with_capacity(faces.len());
660    for face in faces {
661        if face.len() < 3 || face.iter().any(|&i| i >= vertices.len()) {
662            return Err(input("face", "a face needs three or more existing corners".into()));
663        }
664        let mut normal = Vec3::new(0.0, 0.0, 0.0);
665        for k in 0..face.len() {
666            let (p, q) = (vertices[face[k]], vertices[face[(k + 1) % face.len()]]);
667            normal = normal.add(p.sub(centroid).cross(q.sub(centroid)));
668        }
669        let mut normal = normal.normalized().map_err(|_| input("face", "a face has no area".into()))?;
670        let mut face = face.clone();
671        if normal.dot(vertices[face[0]].sub(centroid)) < 0.0 {
672            normal = normal.scale(-1.0);
673            face.reverse();
674        }
675        let offset = normal.dot(vertices[face[0]]);
676        for p in vertices {
677            if normal.dot(*p) - offset > 1e-9 * scale {
678                return Err(refuse("not_convex", "the polyhedron is not convex".into()));
679            }
680        }
681        for &i in &face {
682            if (normal.dot(vertices[i]) - offset).abs() > 1e-9 * scale {
683                return Err(input("face", "a face's corners are not in one plane".into()));
684            }
685        }
686        loops.push(face);
687        planes.push((normal, offset));
688    }
689    // Each face's grazing value (affine along the face).
690    let g = |face: usize, x: Vec3| -> f64 {
691        let value = screw.velocity(x).dot(planes[face].0);
692        if value.abs() <= tolerance * screw.velocity(x).length().max(1.0) { 0.0 } else { value }
693    };
694    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
695    for (index, face) in loops.iter().enumerate() {
696        for k in 0..face.len() {
697            owner.insert((face[k], face[(k + 1) % face.len()]), index);
698        }
699    }
700    for &(i, j) in owner.keys() {
701        if !owner.contains_key(&(j, i)) {
702            return Err(input("closed", "the polyhedron's faces do not close".into()));
703        }
704    }
705    // Split points on edges: where either neighbour's grazing value crosses zero.
706    let mut points: Vec<Vec3> = vertices.to_vec();
707    let mut edge_splits: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
708    let mut keys: Vec<(usize, usize)> = owner.keys().copied().filter(|&(i, j)| i < j).collect();
709    keys.sort_unstable();
710    for (i, j) in keys {
711        let mut params: Vec<f64> = Vec::new();
712        for f in [owner[&(i, j)], owner[&(j, i)]] {
713            let (gi, gj) = (g(f, vertices[i]), g(f, vertices[j]));
714            if gi * gj < 0.0 {
715                params.push(gi / (gi - gj));
716            }
717        }
718        params.sort_by(|a, b| a.total_cmp(b));
719        params.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
720        let mut list = Vec::new();
721        for s in params {
722            points.push(vertices[i].add(vertices[j].sub(vertices[i]).scale(s)));
723            list.push(points.len() - 1);
724        }
725        edge_splits.insert((i, j), list);
726    }
727    let splits_along = |i: usize, j: usize| -> Vec<usize> {
728        if i < j {
729            edge_splits[&(i, j)].clone()
730        } else {
731            edge_splits[&(j, i)].iter().rev().copied().collect()
732        }
733    };
734    // Sub-faces as point rings, counter-clockwise from outside.
735    let mut rings: Vec<(Vec<usize>, usize, bool)> = Vec::new();
736    for (index, face) in loops.iter().enumerate() {
737        let mut ring: Vec<usize> = Vec::new();
738        for k in 0..face.len() {
739            ring.push(face[k]);
740            ring.extend(splits_along(face[k], face[(k + 1) % face.len()]));
741        }
742        let values: Vec<f64> = ring.iter().map(|&p| g(index, points[p])).collect();
743        let positive = values.iter().any(|&v| v > 0.0);
744        let negative = values.iter().any(|&v| v < 0.0);
745        if !positive && !negative {
746            return Err(refuse("face_in_own_plane", format!("face {index} moves in its own plane (its sweep is flat)")));
747        }
748        if !(positive && negative) {
749            rings.push((ring, index, positive));
750            continue;
751        }
752        let zeros: Vec<usize> = (0..ring.len()).filter(|&k| values[k] == 0.0).collect();
753        if zeros.len() != 2 {
754            return Err(refuse("grazing_split", format!("face {index} meets its grazing line {} times", zeros.len())));
755        }
756        let (za, zb) = (zeros[0], zeros[1]);
757        if za + 1 == zb || (zb + 1) % ring.len() == za {
758            return Err(refuse("grazing_split", format!("face {index} is split along one of its own edges")));
759        }
760        let first: Vec<usize> = (za..=zb).map(|k| ring[k]).collect();
761        let second: Vec<usize> = (zb..ring.len()).chain(0..=za).map(|k| ring[k]).collect();
762        let first_front = values[za + 1] > 0.0;
763        rings.push((first, index, first_front));
764        rings.push((second, index, !first_front));
765    }
766    // A growing rise moves the grazing lines: every sub-face must keep its side
767    // at both ends of the motion.
768    if screw.c2 != 0.0 {
769        for (ring, face, front) in &rings {
770            for &p in ring {
771                for t in [screw.t0, screw.t1] {
772                    let value = screw.velocity_at(t, points[p]).dot(planes[*face].0);
773                    let slack = tolerance * screw.velocity_at(t, points[p]).length().max(1.0);
774                    if (*front && value < -slack) || (!*front && value > slack) {
775                        return Err(refuse("rising_sides", format!("face {face} changes side as the rise grows")));
776                    }
777                }
778            }
779        }
780    }
781    // Curves: one straight segment per point pair.
782    let mut curves: Vec<ToolCurve> = Vec::new();
783    let mut by_pair: HashMap<(usize, usize), usize> = HashMap::new();
784    let mut caps = Vec::with_capacity(rings.len());
785    for (ring, face, front) in rings {
786        let normal = planes[face].0;
787        let origin = points[ring[0]];
788        let u = frag(points[ring[1]].sub(origin).normalized(), "plane_axis")?;
789        let v = normal.cross(u);
790        let corners: Vec<Vec3> = ring.iter().map(|&p| points[p]).collect();
791        let surface = plane_patch(origin, u, v, &corners)?;
792        let mut coedges = Vec::with_capacity(ring.len());
793        for k in 0..ring.len() {
794            let (p, q) = (ring[k], ring[(k + 1) % ring.len()]);
795            let key = (p.min(q), p.max(q));
796            let index = match by_pair.get(&key) {
797                Some(&index) => index,
798                None => {
799                    curves.push(ToolCurve {
800                        curve: frag(make_line(points[key.0], points[key.1]), "line")?,
801                        start: key.0,
802                        end: key.1,
803                        degenerate: false,
804                        samples: None,
805                    });
806                    by_pair.insert(key, curves.len() - 1);
807                    curves.len() - 1
808                }
809            };
810            let forward = p == key.0;
811            coedges.push((index, forward, plane_pcurve(origin, u, v, &curves[index].curve, forward)?));
812        }
813        caps.push(Cap { surface, front, coedges, chart: Some(Chart::Plane { origin, u, v }) });
814    }
815    Ok(Split { points, curves, caps, slides: Vec::new(), slide_sides: Vec::new(), scale, shape: Shape::Planes(planes) })
816}
817
818/// The grazing value `A cos ψ + B sin ψ + C` of a face of revolution at one
819/// meridian point, from three samples.
820pub fn harmonic(g: impl Fn(f64) -> f64) -> (f64, f64, f64) {
821    let (g0, g90, g180) = (g(0.0), g(0.5 * PI), g(PI));
822    let c = 0.5 * (g0 + g180);
823    (0.5 * (g0 - g180), g90 - c, c)
824}
825
826pub fn piece_point(piece: &OutlinePiece, s: f64) -> [f64; 2] {
827    match *piece {
828        OutlinePiece::Line { from, to } => [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s],
829        OutlinePiece::Arc { centre, radius, start, end } => {
830            let angle = start + (end - start) * s;
831            [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
832        }
833        OutlinePiece::Ellipse { centre, semi, rotation, start, end } => crate::solid_sweep::ellipse_point(centre, semi, rotation, start + (end - start) * s),
834    }
835}
836
837/// The whole sweep takes meridians of lines and circular arcs; an elliptic
838/// piece is swept only by [`crate::sweep_solid_within`]'s region engine.
839fn refuse_elliptic(meridian: &[OutlinePiece]) -> Result<(), KernelRefusal> {
840    if meridian.iter().any(|piece| matches!(piece, OutlinePiece::Ellipse { .. })) {
841        return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into()));
842    }
843    Ok(())
844}
845
846fn split_revolved(
847    screw: &Screw,
848    origin: Vec3,
849    axis: Vec3,
850    radial: Vec3,
851    meridian: &[OutlinePiece],
852) -> Result<Split, KernelRefusal> {
853    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
854    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
855    let u2 = w.cross(u1);
856    refuse_elliptic(meridian)?;
857    if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian {
858        if ((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius {
859            return split_torus(screw, origin, w, u1, u2, *centre, *radius, meridian);
860        }
861    }
862    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()));
863    let scale = meridian
864        .iter()
865        .flat_map(|p| [piece_point(p, 0.0), piece_point(p, 1.0)])
866        .map(|q| q[0].abs().max(q[1].abs()))
867        .fold(0.0f64, f64::max)
868        .max(1e-300);
869    let on_axis = |q: [f64; 2]| q[0].abs() <= 1e-12 * scale;
870    // Orientation of the meridian outline (+1 counter-clockwise in (ρ, z)).
871    let mut area = 0.0;
872    for piece in meridian {
873        for k in 0..16 {
874            let (p, q) = (piece_point(piece, k as f64 / 16.0), piece_point(piece, (k + 1) as f64 / 16.0));
875            area += p[0] * q[1] - q[0] * p[1];
876        }
877    }
878    // Work counter-clockwise in (ρ, z): a revolved patch's u × v is then outward.
879    let reversed_meridian: Vec<OutlinePiece>;
880    let meridian: &[OutlinePiece] = if area > 0.0 {
881        meridian
882    } else {
883        reversed_meridian = meridian
884            .iter()
885            .rev()
886            .map(|piece| match *piece {
887                OutlinePiece::Line { from, to } => OutlinePiece::Line { from: to, to: from },
888                OutlinePiece::Arc { centre, radius, start, end } => OutlinePiece::Arc { centre, radius, start: end, end: start },
889                OutlinePiece::Ellipse { centre, semi, rotation, start, end } => OutlinePiece::Ellipse { centre, semi, rotation, start: end, end: start },
890            })
891            .collect();
892        &reversed_meridian
893    };
894    let ccw = true;
895    // Outward normal in (ρ, z) of a piece at s.
896    let normal = |piece: &OutlinePiece, s: f64| -> [f64; 2] {
897        let (p, q) = (piece_point(piece, (s - 1e-6).max(0.0)), piece_point(piece, (s + 1e-6).min(1.0)));
898        let (dx, dz) = (q[0] - p[0], q[1] - p[1]);
899        let length = dx.hypot(dz);
900        if ccw { [dz / length, -dx / length] } else { [-dz / length, dx / length] }
901    };
902    let g = |piece: &OutlinePiece, s: f64, psi: f64| -> f64 {
903        let m = piece_point(piece, s);
904        let n = normal(piece, s);
905        let x = at(m[0], m[1], psi);
906        let normal = w.scale(n[1]).add(u1.scale(n[0] * psi.cos())).add(u2.scale(n[0] * psi.sin()));
907        screw.velocity(x).dot(normal)
908    };
909    // The faces: pieces off the axis.
910    let faces: Vec<usize> = (0..meridian.len())
911        .filter(|&i| !(matches!(meridian[i], OutlinePiece::Line { .. }) && on_axis(piece_point(&meridian[i], 0.0)) && on_axis(piece_point(&meridian[i], 1.0))))
912        .collect();
913    // Each face's split angles (where K meets it, constant along it), or its
914    // great circle.
915    enum Kind {
916        /// A cylinder or cone (or a flat end) split along generators at these
917        /// angles (empty: one side).
918        Ruled(Vec<f64>),
919        /// A cylinder or cone whose two grazing curves move round it along
920        /// the meridian (`branches`), from rim to rim.
921        Moving,
922        /// A hemisphere from a pole to an equator rim, split by the great
923        /// circle square to its centre's velocity.
924        Sphere { centre: Vec3, pole_at_start: bool },
925        /// A whole ball (a half circle from pole to pole), split by that
926        /// great circle into two hemispheres.
927        Ball { centre: Vec3, radius: f64 },
928        /// A rounded corner (a zone of a torus: an arc whose centre is off the
929        /// axis), crossed by K as a graph v(ψ) of the tube angle for ψ from
930        /// `psi_a` to `psi_b`, entering and leaving at the same rim (the end
931        /// rim when `at_end`).
932        TorusZone { psi_a: f64, psi_b: f64, at_end: bool },
933        /// A flat end that slides within its own plane (`SlideDisc`).
934        Slide,
935        /// A cylinder slid along its own axis (`SlideSide`).
936        SlideSide,
937        /// A rounded corner split along meridian arcs at these angles (the
938        /// grazing curve keeps its angle about the axis: a turn about a
939        /// parallel axis, a slide across the tool's axis).
940        RuledArc(Vec<f64>),
941    }
942    // The two grazing angles of a cylinder or cone at s, the lower and the
943    // upper, unwrapped against s = 0: the front lies between them.
944    let branches = |piece: &OutlinePiece, s: f64| -> Option<(f64, f64)> {
945        let reference = {
946            let (a, b, _) = harmonic(|psi| g(piece, 0.0, psi));
947            b.atan2(a)
948        };
949        let (a, b, c) = harmonic(|psi| g(piece, s, psi));
950        let r = a.hypot(b);
951        if !(c.abs() < r * (1.0 - 1e-9)) {
952            return None;
953        }
954        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
955        let spread = (-c / r).acos();
956        Some((base - spread, base + spread))
957    };
958    let mut kinds: Vec<Kind> = Vec::with_capacity(faces.len());
959    for &i in &faces {
960        let piece = &meridian[i];
961        match *piece {
962            OutlinePiece::Ellipse { .. } => return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into())),
963            OutlinePiece::Line { .. } => {
964                let roots = |s: f64| -> Vec<f64> {
965                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
966                    let r = a.hypot(b);
967                    if c.abs() >= r * (1.0 - 1e-12) {
968                        return Vec::new();
969                    }
970                    let base = b.atan2(a);
971                    let spread = (-c / r).acos();
972                    let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
973                    list.sort_by(|x, y| x.total_cmp(y));
974                    list
975                };
976                // Where the grazing value vanishes all round (a rim through
977                // the motion's axis turning in its own plane) it names no
978                // angle; read the roots where it does not.
979                let alive = |s: f64| {
980                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
981                    a.hypot(b).max(c.abs()) > 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound())
982                };
983                let readings: Vec<Vec<f64>> = [0.0, 0.5, 1.0].into_iter().filter(|&t| alive(t)).map(roots).collect();
984                if readings.is_empty() {
985                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
986                    let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
987                    if flat && (on_axis(m0) || on_axis(m1)) {
988                        kinds.push(Kind::Slide);
989                        continue;
990                    }
991                    let upright = (m0[0] - m1[0]).abs() <= 1e-12 * scale;
992                    if upright && screw.omega == 0.0 && screw.turns.is_none() && screw.frame.is_none() {
993                        kinds.push(Kind::SlideSide);
994                        continue;
995                    }
996                    return Err(refuse("revolved_grazing", format!("meridian piece {i} grazes all over")));
997                }
998                let r0 = readings[0].clone();
999                let still = readings.iter().all(|r| r.len() == r0.len() && r.iter().zip(&r0).all(|(x, y)| (x - y).abs() < 1e-10));
1000                if still {
1001                    // A face wholly on one side that is not a disc about the
1002                    // axis (a cone to its point, an annulus, a whole side):
1003                    // two halves of the same side, seamed at 0 and π.
1004                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1005                    let disc = (m0[1] - m1[1]).abs() <= 1e-12 * scale && (on_axis(m0) || on_axis(m1));
1006                    kinds.push(Kind::Ruled(if r0.is_empty() && !disc { vec![0.0, PI] } else { r0 }));
1007                    continue;
1008                }
1009                let mut previous: Option<(f64, f64)> = None;
1010                for k in 0..=64 {
1011                    let Some(pair) = branches(piece, k as f64 / 64.0) else {
1012                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} do not run rim to rim")));
1013                    };
1014                    if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
1015                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} turn too fast")));
1016                    }
1017                    previous = Some(pair);
1018                }
1019                kinds.push(Kind::Moving);
1020            }
1021            OutlinePiece::Arc { centre, radius, start, end } => {
1022                let (p0, p1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1023                let span = (end - start).abs();
1024                let centre_on_axis = on_axis(centre);
1025                let pole_at_start = on_axis(p0);
1026                let equator = |p: [f64; 2]| (p[1] - centre[1]).abs() <= 1e-12 * scale && (p[0] - radius).abs() <= 1e-12 * scale;
1027                if centre_on_axis && (span - PI).abs() < 1e-12 && pole_at_start && on_axis(p1) {
1028                    kinds.push(Kind::Ball { centre: origin.add(w.scale(centre[1])), radius });
1029                    continue;
1030                }
1031                if centre[0] > radius * (1.0 + 1e-9) && end > start && span <= PI + 1e-12 {
1032                    let at_rim = |v: f64| [centre[0] + radius * v.cos(), centre[1] + radius * v.sin()];
1033                    let g_tube = |psi: f64, v: f64| -> f64 {
1034                        let m = at_rim(v);
1035                        let x = at(m[0], m[1], psi);
1036                        let normal = w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1037                        screw.velocity(x).dot(normal)
1038                    };
1039                    // K at the same angles about the axis all along the arc?
1040                    {
1041                        let roots_at = |v: f64| -> Option<Vec<f64>> {
1042                            let (a, b, c) = harmonic(|psi| g_tube(psi, v));
1043                            let r = a.hypot(b);
1044                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1045                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1046                                return None;
1047                            }
1048                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1049                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1050                            list.sort_by(|x, y| x.total_cmp(y));
1051                            Some(list)
1052                        };
1053                        let readings: Vec<Option<Vec<f64>>> = [0.25, 0.5, 0.75].into_iter().map(|t| roots_at(start + (end - start) * t)).collect();
1054                        if let [Some(r0), Some(r1), Some(r2)] = readings.as_slice() {
1055                            if r0.iter().zip(r1).chain(r0.iter().zip(r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1056                                kinds.push(Kind::RuledArc(r0.clone()));
1057                                continue;
1058                            }
1059                        }
1060                    }
1061                    if span >= PI {
1062                        return Err(refuse("revolved_arc", format!("meridian piece {i}: a half-round rim is swept only where its grazing curves keep their angle")));
1063                    }
1064                    let in_zone = |psi: f64| -> Result<Option<f64>, KernelRefusal> {
1065                        let (a, b, c) = harmonic(|v| g_tube(psi, v));
1066                        let r = a.hypot(b);
1067                        if !(c.abs() < r) {
1068                            return Ok(None);
1069                        }
1070                        let base = b.atan2(a);
1071                        let spread = (-c / r).acos();
1072                        let inside: Vec<f64> = [base - spread, base + spread]
1073                            .into_iter()
1074                            .map(|v| start + (v - start).rem_euclid(TAU))
1075                            .filter(|&v| v <= end)
1076                            .collect();
1077                        match inside.as_slice() {
1078                            [] => Ok(None),
1079                            [v] => Ok(Some(*v)),
1080                            _ => Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner twice at one angle"))),
1081                        }
1082                    };
1083                    let count = 720;
1084                    let has: Vec<bool> = (0..count).map(|k| in_zone(TAU * k as f64 / count as f64).map(|r| r.is_some())).collect::<Result<_, _>>()?;
1085                    let rises: Vec<usize> = (0..count).filter(|&k| has[k] && !has[(k + count - 1) % count]).collect();
1086                    let falls: Vec<usize> = (0..count).filter(|&k| !has[k] && has[(k + count - 1) % count]).collect();
1087                    let ([rise], [fall]) = (rises.as_slice(), falls.as_slice()) else {
1088                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve does not cross the rounded corner once")));
1089                    };
1090                    // The crossing's ends: roots of the grazing value along the rim it meets.
1091                    let estimate = |k: usize| TAU * (k as f64 - 0.5) / count as f64;
1092                    let (ea, eb) = (estimate(*rise), estimate(*fall));
1093                    let sample = |k: usize| TAU * (k % count) as f64 / count as f64;
1094                    let probe_v = in_zone(sample(*rise))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1095                    let at_end = (probe_v - end).abs() < (probe_v - start).abs();
1096                    let rim_v = if at_end { end } else { start };
1097                    let (a, b, c) = harmonic(|psi| g_tube(psi, rim_v));
1098                    let r = a.hypot(b);
1099                    let base = b.atan2(a);
1100                    let spread = (-c / r).acos();
1101                    let roots = [base - spread, base + spread];
1102                    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");
1103                    let (psi_a, psi_b) = (nearest(ea).rem_euclid(TAU), nearest(eb).rem_euclid(TAU));
1104                    let psi_b = if psi_b <= psi_a { psi_b + TAU } else { psi_b };
1105                    let leave_v = in_zone(sample(*fall + count - 1))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1106                    if ((leave_v - end).abs() < (leave_v - start).abs()) != at_end {
1107                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner from rim to rim")));
1108                    }
1109                    kinds.push(Kind::TorusZone { psi_a, psi_b, at_end });
1110                    continue;
1111                }
1112                if !(centre_on_axis && (span - 0.5 * PI).abs() < 1e-12 && (pole_at_start && equator(p1) || on_axis(p1) && equator(p0))) {
1113                    // A cap of a sphere about the axis, from its pole to a rim
1114                    // short of (or past) the equator: swept where its grazing
1115                    // curves keep their angle about the axis (meridian arcs
1116                    // through the pole).
1117                    if centre_on_axis && end > start && span < PI && (pole_at_start != on_axis(p1)) {
1118                        let roots_at = |s: f64| -> Option<Vec<f64>> {
1119                            let (a, b, c) = harmonic(|psi| g(piece, s, psi));
1120                            let r = a.hypot(b);
1121                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1122                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1123                                return None;
1124                            }
1125                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1126                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1127                            list.sort_by(|x, y| x.total_cmp(y));
1128                            Some(list)
1129                        };
1130                        if let [Some(r0), Some(r1), Some(r2)] = [0.25, 0.5, 0.75].map(roots_at) {
1131                            if r0.iter().zip(&r1).chain(r0.iter().zip(&r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1132                                kinds.push(Kind::RuledArc(r0));
1133                                continue;
1134                            }
1135                        }
1136                    }
1137                    return Err(refuse("revolved_arc", format!("meridian piece {i}: only a quarter circle from a pole to an equator is swept here")));
1138                }
1139                kinds.push(Kind::Sphere { centre: origin.add(w.scale(centre[1])), pole_at_start });
1140            }
1141        }
1142    }
1143    // Rims: junctions off the axis, with the angles they are split at.
1144    let count = meridian.len();
1145    let junction = |k: usize| piece_point(&meridian[k], 1.0); // between piece k and k + 1
1146    let face_of = |piece: usize| faces.iter().position(|&f| f == piece);
1147    let mut rim_angles: HashMap<usize, Vec<f64>> = HashMap::new();
1148    for k in 0..count {
1149        if on_axis(junction(k)) {
1150            continue;
1151        }
1152        let mut angles: Vec<f64> = Vec::new();
1153        for (piece, s_end) in [(k, 1.0), ((k + 1) % count, 0.0)] {
1154            let Some(f) = face_of(piece) else { continue };
1155            match &kinds[f] {
1156                Kind::Ruled(roots) | Kind::RuledArc(roots) => angles.extend(roots.iter().copied()),
1157                Kind::Ball { .. } | Kind::Slide => {}
1158                Kind::SlideSide => angles.extend([0.0, PI]),
1159                Kind::TorusZone { psi_a, psi_b, .. } => angles.extend([psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)]),
1160                Kind::Moving => {
1161                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1162                    angles.extend([lower.rem_euclid(TAU), upper.rem_euclid(TAU)]);
1163                }
1164                Kind::Sphere { centre, .. } => {
1165                    let d = screw.velocity(*centre).cross(w);
1166                    let base = d.dot(u2).atan2(d.dot(u1)).rem_euclid(TAU);
1167                    angles.extend([base, (base + PI).rem_euclid(TAU)]);
1168                }
1169            }
1170        }
1171        angles.sort_by(|a, b| a.total_cmp(b));
1172        let mut merged: Vec<f64> = Vec::new();
1173        for a in angles {
1174            if merged.last().is_some_and(|&b| (a - b).abs() < 1e-9) || merged.first().is_some_and(|&b| (b + TAU - a).abs() < 1e-9) {
1175                continue;
1176            }
1177            merged.push(a);
1178        }
1179        rim_angles.insert(k, merged);
1180    }
1181    // Every face's own split angles must be its rims' (one arc per patch side).
1182    for (f, &piece) in faces.iter().enumerate() {
1183        for (k, s_end) in [((piece + count - 1) % count, 0.0), (piece, 1.0)] {
1184            let own: Vec<f64> = match &kinds[f] {
1185                Kind::Ruled(roots) | Kind::RuledArc(roots) => roots.clone(),
1186                Kind::Moving => {
1187                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1188                    let mut list = vec![lower.rem_euclid(TAU), upper.rem_euclid(TAU)];
1189                    list.sort_by(|a, b| a.total_cmp(b));
1190                    list
1191                }
1192                Kind::TorusZone { psi_a, psi_b, .. } => {
1193                    let mut list = vec![psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)];
1194                    list.sort_by(|a, b| a.total_cmp(b));
1195                    list
1196                }
1197                Kind::Sphere { .. } | Kind::Ball { .. } | Kind::Slide => continue,
1198                Kind::SlideSide => vec![0.0, PI],
1199            };
1200            if let Some(angles) = rim_angles.get(&k) {
1201                if own.is_empty() {
1202                    continue;
1203                }
1204                if angles.len() != own.len() || angles.iter().zip(&own).any(|(a, b)| (a - b).abs() > 1e-9) {
1205                    return Err(refuse("revolved_rims", format!("meridian piece {piece} splits at other angles than its rim")));
1206                }
1207            }
1208        }
1209    }
1210    let mut points: Vec<Vec3> = Vec::new();
1211    let mut curves: Vec<ToolCurve> = Vec::new();
1212    let mut caps: Vec<Cap> = Vec::new();
1213    let mut slides: Vec<SlideDisc> = Vec::new();
1214    let mut slide_sides: Vec<SlideSide> = Vec::new();
1215    // Rim points and arcs: arc j of rim k runs from angle j to angle j + 1.
1216    let mut rim_points: HashMap<(usize, usize), usize> = HashMap::new();
1217    let mut rim_arcs: HashMap<(usize, usize), usize> = HashMap::new();
1218    let mut rim_keys: Vec<usize> = rim_angles.keys().copied().collect();
1219    rim_keys.sort_unstable();
1220    for &k in &rim_keys {
1221        let q = junction(k);
1222        let angles = rim_angles[&k].clone();
1223        let angles = if angles.is_empty() { vec![0.0] } else { angles };
1224        for (j, &a) in angles.iter().enumerate() {
1225            points.push(at(q[0], q[1], a));
1226            rim_points.insert((k, j), points.len() - 1);
1227        }
1228        for j in 0..angles.len() {
1229            let a = angles[j];
1230            let b = if j + 1 < angles.len() { angles[j + 1] } else { angles[0] + TAU };
1231            let base = at(q[0], q[1], a);
1232            let surface = frag(make_revolution(origin, w, &frag(make_line(base, base.add(w)), "line")?, b - a), "rim")?;
1233            curves.push(ToolCurve {
1234                curve: frag(surface.iso_curve_v(0.0), "rim_arc")?,
1235                start: rim_points[&(k, j)],
1236                end: rim_points[&(k, (j + 1) % angles.len())],
1237                degenerate: false,
1238                samples: Some((0..=LOFT_SAMPLES).map(|i| at(q[0], q[1], a + (b - a) * i as f64 / LOFT_SAMPLES as f64)).collect()),
1239            });
1240            rim_arcs.insert((k, j), curves.len() - 1);
1241        }
1242        rim_angles.insert(k, angles);
1243    }
1244    let arc_index = |k: usize, angle: f64| -> Result<usize, KernelRefusal> {
1245        rim_angles[&k]
1246            .iter()
1247            .position(|&a| ((a - angle).rem_euclid(TAU)).min((angle - a).rem_euclid(TAU)) < 1e-9)
1248            .ok_or_else(|| refuse("revolved_rims", "a patch corner is not on its rim's split".into()))
1249    };
1250    let sign_at = |piece: &OutlinePiece, psi: f64| g(piece, 0.5, psi) > 0.0;
1251    for (f, &piece_index) in faces.iter().enumerate() {
1252        let piece = &meridian[piece_index];
1253        let below = (piece_index + count - 1) % count; // rim at the piece's start
1254        let above = piece_index; // rim at its end
1255        let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1256        match &kinds[f] {
1257            Kind::SlideSide => {
1258                if on_axis(m0) || on_axis(m1) {
1259                    return Err(refuse("revolved_grazing", format!("meridian piece {piece_index} grazes all over")));
1260                }
1261                let seams = [0.0, PI];
1262                let mut patches = Vec::with_capacity(2);
1263                for j in 0..2 {
1264                    let (alpha, theta) = (seams[j], PI);
1265                    let (ib, ia) = (arc_index(below, alpha)?, arc_index(above, alpha)?);
1266                    patches.push((alpha, theta, rim_arcs[&(below, ib)], rim_arcs[&(above, ia)], [rim_points[&(below, ib)], rim_points[&(above, ia)]]));
1267                }
1268                slide_sides.push(SlideSide { origin, w, patches });
1269            }
1270            Kind::RuledArc(roots) => {
1271                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1272                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1273                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1274                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1275                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1276                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1277                    let from = tube_point(psi, start);
1278                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1279                    frag(surface.iso_curve_v(0.0), "tube")
1280                };
1281                // A cap to its pole: the meridian arcs start (or end) there,
1282                // and each patch has a pole in place of a rim arc.
1283                let apex = if on_axis(m0) || on_axis(m1) {
1284                    let m = if on_axis(m0) { m0 } else { m1 };
1285                    points.push(at(0.0, m[1], 0.0));
1286                    Some(points.len() - 1)
1287                } else {
1288                    None
1289                };
1290                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1291                    match (on, apex) {
1292                        (true, Some(p)) => Ok(p),
1293                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1294                    }
1295                };
1296                let mut generators = Vec::with_capacity(roots.len());
1297                for &root in roots {
1298                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1299                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| tube_point(root, start + (end - start) * i as f64 / LOFT_SAMPLES as f64)).collect();
1300                    exact[0] = points[a];
1301                    exact[LOFT_SAMPLES] = points[b];
1302                    curves.push(ToolCurve { curve: generatrix(root)?, start: a, end: b, degenerate: false, samples: Some(exact) });
1303                    generators.push(curves.len() - 1);
1304                }
1305                for j in 0..roots.len() {
1306                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1307                    let surface = frag(make_revolution(origin, w, &generatrix(alpha)?, beta - alpha), "patch")?;
1308                    let (mid_psi, mid_v) = (0.5 * (alpha + beta), 0.5 * (start + end));
1309                    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()));
1310                    let front = screw.velocity(tube_point(mid_psi, mid_v)).dot(mid_normal) > 0.0;
1311                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1312                        let p = apex.expect("apex");
1313                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1314                        curves.len() - 1
1315                    };
1316                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1317                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1318                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1319                    let coedges = vec![
1320                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1321                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1322                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1323                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1324                    ];
1325                    let chart = Chart::Revolution {
1326                        origin,
1327                        w,
1328                        u1,
1329                        u2,
1330                        alpha,
1331                        theta: beta - alpha,
1332                        spans_u: spans_of(&surface.knots_u),
1333                        meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_of(&surface.knots_v) },
1334                    };
1335                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1336                }
1337            }
1338            Kind::Slide => {
1339                let rim = if on_axis(m0) { above } else { below };
1340                let n = normal(piece, 0.5);
1341                let outward = w.scale(n[1].signum());
1342                let arcs = rim_angles[&rim].len();
1343                // Counter-clockwise about the outward normal: increasing ψ about +w.
1344                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1345                slides.push(SlideDisc {
1346                    centre: origin.add(w.scale(m0[1])),
1347                    u: u1,
1348                    v: outward.cross(u1),
1349                    rim: order.into_iter().map(|j| (rim_arcs[&(rim, j)], n[1] > 0.0)).collect(),
1350                });
1351            }
1352            Kind::Ruled(roots) if roots.is_empty() => {
1353                // A flat end wholly on one side: a disc about the axis.
1354                let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
1355                if !flat || !(on_axis(m0) || on_axis(m1)) {
1356                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a whole side or ring is not swept here")));
1357                }
1358                let rim = if on_axis(m0) { above } else { below };
1359                let front = sign_at(piece, 0.0);
1360                if (0..64).any(|k| sign_at(piece, TAU * k as f64 / 64.0) != front) {
1361                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a flat end meets its grazing line")));
1362                }
1363                let n = normal(piece, 0.5);
1364                let outward = w.scale(n[1].signum());
1365                let centre = origin.add(w.scale(m0[1]));
1366                let (u, v) = (u1, outward.cross(u1));
1367                let arcs = rim_angles[&rim].len();
1368                let mut coedges = Vec::with_capacity(arcs);
1369                let mut corners = Vec::new();
1370                // Counter-clockwise about the outward normal: increasing ψ about +w.
1371                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1372                for j in order {
1373                    let c = rim_arcs[&(rim, j)];
1374                    let forward = n[1] > 0.0;
1375                    coedges.push((c, forward, plane_pcurve(centre, u, v, &curves[c].curve, forward)?));
1376                    corners.push(points[curves[c].start]);
1377                }
1378                let r = junction(rim)[0];
1379                corners.extend([centre.add(u.scale(r)).add(v.scale(r)), centre.sub(u.scale(r)).sub(v.scale(r))]);
1380                caps.push(Cap { surface: plane_patch(centre, u, v, &corners)?, front, coedges, chart: Some(Chart::Plane { origin: centre, u, v }) });
1381            }
1382            Kind::Ruled(roots) => {
1383                // A cone to a point: its generators start (or end) at the
1384                // apex, and each patch has a pole there in place of a rim arc.
1385                let apex = if on_axis(m0) || on_axis(m1) {
1386                    let m = if on_axis(m0) { m0 } else { m1 };
1387                    points.push(at(0.0, m[1], 0.0));
1388                    Some(points.len() - 1)
1389                } else {
1390                    None
1391                };
1392                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1393                    match (on, apex) {
1394                        (true, Some(p)) => Ok(p),
1395                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1396                    }
1397                };
1398                // Generators at each root, from the start rim to the end rim.
1399                let mut generators = Vec::with_capacity(roots.len());
1400                for &root in roots {
1401                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1402                    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();
1403                    curves.push(ToolCurve { curve: frag(make_line(points[a], points[b]), "generator")?, start: a, end: b, degenerate: false, samples: Some(line_samples) });
1404                    generators.push(curves.len() - 1);
1405                }
1406                for j in 0..roots.len() {
1407                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1408                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1409                    let surface = frag(make_revolution(origin, w, &generatrix, beta - alpha), "patch")?;
1410                    let front = sign_at(piece, 0.5 * (alpha + beta));
1411                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1412                        let p = apex.expect("apex");
1413                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1414                        curves.len() - 1
1415                    };
1416                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1417                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1418                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1419                    let coedges = vec![
1420                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1421                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1422                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1423                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1424                    ];
1425                    let chart = Chart::Revolution { origin, w, u1, u2, alpha, theta: beta - alpha, spans_u: spans_of(&surface.knots_u), meridian: MeridianChart::Line { m0, m1 } };
1426                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1427                }
1428            }
1429            Kind::Moving => {
1430                if on_axis(m0) || on_axis(m1) {
1431                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a split cone to a point is not swept here")));
1432                }
1433                let n = 128;
1434                let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1435                let pairs: Vec<(f64, f64)> = params.iter().map(|&t| branches(piece, t).expect("checked")).collect();
1436                let pick = |pair: (f64, f64), which: usize| if which == 0 { pair.0 } else { pair.1 };
1437                // K: the lower and upper branch, each from the start rim to the end rim.
1438                let mut branch_curves = [0usize; 2];
1439                for which in 0..2 {
1440                    let (psi0, psi1) = (pick(pairs[0], which), pick(pairs[n], which));
1441                    let start = rim_points[&(below, arc_index(below, psi0)?)];
1442                    let end = rim_points[&(above, arc_index(above, psi1)?)];
1443                    let mut samples: Vec<Vec3> = params
1444                        .iter()
1445                        .zip(&pairs)
1446                        .map(|(&t, &pair)| {
1447                            let m = piece_point(piece, t);
1448                            at(m[0], m[1], pick(pair, which))
1449                        })
1450                        .collect();
1451                    samples[0] = points[start];
1452                    samples[n] = points[end];
1453                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES)
1454                        .map(|i| {
1455                            let t = i as f64 / LOFT_SAMPLES as f64;
1456                            let m = piece_point(piece, t);
1457                            at(m[0], m[1], pick(branches(piece, t).expect("checked"), which))
1458                        })
1459                        .collect();
1460                    exact[0] = points[start];
1461                    exact[LOFT_SAMPLES] = points[end];
1462                    curves.push(ToolCurve { curve: frag(fit_tool_curve(&samples, &params), "branch")?, start, end, degenerate: false, samples: Some(exact) });
1463                    branch_curves[which] = curves.len() - 1;
1464                }
1465                // Front between lower and upper; back from upper to lower + 2π.
1466                for (lo_which, hi_which, hi_turn) in [(0usize, 1usize, 0.0), (1, 0, TAU)] {
1467                    let lo = |i: usize| pick(pairs[i], lo_which);
1468                    let hi = |i: usize| pick(pairs[i], hi_which) + hi_turn;
1469                    let alpha = (0..=n).map(lo).fold(f64::INFINITY, f64::min) - 1e-3;
1470                    let theta = (0..=n).map(hi).fold(f64::NEG_INFINITY, f64::max) + 1e-3 - alpha;
1471                    if theta >= TAU {
1472                        return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a side patch wraps all the way round")));
1473                    }
1474                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1475                    let surface = frag(make_revolution(origin, w, &generatrix, theta), "patch")?;
1476                    let spans = (surface.knots_u.len() - 6) / 2 + 1;
1477                    let u_of = |psi: f64| crate::circle_angle_to_parameter(spans, theta, psi - alpha);
1478                    let angle_near = |x: Vec3, guess: f64| -> f64 {
1479                        let r = x.sub(origin);
1480                        let a = r.dot(u2).atan2(r.dot(u1));
1481                        guess + (a - guess + PI).rem_euclid(TAU) - PI
1482                    };
1483                    let front = sign_at(piece, 0.5 * (lo(n / 2) + hi(n / 2)));
1484                    // A rim arc's pcurve on this patch, through its own parameter.
1485                    let rim_pcurve = |arc: usize, v: f64| -> Result<NurbsCurve, KernelRefusal> {
1486                        let curve = &curves[arc].curve;
1487                        let [d0, d1] = frag(curve.domain(), "domain")?;
1488                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1489                        let mut uv = Vec::with_capacity(ts.len());
1490                        for &t in &ts {
1491                            let x = frag(curve.evaluate(t), "rim")?;
1492                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), v, 0.0));
1493                        }
1494                        if pcurve_joints_on() {
1495                            let (ju, jv) = surface_joints(&surface);
1496                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok([u_of(angle_near(frag(curve.evaluate(t), "rim")?, alpha + 0.5 * theta)), v]) };
1497                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1498                                return Ok(fitted);
1499                            }
1500                        }
1501                        frag(fit_pcurve(&uv, &ts), "rim_pcurve")
1502                    };
1503                    // A grazing branch's pcurve: the image of the built edge,
1504                    // through its own parameter (angle about the axis; place
1505                    // along the meridian line).
1506                    let branch_pcurve = |which: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> {
1507                        let curve = &curves[branch_curves[which]].curve;
1508                        let [d0, d1] = frag(curve.domain(), "domain")?;
1509                        let (span_rho, span_z) = (m1[0] - m0[0], m1[1] - m0[1]);
1510                        let length2 = span_rho * span_rho + span_z * span_z;
1511                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1512                        let mut uv = Vec::with_capacity(ts.len());
1513                        let read = |x: Vec3| -> [f64; 2] {
1514                            let r = x.sub(origin);
1515                            let z = r.dot(w);
1516                            let rho = r.sub(w.scale(z)).length();
1517                            let along = ((rho - m0[0]) * span_rho + (z - m0[1]) * span_z) / length2;
1518                            [u_of(angle_near(x, alpha + 0.5 * theta)), along]
1519                        };
1520                        for &t in &ts {
1521                            let [u, along] = read(frag(curve.evaluate(t), "branch")?);
1522                            uv.push(Vec3::new(u, along, 0.0));
1523                        }
1524                        if pcurve_joints_on() {
1525                            let (ju, jv) = surface_joints(&surface);
1526                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "branch")?)) };
1527                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1528                                return Ok(fitted);
1529                            }
1530                        }
1531                        frag(fit_pcurve(&uv, &ts), "branch_pcurve")
1532                    };
1533                    let bottom = rim_arcs[&(below, arc_index(below, lo(0))?)];
1534                    let top = rim_arcs[&(above, arc_index(above, lo(n))?)];
1535                    let coedges = vec![
1536                        (bottom, true, rim_pcurve(bottom, 0.0)?),
1537                        (branch_curves[hi_which], true, branch_pcurve(hi_which, hi_turn)?),
1538                        (top, false, frag(rim_pcurve(top, 1.0)?.reversed(), "reversed")?),
1539                        (branch_curves[lo_which], false, frag(branch_pcurve(lo_which, 0.0)?.reversed(), "reversed")?),
1540                    ];
1541                    let chart_spans = spans_of(&surface.knots_u);
1542                    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 } }) });
1543                }
1544            }
1545            Kind::TorusZone { psi_a, psi_b, at_end } => {
1546                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1547                let (psi_a, psi_b, at_end) = (*psi_a, *psi_b, *at_end);
1548                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1549                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1550                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1551                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()));
1552                let root = |psi: f64| -> Option<f64> {
1553                    let (a, b, c) = harmonic(|v| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)));
1554                    let r = a.hypot(b);
1555                    if !(c.abs() < r) {
1556                        return None;
1557                    }
1558                    let base = b.atan2(a);
1559                    let spread = (-c / r).acos();
1560                    [base - spread, base + spread].into_iter().map(|v| start + (v - start).rem_euclid(TAU)).find(|&v| v <= end + 1e-12)
1561                };
1562                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1563                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1564                    let from = tube_point(psi, start);
1565                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1566                    frag(surface.iso_curve_v(0.0), "tube")
1567                };
1568                let (rim_k, other_k) = if at_end { (above, below) } else { (below, above) };
1569                let ka = rim_points[&(rim_k, arc_index(rim_k, psi_a)?)];
1570                let kb = rim_points[&(rim_k, arc_index(rim_k, psi_b)?)];
1571                // K: the graph over ψ ∈ [ψa, ψb].
1572                let n = 256;
1573                let params: Vec<f64> = (0..=n).map(|j| j as f64 / n as f64).collect();
1574                // Spaced as 1 − cos: where K meets its rim it runs along the
1575                // meridian, so its tube angle goes as √(ψ − ψa); in this
1576                // parameter it is regular.
1577                let psi_of = |t: f64| psi_a + (psi_b - psi_a) * 0.5 * (1.0 - (PI * t).cos());
1578                let mut xyz = Vec::with_capacity(n + 1);
1579                for j in 0..=n {
1580                    let psi = psi_of(params[j]);
1581                    let v = if j == 0 || j == n { if at_end { end } else { start } } else {
1582                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1583                    };
1584                    xyz.push(tube_point(psi, v));
1585                }
1586                xyz[0] = points[ka];
1587                xyz[n] = points[kb];
1588                let mut exact = Vec::with_capacity(LOFT_SAMPLES + 1);
1589                for i in 0..=LOFT_SAMPLES {
1590                    let psi = psi_of(i as f64 / LOFT_SAMPLES as f64);
1591                    let v = if i == 0 || i == LOFT_SAMPLES { if at_end { end } else { start } } else {
1592                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1593                    };
1594                    exact.push(tube_point(psi, v));
1595                }
1596                exact[0] = points[ka];
1597                exact[LOFT_SAMPLES] = points[kb];
1598                curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "torus_k")?, start: ka, end: kb, degenerate: false, samples: Some(exact) });
1599                let k_curve = curves.len() - 1;
1600                // Cut meridians at ψa and ψb, from the start rim to the end rim.
1601                let mut cut = [0usize; 2];
1602                for (slot, psi) in [(0, psi_a), (1, psi_b)] {
1603                    let (lo, hi) = (rim_points[&(below, arc_index(below, psi)?)], rim_points[&(above, arc_index(above, psi)?)]);
1604                    curves.push(ToolCurve { curve: generatrix(psi)?, start: lo, end: hi, degenerate: false, samples: None });
1605                    cut[slot] = curves.len() - 1;
1606                }
1607                let label = |psi: f64, v: f64| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)) > 0.0;
1608                // The patch over [α, β] and its exact inverse.
1609                let patch = |alpha: f64, beta: f64| -> Result<(NurbsSurface, usize, usize), KernelRefusal> {
1610                    let g = generatrix(alpha)?;
1611                    let surface = frag(make_revolution(origin, w, &g, beta - alpha), "torus_patch")?;
1612                    let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1613                    let spans_v = (g.knots.len() - 6) / 2 + 1;
1614                    Ok((surface, spans_u, spans_v))
1615                };
1616                let inverse_pcurve = |curve: &NurbsCurve, alpha: f64, beta: f64, spans_u: usize, spans_v: usize, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
1617                    let [d0, d1] = frag(curve.domain(), "domain")?;
1618                    let ts: Vec<f64> = pcurve_stations(d0, d1);
1619                    let mut uv = Vec::with_capacity(ts.len());
1620                    let read = |x: Vec3| -> [f64; 2] {
1621                        let r = x.sub(origin);
1622                        let mid = 0.5 * (alpha + beta);
1623                        let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
1624                        let q = x.sub(tube_centre(psi));
1625                        let radial = u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1626                        let vmid = 0.5 * (start + end);
1627                        let v = vmid + (q.dot(w).atan2(q.dot(radial)) - vmid + PI).rem_euclid(TAU) - PI;
1628                        [crate::circle_angle_to_parameter(spans_u, beta - alpha, psi - alpha), crate::circle_angle_to_parameter(spans_v, end - start, v - start)]
1629                    };
1630                    for &t in &ts {
1631                        let [u, v] = read(frag(curve.evaluate(t), "point")?);
1632                        uv.push(Vec3::new(u, v, 0.0));
1633                    }
1634                    if pcurve_joints_on() {
1635                        let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1636                        let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "point")?)) };
1637                        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1638                            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
1639                        }
1640                    }
1641                    let fitted = frag(fit_pcurve(&uv, &ts), "torus_pcurve")?;
1642                    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
1643                };
1644                // The band away from K: a natural patch over [ψb, ψa + 2π].
1645                {
1646                    let (surface, _, band_spans_v) = patch(psi_b, psi_a + TAU)?;
1647                    let (bottom, top) = (rim_arcs[&(below, arc_index(below, psi_b)?)], rim_arcs[&(above, arc_index(above, psi_b)?)]);
1648                    let coedges = vec![
1649                        (bottom, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1650                        (cut[0], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1651                        (top, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1652                        (cut[1], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1653                    ];
1654                    let mid = psi_b + 0.5 * (psi_a + TAU - psi_b);
1655                    let chart_spans = spans_of(&surface.knots_u);
1656                    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 } }) });
1657                }
1658                // Over [ψa, ψb]: the lens between K and its rim, and the rest.
1659                let (surface, spans_u, spans_v) = patch(psi_a, psi_b)?;
1660                let rim_arc = rim_arcs[&(rim_k, arc_index(rim_k, psi_a)?)];
1661                let other_arc = rim_arcs[&(other_k, arc_index(other_k, psi_a)?)];
1662                let mid = 0.5 * (psi_a + psi_b);
1663                let v_k = root(mid).ok_or_else(|| refuse("torus_zone", "no grazing point mid-way".into()))?;
1664                let k_pc = |forward: bool| inverse_pcurve(&curves[k_curve].curve, psi_a, psi_b, spans_u, spans_v, forward);
1665                let lens_v = if at_end { 0.5 * (v_k + end) } else { 0.5 * (v_k + start) };
1666                let rest_v = if at_end { 0.5 * (v_k + start) } else { 0.5 * (v_k + end) };
1667                if at_end {
1668                    // Lens: K (ψa -> ψb) under the end rim, then the end rim back.
1669                    let lens = vec![(k_curve, true, k_pc(true)?), (rim_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?)];
1670                    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 } }) });
1671                    let rest = vec![
1672                        (other_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1673                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1674                        (k_curve, false, k_pc(false)?),
1675                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1676                    ];
1677                    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 } }) });
1678                } else {
1679                    let lens = vec![(rim_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?), (k_curve, false, k_pc(false)?)];
1680                    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 } }) });
1681                    let rest = vec![
1682                        (k_curve, true, k_pc(true)?),
1683                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1684                        (other_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1685                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1686                    ];
1687                    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 } }) });
1688                }
1689            }
1690            Kind::Ball { centre, radius } => {
1691                let m = frag(screw.velocity(*centre).normalized(), "ball_still")?;
1692                let d = frag(w.cross(m).normalized().or_else(|_| u1.cross(m).normalized()), "ball_axis")?;
1693                let (e1, e2) = (centre.add(d.scale(*radius)), centre.sub(d.scale(*radius)));
1694                points.push(e1);
1695                points.push(e2);
1696                let (i1, i2) = (points.len() - 2, points.len() - 1);
1697                let half = frag(make_revolution(*centre, m, &frag(make_line(e1, e1.add(m)), "line")?, PI), "great")?;
1698                let k_a = frag(half.iso_curve_v(0.0), "great")?;
1699                // Exact samples at even angles from e1 round to e2 (for a
1700                // lofted wall), turned the way the curve runs.
1701                let k_a_samples: Vec<Vec3> = {
1702                    let [a0, a1] = frag(k_a.domain(), "domain")?;
1703                    let middle = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?;
1704                    let arm = e1.sub(*centre);
1705                    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 };
1706                    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();
1707                    list[0] = e1;
1708                    list[LOFT_SAMPLES] = e2;
1709                    list
1710                };
1711                curves.push(ToolCurve { curve: k_a.clone(), start: i1, end: i2, degenerate: false, samples: Some(k_a_samples.clone()) });
1712                let k_a_index = curves.len() - 1;
1713                let [a0, a1] = frag(k_a.domain(), "domain")?;
1714                let h = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?.sub(*centre);
1715                let mut k_b_index: Option<usize> = None;
1716                for front in [true, false] {
1717                    let toward = if front { m } else { m.scale(-1.0) };
1718                    let da = if d.cross(h).dot(toward) > 0.0 { d } else { d.scale(-1.0) };
1719                    let mut generatrix = k_a.clone();
1720                    let mut surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1721                    let outward = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1722                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1723                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1724                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1725                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1726                    };
1727                    let mut forward = true;
1728                    if !outward(&surface)? {
1729                        generatrix = frag(generatrix.reversed(), "reversed")?;
1730                        surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1731                        forward = false;
1732                    }
1733                    let (start, end) = if forward { (i1, i2) } else { (i2, i1) };
1734                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1735                    let k_b = match k_b_index {
1736                        Some(index) => index,
1737                        None => {
1738                            // The other half of the great circle: the first half turned half way about `da`.
1739                            let mut samples: Vec<Vec3> = k_a_samples.iter().map(|&x| centre.add(x.sub(*centre).rotate_about(da, PI))).collect();
1740                            if !forward {
1741                                samples.reverse();
1742                            }
1743                            samples[0] = points[start];
1744                            samples[LOFT_SAMPLES] = points[end];
1745                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: Some(samples) });
1746                            k_b_index = Some(curves.len() - 1);
1747                            curves.len() - 1
1748                        }
1749                    };
1750                    let k_b_forward = curves[k_b].start == start;
1751                    let k_b_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1752                    let poles = [start, end].map(|p| {
1753                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1754                        curves.len() - 1
1755                    });
1756                    let coedges = vec![
1757                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1758                        (k_b, k_b_forward, k_b_pcurve),
1759                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1760                        (k_a_index, !forward, uv_line([0.0, g1], [0.0, g0])?),
1761                    ];
1762                    caps.push(Cap { surface, front, coedges, chart: None });
1763                }
1764            }
1765            Kind::Sphere { centre, pole_at_start } => {
1766                let rim = if *pole_at_start { above } else { below };
1767                let angles = rim_angles[&rim].clone();
1768                if angles.len() != 2 {
1769                    return Err(refuse("revolved_rims", "a hemisphere's rim is not split in two".into()));
1770                }
1771                let pole_side = w.scale(if *pole_at_start { m0[1] - m1[1] } else { m1[1] - m0[1] }.signum());
1772                let m = screw.velocity(*centre);
1773                let e1 = points[rim_points[&(rim, 0)]];
1774                let d = frag(e1.sub(*centre).normalized(), "lune_axis")?;
1775                let mut great: Option<usize> = None;
1776                for j in 0..2 {
1777                    let arc = rim_arcs[&(rim, j)];
1778                    let [a0, a1] = frag(curves[arc].curve.domain(), "domain")?;
1779                    let middle = frag(curves[arc].curve.evaluate(0.5 * (a0 + a1)), "middle")?;
1780                    let hv = middle.sub(*centre);
1781                    let da = if d.cross(hv).dot(pole_side) > 0.0 { d } else { d.scale(-1.0) };
1782                    // Turn the rim arc about da until its middle reaches K's plane.
1783                    let theta = (-m.dot(hv)).atan2(m.dot(da.cross(hv))).rem_euclid(TAU);
1784                    let theta = if theta > PI { theta - PI } else { theta };
1785                    if !(theta > 1e-9 && theta < PI - 1e-9) {
1786                        return Err(refuse("revolved_lune", "the great circle meets the rim's plane edge-on".into()));
1787                    }
1788                    let mut generatrix = curves[arc].curve.clone();
1789                    let mut surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1790                    // Outward: (x − centre) at the lune's middle.
1791                    let probe = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1792                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1793                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1794                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1795                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1796                    };
1797                    let mut forward = true;
1798                    if !probe(&surface)? {
1799                        generatrix = frag(generatrix.reversed(), "reversed")?;
1800                        surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1801                        forward = false;
1802                    }
1803                    let (start, end) = if forward { (curves[arc].start, curves[arc].end) } else { (curves[arc].end, curves[arc].start) };
1804                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1805                    // The great-circle half: the turned generatrix (u = 1), from
1806                    // `start` to `end`; made once, by the first lune.
1807                    let k_curve = match great {
1808                        Some(index) => index,
1809                        None => {
1810                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: None });
1811                            great = Some(curves.len() - 1);
1812                            curves.len() - 1
1813                        }
1814                    };
1815                    let k_forward = curves[k_curve].start == start;
1816                    let poles = [start, end].map(|p| {
1817                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1818                        curves.len() - 1
1819                    });
1820                    let k_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1821                    let coedges = vec![
1822                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1823                        (k_curve, k_forward, k_pcurve),
1824                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1825                        (arc, !forward, uv_line([0.0, g1], [0.0, g0])?),
1826                    ];
1827                    let mid_psi = if j == 0 { 0.5 * (angles[0] + angles[1]) } else { 0.5 * (angles[1] + angles[0] + TAU) };
1828                    let front = m.dot(at(1.0, 0.0, mid_psi).sub(origin)) > 0.0;
1829                    caps.push(Cap { surface, front, coedges, chart: None });
1830                }
1831            }
1832        }
1833    }
1834    Ok(Split {
1835        points,
1836        curves,
1837        caps,
1838        slides,
1839        slide_sides,
1840        scale,
1841        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1842    })
1843}
1844
1845/// `BREP_SWEEP_RING_WINDING` (default off): a ring whose grazing curves wind
1846/// round its tube as they go once round the ring is split along their
1847/// continuous unwrapping, in six pieces, instead of refused.
1848fn ring_winding_on() -> bool {
1849    crate::switch!("BREP_SWEEP_RING_WINDING", false)
1850}
1851
1852/// A ring split by grazing curves that wind round its tube: the curves' angle
1853/// v on the tube, unwrapped continuously along ψ, gains a whole number of
1854/// turns going once round the ring. None where it gains none (the two-halves
1855/// split serves). Six pieces along ψ keep each band's stretch of v short of a
1856/// whole turn while the curves turn, and leave the tumble's eight trial seams
1857/// (π/4 apart) four distinct placements.
1858#[allow(clippy::too_many_arguments)]
1859fn split_torus_wound(
1860    screw: &Screw,
1861    origin: Vec3,
1862    w: Vec3,
1863    u1: Vec3,
1864    u2: Vec3,
1865    centre: [f64; 2],
1866    radius: f64,
1867    meridian: &[OutlinePiece],
1868) -> Result<Option<Split>, KernelRefusal> {
1869    const PIECES: usize = 6;
1870    let (rho_c, z_c) = (centre[0], centre[1]);
1871    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1872    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
1873    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
1874    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
1875    let n = screw.loop_samples;
1876    let total = PIECES * n;
1877    // (ψ, lower, upper) round the whole ring, each base angle the one nearest
1878    // the last.
1879    let mut round: Vec<(f64, f64, f64)> = Vec::with_capacity(total + 1);
1880    let mut near = {
1881        let (a, b, _) = harmonic(|v| g(0.0, v));
1882        b.atan2(a)
1883    };
1884    for i in 0..=total {
1885        let psi = TAU * i as f64 / total as f64;
1886        let (a, b, c) = harmonic(|v| g(psi, v));
1887        let r = a.hypot(b);
1888        if !(c.abs() < r * (1.0 - 1e-9)) {
1889            return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
1890        }
1891        let base = near + (b.atan2(a) - near + PI).rem_euclid(TAU) - PI;
1892        if i > 0 && (base - near).abs() > 0.5 {
1893            return Err(refuse("ring_grazing", GRAZING_TURNS_TOO_FAST.into()));
1894        }
1895        near = base;
1896        let spread = (-c / r).acos();
1897        round.push((psi, base - spread, base + spread));
1898    }
1899    if ((round[total].1 - round[0].1) / TAU).round() == 0.0 {
1900        return Ok(None);
1901    }
1902    let samples: Vec<Vec<(f64, f64, f64)>> = (0..PIECES).map(|k| round[k * n..=(k + 1) * n].to_vec()).collect();
1903    let seam_psi = |k: usize| TAU * k as f64 / PIECES as f64;
1904    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1905    let mut points: Vec<Vec3> = Vec::new();
1906    let mut curves: Vec<ToolCurve> = Vec::new();
1907    // Points: at each seam, on each branch (the last piece ends on seam 0,
1908    // a whole number of turns round the tube on).
1909    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, branch)
1910    for (seam, piece) in samples.iter().enumerate() {
1911        let (psi, lower, upper) = piece[0];
1912        for (branch, v) in [(0, lower), (1, upper)] {
1913            points.push(point(psi, v));
1914            corner.insert((seam, branch), points.len() - 1);
1915        }
1916    }
1917    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (piece, branch)
1918    for (piece, list) in samples.iter().enumerate() {
1919        for branch in 0..2 {
1920            let mut xyz: Vec<Vec3> = list.iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
1921            let (start, end) = (corner[&(piece, branch)], corner[&((piece + 1) % PIECES, branch)]);
1922            xyz[0] = points[start];
1923            xyz[n] = points[end];
1924            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
1925            branch_curve.insert((piece, branch), curves.len() - 1);
1926        }
1927    }
1928    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
1929        let start = point(psi, v0);
1930        let axis = radial(psi).cross(w);
1931        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
1932        frag(surface.iso_curve_v(0.0), "tube_arc")
1933    };
1934    // Seam arcs of each band: band 0 (front) from lower to upper, band 1
1935    // (back) from upper to lower + 2π.
1936    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
1937    for seam in 0..PIECES {
1938        let (psi, lower, upper) = samples[seam][0];
1939        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
1940        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
1941        seam_arc.insert((seam, 0), curves.len() - 1);
1942        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
1943        seam_arc.insert((seam, 1), curves.len() - 1);
1944    }
1945    let mut caps = Vec::new();
1946    for piece in 0..PIECES {
1947        let (psi_a, psi_b) = (seam_psi(piece), seam_psi(piece + 1));
1948        for band in 0..2 {
1949            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
1950            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
1951            // As in the two-halves split: a margin each side for end trims.
1952            let low = samples[piece].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
1953            let high = samples[piece].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
1954            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
1955            let (v_low, v_high) = (low - margin, high + margin);
1956            let theta_v = v_high - v_low;
1957            if theta_v >= TAU {
1958                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
1959            }
1960            let generatrix = tube_arc(psi_a, v_low, v_high)?;
1961            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
1962            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1963            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
1964            let uv_of = |psi: f64, v: f64| {
1965                Vec3::new(
1966                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
1967                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
1968                    0.0,
1969                )
1970            };
1971            let angles_of = |x: Vec3| -> (f64, f64) {
1972                let r = x.sub(origin);
1973                let psi = r.dot(u2).atan2(r.dot(u1));
1974                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
1975                let q = x.sub(tube_centre(psi));
1976                let v = q.dot(w).atan2(q.dot(radial(psi)));
1977                let mid = 0.5 * (v_low + v_high);
1978                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
1979            };
1980            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1981                let [d0, d1] = frag(curve.domain(), "domain")?;
1982                let ts: Vec<f64> = pcurve_stations(d0, d1);
1983                let mut uv = Vec::with_capacity(ts.len());
1984                for &t in &ts {
1985                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1986                    uv.push(uv_of(psi, v));
1987                }
1988                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
1989                if pcurve_joints_on() {
1990                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1991                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
1992                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1993                        let p = uv_of(psi, v);
1994                        Ok([p.x, p.y])
1995                    };
1996                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1997                        return Ok(fitted);
1998                    }
1999                }
2000                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
2001            };
2002            let lower_edge = branch_curve[&(piece, lo_branch)];
2003            let upper_edge = branch_curve[&(piece, hi_branch)];
2004            let right = seam_arc[&((piece + 1) % PIECES, band)];
2005            let left = seam_arc[&(piece, band)];
2006            let coedges = vec![
2007                (lower_edge, true, inverse_pcurve(&curves[lower_edge].curve)?),
2008                (right, true, inverse_pcurve(&curves[right].curve)?),
2009                (upper_edge, false, frag(inverse_pcurve(&curves[upper_edge].curve)?.reversed(), "reversed")?),
2010                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2011            ];
2012            let mid = &samples[piece][n / 2];
2013            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2014            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 } }) });
2015        }
2016    }
2017    Ok(Some(Split {
2018        points,
2019        curves,
2020        caps,
2021        slides: Vec::new(),
2022        slide_sides: Vec::new(),
2023        scale: rho_c + radius,
2024        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2025    }))
2026}
2027
2028/// A ring (torus: the circle of `radius` about `centre` in (ρ, z), off the
2029/// axis), split by its two grazing curves. For each angle ψ about the ring's
2030/// axis the grazing value along the tube's circle is A cos v + B sin v + C, so
2031/// each curve is a graph v(ψ) round the ring; the front band lies between
2032/// them. Each band is built in two halves (ψ in [0, π] and [π, 2π]) so no face
2033/// closes on itself.
2034#[allow(clippy::too_many_arguments)]
2035fn split_torus(
2036    screw: &Screw,
2037    origin: Vec3,
2038    w: Vec3,
2039    u1: Vec3,
2040    u2: Vec3,
2041    centre: [f64; 2],
2042    radius: f64,
2043    meridian: &[OutlinePiece],
2044) -> Result<Split, KernelRefusal> {
2045    if ring_winding_on() {
2046        if let Some(split) = split_torus_wound(screw, origin, w, u1, u2, centre, radius, meridian)? {
2047            return Ok(split);
2048        }
2049    }
2050    let (rho_c, z_c) = (centre[0], centre[1]);
2051    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
2052    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
2053    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
2054    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
2055    let reference = {
2056        let (a, b, _) = harmonic(|v| g(0.0, v));
2057        b.atan2(a)
2058    };
2059    // The lower and upper grazing angles v at ψ, unwrapped; the front between.
2060    let branches = |psi: f64| -> Option<(f64, f64)> {
2061        let (a, b, c) = harmonic(|v| g(psi, v));
2062        let r = a.hypot(b);
2063        if !(c.abs() < r * (1.0 - 1e-9)) {
2064            return None;
2065        }
2066        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
2067        let spread = (-c / r).acos();
2068        Some((base - spread, base + spread))
2069    };
2070    let n = screw.loop_samples;
2071    let halves = [(0.0, PI), (PI, TAU)];
2072    let mut samples: Vec<Vec<(f64, f64, f64)>> = Vec::new(); // per half: (ψ, lower, upper)
2073    for &(a, b) in &halves {
2074        let mut list = Vec::with_capacity(n + 1);
2075        let mut previous: Option<(f64, f64)> = None;
2076        for i in 0..=n {
2077            let psi = a + (b - a) * i as f64 / n as f64;
2078            let Some(pair) = branches(psi) else {
2079                return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
2080            };
2081            if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
2082                return Err(refuse("ring_grazing", GRAZING_TURNS_TOO_FAST.into()));
2083            }
2084            previous = Some(pair);
2085            list.push((psi, pair.0, pair.1));
2086        }
2087        samples.push(list);
2088    }
2089    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
2090    let mut points: Vec<Vec3> = Vec::new();
2091    let mut curves: Vec<ToolCurve> = Vec::new();
2092    // Points: at ψ = 0 and π, on each branch.
2093    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam 0 | 1, branch)
2094    for seam in 0..2 {
2095        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)) };
2096        for (branch, v) in [(0, lower), (1, upper)] {
2097            points.push(point(psi, v));
2098            corner.insert((seam, branch), points.len() - 1);
2099        }
2100    }
2101    let seam_of_end = |half: usize, at_end: bool| -> usize { if at_end { 1 - half } else { half } };
2102    // K: each branch over each half.
2103    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (half, branch)
2104    for half in 0..2 {
2105        for branch in 0..2 {
2106            let mut xyz: Vec<Vec3> = samples[half].iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
2107            let (start, end) = (corner[&(seam_of_end(half, false), branch)], corner[&(seam_of_end(half, true), branch)]);
2108            xyz[0] = points[start];
2109            xyz[n] = points[end];
2110            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
2111            branch_curve.insert((half, branch), curves.len() - 1);
2112        }
2113    }
2114    // Seam arcs of each band at ψ = 0 and π: band 0 (front) from lower to
2115    // upper, band 1 (back) from upper to lower + 2π.
2116    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
2117        let start = point(psi, v0);
2118        let axis = radial(psi).cross(w);
2119        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
2120        frag(surface.iso_curve_v(0.0), "tube_arc")
2121    };
2122    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
2123    for seam in 0..2 {
2124        let psi = if seam == 0 { 0.0 } else { PI };
2125        let (lower, upper) = (samples[seam][0].1, samples[seam][0].2);
2126        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
2127        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
2128        seam_arc.insert((seam, 0), curves.len() - 1);
2129        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
2130        seam_arc.insert((seam, 1), curves.len() - 1);
2131    }
2132    let mut caps = Vec::new();
2133    for half in 0..2 {
2134        let (psi_a, psi_b) = halves[half];
2135        for band in 0..2 {
2136            // The band's lower and upper edges (v), as branches.
2137            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
2138            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
2139            // A margin each side: an end cap may be carried a little across its
2140            // grazing curve (see `end_trim`), as far as the tube leaves room.
2141            let low = samples[half].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
2142            let high = samples[half].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
2143            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
2144            let (v_low, v_high) = (low - margin, high + margin);
2145            let theta_v = v_high - v_low;
2146            if theta_v >= TAU {
2147                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
2148            }
2149            let generatrix = tube_arc(psi_a, v_low, v_high)?;
2150            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
2151            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
2152            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
2153            let uv_of = |psi: f64, v: f64| {
2154                Vec3::new(
2155                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
2156                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
2157                    0.0,
2158                )
2159            };
2160            // (ψ, v) of a point, unwrapped near the patch.
2161            let angles_of = |x: Vec3| -> (f64, f64) {
2162                let r = x.sub(origin);
2163                let psi = r.dot(u2).atan2(r.dot(u1));
2164                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
2165                let q = x.sub(tube_centre(psi));
2166                let v = q.dot(w).atan2(q.dot(radial(psi)));
2167                let mid = 0.5 * (v_low + v_high);
2168                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
2169            };
2170            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
2171                let [d0, d1] = frag(curve.domain(), "domain")?;
2172                let ts: Vec<f64> = pcurve_stations(d0, d1);
2173                let mut uv = Vec::with_capacity(ts.len());
2174                for &t in &ts {
2175                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2176                    uv.push(uv_of(psi, v));
2177                }
2178                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
2179                if pcurve_joints_on() {
2180                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
2181                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
2182                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2183                        let p = uv_of(psi, v);
2184                        Ok([p.x, p.y])
2185                    };
2186                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
2187                        return Ok(fitted);
2188                    }
2189                }
2190                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
2191            };
2192            let branch_pcurve = |b: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> { inverse_pcurve(&curves[branch_curve[&(half, b)]].curve) };
2193            let lower_edge = branch_curve[&(half, lo_branch)];
2194            let upper_edge = branch_curve[&(half, hi_branch)];
2195            let right = seam_arc[&(seam_of_end(half, true), band)];
2196            let left = seam_arc[&(seam_of_end(half, false), band)];
2197            let coedges = vec![
2198                (lower_edge, true, branch_pcurve(lo_branch, 0.0)?),
2199                (right, true, inverse_pcurve(&curves[right].curve)?),
2200                (upper_edge, false, frag(branch_pcurve(hi_branch, hi_turn)?.reversed(), "reversed")?),
2201                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2202            ];
2203            let mid = &samples[half][n / 2];
2204            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2205            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 } }) });
2206        }
2207    }
2208    Ok(Split {
2209        points,
2210        curves,
2211        caps,
2212        slides: Vec::new(),
2213        slide_sides: Vec::new(),
2214        scale: rho_c + radius,
2215        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2216    })
2217}
2218
2219/// Builder of a closed shell with shared vertices and edges.
2220struct Shell {
2221    vertices: Vec<VertexRecord>,
2222    edges: Vec<EdgeRecord>,
2223    faces: Vec<FaceRecord>,
2224    next: u64,
2225    /// Loops beyond each face's first (holes).
2226    holes: usize,
2227}
2228
2229impl Shell {
2230    fn new() -> Self {
2231        Self { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 1, holes: 0 }
2232    }
2233
2234    fn id(&mut self) -> u64 {
2235        self.next += 1;
2236        self.next
2237    }
2238
2239    fn vertex(&mut self, point: Vec3) -> u64 {
2240        let id = self.id();
2241        self.vertices.push(VertexRecord { id, point });
2242        id
2243    }
2244
2245    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64, degenerate: bool) -> Result<u64, KernelRefusal> {
2246        let domain = frag(curve.domain(), "edge_domain")?;
2247        let id = self.id();
2248        self.edges.push(EdgeRecord { id, curve, t0: domain[0], t1: domain[1], start_vertex_id: start, end_vertex_id: end, degenerate, name: None });
2249        Ok(id)
2250    }
2251
2252    /// A face from its surface and its loop: (edge, traversed forward?, pcurve
2253    /// in the traversal direction).
2254    fn face(&mut self, surface: NurbsSurface, coedges: Vec<(u64, bool, NurbsCurve)>) -> u64 {
2255        let mut records = Vec::with_capacity(coedges.len());
2256        for (edge, forward, pcurve) in coedges {
2257            let id = self.id();
2258            records.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2259        }
2260        let loop_id = self.id();
2261        let id = self.id();
2262        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: vec![LoopRecord { id: loop_id, coedges: records }], name: None });
2263        id
2264    }
2265
2266    /// A face from its surface and its loops, the outer one first.
2267    fn face_loops(&mut self, surface: NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) -> u64 {
2268        let mut records = Vec::with_capacity(loops.len());
2269        for coedges in loops {
2270            let mut list = Vec::with_capacity(coedges.len());
2271            for (edge, forward, pcurve) in coedges {
2272                let id = self.id();
2273                list.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2274            }
2275            let id = self.id();
2276            records.push(LoopRecord { id, coedges: list });
2277        }
2278        self.holes += records.len().saturating_sub(1);
2279        let id = self.id();
2280        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: records, name: None });
2281        id
2282    }
2283
2284    fn solid(mut self) -> BrepSolid {
2285        let shell = self.id();
2286        let id = self.id();
2287        // One shell: V − E + F = 2 − 2g (every face one loop; a pole's
2288        // degenerate edge is not counted, as the validator counts).
2289        let edges = self.edges.iter().filter(|e| !e.degenerate).count() as i64;
2290        // A face with holes counts once for each loop beyond its first less.
2291        let euler = self.vertices.len() as i64 - edges + self.faces.len() as i64 - self.holes as i64;
2292        let genus = (2 - euler) / 2;
2293        BrepSolid {
2294            mass_properties_cache: Default::default(),
2295            id,
2296            vertices: self.vertices,
2297            edges: self.edges,
2298            shells: vec![ShellRecord { id: shell, faces: self.faces }],
2299            genus,
2300            kind: Default::default(),
2301            cells: Default::default(),
2302        }
2303    }
2304}
2305
2306/// The whole sweep of `tool` along `motion` (a single screw, turn or slide),
2307/// its two end positions included.
2308pub fn sweep_solid(tool: &SolidTool, motion: &SolidMotion) -> Result<BrepSolid, KernelRefusal> {
2309    let screw = Screw::from_motion(motion)?;
2310    let refusal = match sweep_with(&screw, tool) {
2311        Err(refusal) => refusal,
2312        body => return body,
2313    };
2314    // A rescue where the general route refuses: a cone turned about a line
2315    // crossing its axis inside it (`BREP_SWEEP_CONE_ACROSS`).
2316    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool {
2317        if cone_across::cone_across_on() {
2318            if let Ok(Some(body)) = cone_across::cone_across_axis(&screw, *axis_origin, *axis_direction, meridian) {
2319                return Ok(body);
2320            }
2321        }
2322    }
2323    Err(refusal)
2324}
2325
2326fn sweep_with(screw: &Screw, tool: &SolidTool) -> Result<BrepSolid, KernelRefusal> {
2327    let screw = *screw;
2328    if let SolidTool::Revolved { meridian, .. } = tool {
2329        refuse_elliptic(meridian)?;
2330    }
2331    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, radial } = tool {
2332        if let Some(body) = ball_across_axis(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2333            return Ok(body);
2334        }
2335        // (A tool whose radial direction lies along its axis is left to the
2336        // refusal below.)
2337        let radial_holds = match (tool, axis_direction.normalized()) {
2338            (SolidTool::Revolved { radial, .. }, Ok(w)) => radial.sub(w.scale(radial.dot(w))).normalized().is_ok(),
2339            _ => false,
2340        };
2341        if radial_holds && ball_screw::ball_screw_on() {
2342            if let Some(body) = ball_screw::ball_screwed_past_fold(&screw, *axis_origin, *axis_direction, meridian)? {
2343                return Ok(body);
2344            }
2345        }
2346    }
2347    if let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool {
2348        if ring_fold::ring_fold_on() {
2349            if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() {
2350                if ((end - start).abs() - TAU).abs() < 1e-12 {
2351                    let w = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
2352                    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
2353                    if let Some(body) = ring_fold::ring_slid_past_fold(&screw, *axis_origin, w, u1, w.cross(u1), *centre, *radius)? {
2354                        return Ok(body);
2355                    }
2356                }
2357            }
2358        }
2359        if let Some(body) = flat_ring(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2360            return Ok(body);
2361        }
2362        if let Some(body) = rod_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2363            return Ok(body);
2364        }
2365    }
2366    if let SolidTool::Polyhedron { vertices, faces } = tool {
2367        let slid = screw.omega == 0.0 && screw.c2 == 0.0 && screw.frame.is_none() && screw.turns.is_none();
2368        if slid && slid_hull_on() {
2369            return slid_polyhedron_hull(&screw, vertices, faces);
2370        }
2371    }
2372    if let SolidTool::Polyhedron { vertices, faces } = tool {
2373        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);
2374        if whole {
2375            return whole_turn_shadow(&screw, vertices, faces);
2376        }
2377    }
2378    let split = match tool {
2379        SolidTool::Polyhedron { vertices, faces } => split_polyhedron(&screw, vertices, faces)?,
2380        SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } => {
2381            split_revolved(&screw, *axis_origin, *axis_direction, *radial, meridian)?
2382        }
2383    };
2384    let grazing = split.grazing()?;
2385    // A tool slid along its own axis has no grazing curve: its sliding sides
2386    // join its back at the start to its front at the end.
2387    if grazing.is_empty() && split.slide_sides.is_empty() {
2388        return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
2389    }
2390    let times = row_times(&screw);
2391    let last = times.len() - 1;
2392    let mut shell = Shell::new();
2393    // Vertices and edges at the row times (0 and `last` are the end positions),
2394    // made on demand.
2395    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
2396    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
2397    let mut at_time = |shell: &mut Shell, j: usize, p: usize| -> u64 {
2398        *vertex_at.entry((j, p)).or_insert_with(|| shell.vertex(screw.apply(times[j], split.points[p])))
2399    };
2400    let mut time_edge = |shell: &mut Shell, j: usize, c: usize, vertex: &mut dyn FnMut(&mut Shell, usize, usize) -> u64| -> Result<u64, KernelRefusal> {
2401        if let Some(&edge) = edge_at.get(&(j, c)) {
2402            return Ok(edge);
2403        }
2404        let curve = &split.curves[c];
2405        let (a, b) = (vertex(shell, j, curve.start), vertex(shell, j, curve.end));
2406        let edge = shell.edge(screw.move_curve(times[j], &curve.curve)?, a, b, curve.degenerate)?;
2407        edge_at.insert((j, c), edge);
2408        Ok(edge)
2409    };
2410    // Caps: the back at t0, the front at t1.
2411    for cap in &split.caps {
2412        let j = if cap.front { last } else { 0 };
2413        let surface = screw.move_surface(times[j], &cap.surface)?;
2414        let mut coedges = Vec::with_capacity(cap.coedges.len());
2415        for (c, forward, pcurve) in &cap.coedges {
2416            let edge = time_edge(&mut shell, j, *c, &mut at_time)?;
2417            coedges.push((edge, *forward, pcurve.clone()));
2418        }
2419        shell.face(surface, coedges);
2420    }
2421    // Walls, a row at a time. The back cap at t0 runs K's curve with the back
2422    // on its left, so the wall beside it runs the other way: u along the curve
2423    // that way, v from the row's start to its end, the loop (u0,0) (u1,0)
2424    // (u1,1) (u0,1).
2425    // The paths of K's corners, a row at a time: (row, point) -> edge.
2426    let mut orbit_at: HashMap<(usize, usize), u64> = HashMap::new();
2427    for row in 0..last {
2428        let (ta, tb) = (times[row], times[row + 1]);
2429        let segments = carry_segments(&screw, ta, tb);
2430        let knots_v = carry_knots(segments);
2431        let mut orbits: HashMap<usize, u64> = HashMap::new();
2432        for &(c, _) in &grazing {
2433            for r in [split.curves[c].start, split.curves[c].end] {
2434                if orbits.contains_key(&r) {
2435                    continue;
2436                }
2437                let (v0, v1) = (at_time(&mut shell, row, r), at_time(&mut shell, row + 1, r));
2438                let edge = shell.edge(carry_curve(&screw, split.points[r], ta, tb, segments)?, v0, v1, false)?;
2439                orbits.insert(r, edge);
2440                orbit_at.insert((row, r), edge);
2441            }
2442        }
2443        for &(c, back_forward) in &grazing {
2444            let tool_curve = &split.curves[c];
2445            let along = if back_forward { frag(tool_curve.curve.reversed(), "reversed")? } else { tool_curve.curve.clone() };
2446            let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
2447            let mut rows = Vec::with_capacity(along.control_points.len());
2448            for p in &along.control_points {
2449                let x = frag(p.point(), "control_point")?;
2450                rows.push(carry_points(&screw, x, ta, tb, segments).into_iter().map(|q| Vec4::from_point(q, p.w)).collect::<Vec<_>>());
2451            }
2452            let surface = frag(NurbsSurface::new(along.degree, 5, along.knots.clone(), knots_v.clone(), rows), "wall")?;
2453            let [u0, u1] = frag(along.domain(), "domain")?;
2454            let bottom = time_edge(&mut shell, row, c, &mut at_time)?;
2455            let top = time_edge(&mut shell, row + 1, c, &mut at_time)?;
2456            let coedges = vec![
2457                (bottom, !back_forward, uv_line([u0, 0.0], [u1, 0.0])?),
2458                (orbits[&to], true, uv_line([u1, 0.0], [u1, 1.0])?),
2459                (top, back_forward, uv_line([u1, 1.0], [u0, 1.0])?),
2460                (orbits[&from], false, uv_line([u0, 1.0], [u0, 0.0])?),
2461            ];
2462            shell.face(surface, coedges);
2463        }
2464    }
2465    // Sliding ends: each rim arc where its neighbour's cap sits (back at t0,
2466    // front at t1), joined by the paths of the points where that changes.
2467    // Faces the tool slides within: the one-pass probe stands further off them.
2468    let mut sliding: std::collections::HashSet<u64> = std::collections::HashSet::new();
2469    let side_of: HashMap<usize, bool> = split.caps.iter().flat_map(|cap| cap.coedges.iter().map(move |&(c, _, _)| (c, cap.front))).collect();
2470    for slide in &split.slides {
2471        let centre = screw.apply(times[0], slide.centre);
2472        let u = screw.apply(times[0], slide.centre.add(slide.u)).sub(centre);
2473        let v = screw.apply(times[0], slide.centre.add(slide.v)).sub(centre);
2474        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2475            match side_of.get(&c) {
2476                Some(true) => Ok(last),
2477                Some(false) => Ok(0),
2478                None => Err(refuse("revolved_grazing", "a sliding end has no face beside its rim".into())),
2479            }
2480        };
2481        let mut coedges = Vec::new();
2482        let mut corners: Vec<Vec3> = Vec::new();
2483        let push = |coedges: &mut Vec<(u64, bool, NurbsCurve)>, corners: &mut Vec<Vec3>, edge: u64, forward: bool, curve: &NurbsCurve| -> Result<(), KernelRefusal> {
2484            let [d0, d1] = frag(curve.domain(), "domain")?;
2485            for k in 0..=8 {
2486                corners.push(frag(curve.evaluate(d0 + (d1 - d0) * k as f64 / 8.0), "slide")?);
2487            }
2488            coedges.push((edge, forward, plane_pcurve(centre, u, v, curve, forward)?));
2489            Ok(())
2490        };
2491        for (index, &(c, forward)) in slide.rim.iter().enumerate() {
2492            let j = row_of(c)?;
2493            let edge = time_edge(&mut shell, j, c, &mut at_time)?;
2494            push(&mut coedges, &mut corners, edge, forward, &screw.move_curve(times[j], &split.curves[c].curve)?)?;
2495            // On to the next arc's time along the path of the point between them.
2496            let (next, _) = slide.rim[(index + 1) % slide.rim.len()];
2497            let next_j = row_of(next)?;
2498            if next_j == j {
2499                continue;
2500            }
2501            let point = if forward { split.curves[c].end } else { split.curves[c].start };
2502            let rows: Vec<usize> = if next_j > j { (j..next_j).collect() } else { (next_j..j).rev().collect() };
2503            for row in rows {
2504                let Some(&orbit) = orbit_at.get(&(row, point)) else {
2505                    return Err(refuse("revolved_grazing", "a sliding end's rim changes side where no grazing curve meets it".into()));
2506                };
2507                let (ta, tb) = (times[row], times[row + 1]);
2508                let curve = carry_curve(&screw, split.points[point], ta, tb, carry_segments(&screw, ta, tb))?;
2509                push(&mut coedges, &mut corners, orbit, next_j > j, &curve)?;
2510            }
2511        }
2512        sliding.insert(shell.face(plane_patch(centre, u, v, &corners)?, coedges));
2513    }
2514    // Sliding cylinders: from the start rim where its neighbour sits to the
2515    // end rim where its neighbour sits, in halves seamed along generators.
2516    for side in &split.slide_sides {
2517        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2518            match side_of.get(&c) {
2519                Some(true) => Ok(last),
2520                Some(false) => Ok(0),
2521                None => Err(refuse("revolved_grazing", "a sliding side has no face beside its rim".into())),
2522            }
2523        };
2524        let origin = screw.apply(times[0], side.origin);
2525        let w = screw.apply(times[0], side.origin.add(side.w)).sub(origin);
2526        let rows: Vec<[usize; 2]> = side.patches.iter().map(|patch| Ok([row_of(patch.2)?, row_of(patch.3)?])).collect::<Result<_, KernelRefusal>>()?;
2527        if rows.iter().any(|r| *r != rows[0]) {
2528            return Err(refuse("revolved_grazing", "a sliding side's rim changes side along it".into()));
2529        }
2530        let [jb, ja] = rows[0];
2531        // Seams: the generator at each patch's start angle, rim point to rim point.
2532        let mut seams = Vec::with_capacity(side.patches.len());
2533        for patch in &side.patches {
2534            let (a, b) = (at_time(&mut shell, jb, patch.4[0]), at_time(&mut shell, ja, patch.4[1]));
2535            let line = frag(make_line(screw.apply(times[jb], split.points[patch.4[0]]), screw.apply(times[ja], split.points[patch.4[1]])), "seam")?;
2536            seams.push((shell.edge(line.clone(), a, b, false)?, line));
2537        }
2538        for (k, patch) in side.patches.iter().enumerate() {
2539            let surface = frag(make_revolution(origin, w, &seams[k].1, patch.1), "slide_side")?;
2540            let lower = time_edge(&mut shell, jb, patch.2, &mut at_time)?;
2541            let upper = time_edge(&mut shell, ja, patch.3, &mut at_time)?;
2542            let next = (k + 1) % side.patches.len();
2543            let face = shell.face(
2544                surface,
2545                vec![
2546                    (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
2547                    (seams[next].0, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
2548                    (upper, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
2549                    (seams[k].0, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
2550                ],
2551            );
2552            sliding.insert(face);
2553        }
2554    }
2555    let body = shell.solid();
2556    let issues = body.validate();
2557    if !issues.is_empty() {
2558        return Err(refuse("assembly", format!("the assembled sweep is not valid: {:?}", issues.first())));
2559    }
2560    // A ball under one screw is proved one pass from its centre's helix
2561    // (`BREP_SWEEP_BALL_ONE_PASS`, default on): nothing for the walk to find.
2562    if !crate::solid_sweep_one_pass::ball_screw_one_pass(&screw, tool) {
2563        check_single_pass(&screw, &split, &body, &sliding)?;
2564    }
2565    Ok(body)
2566}
2567
2568/// A rod (a cylinder with flat ends) TURNED about a line that crosses its
2569/// axis squarely between its ends, if `meridian` is one and the motion such.
2570///
2571/// Arm by arm: the rod is its arm one way from the turn's axis and its arm
2572/// the other way, and sweeps what they sweep. At a height z (half-width
2573/// w = √(r² − z²)) an arm of length L is the rectangle 0 ≤ x ≤ L, |y| ≤ w,
2574/// which a circle about the turn's axis of radius ρ ≤ L meets in one arc
2575/// holding the arm's own direction, and beyond, out to √(L² + w²), in two
2576/// arcs ±[a, b] with a ≤ acos(L / √(L² + r²)). Turned by more than 2a, the
2577/// two arcs sweep the same angles as the arc [−b, b] they leave a gap in:
2578/// the arm with the gap filled, its points beyond its end within
2579/// √(L² + r²) of the crossing point (a cap of that ball). The filled arm
2580/// meets every circle in one arc holding its direction, so it sweeps itself
2581/// where it starts and where it stops and, between, its section by the half
2582/// plane at its direction turned. So the sweep is the union of the filled rod
2583/// (one solid of revolution about the rod's axis) at both ends of the turn
2584/// and the two arms' sections turned.
2585fn rod_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2586    if screw.frame.is_some() || screw.turns.is_some() || screw.omega == 0.0 || screw.c != 0.0 || screw.c2 != 0.0 {
2587        return Ok(None);
2588    }
2589    let Ok(w) = axis.normalized() else { return Ok(None) };
2590    // A rectangle against the axis: radius r from z0 to z1.
2591    let mut corners: Vec<[f64; 2]> = Vec::new();
2592    for piece in meridian {
2593        let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2594        corners.push(*from);
2595        corners.push(*to);
2596    }
2597    if meridian.len() != 4 {
2598        return Ok(None);
2599    }
2600    let r = corners.iter().map(|c| c[0]).fold(0.0f64, f64::max);
2601    let (z0, z1) = corners.iter().map(|c| c[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
2602    let scale = r.max(z0.abs()).max(z1.abs());
2603    let on = |a: f64, b: f64| (a - b).abs() <= 1e-12 * scale;
2604    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))) {
2605        return Ok(None);
2606    }
2607    // The turn's axis squarely across the rod's, between its ends.
2608    if w.dot(screw.e).abs() > 1e-12 {
2609        return Ok(None);
2610    }
2611    let offset = screw.a.sub(origin);
2612    let along = offset.dot(w);
2613    let foot = origin.add(w.scale(along));
2614    let apart = screw.a.sub(foot);
2615    if apart.sub(screw.e.scale(apart.dot(screw.e))).length() > 1e-12 * (scale + offset.length()) {
2616        return Ok(None);
2617    }
2618    if !(along > z0 + 1e-9 * scale && along < z1 - 1e-9 * scale) {
2619        return Ok(None);
2620    }
2621    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2622    let arms = [z1 - along, along - z0];
2623    let gap = arms.iter().map(|l| (l / l.hypot(r)).acos()).fold(0.0f64, f64::max);
2624    if !(theta > 2.0 * gap * (1.0 + 1e-9) && theta < TAU * (1.0 - 1e-9)) {
2625        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()));
2626    }
2627    let arc = |centre: Vec3, from: Vec3, normal: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
2628        let surface = frag(make_revolution(centre, normal, &frag(make_line(from, from.add(normal)), "line")?, angle), "rod_across")?;
2629        frag(surface.iso_curve_v(0.0), "rod_across")
2630    };
2631    let line = |a: Vec3, b: Vec3| frag(make_line(a, b), "rod_across");
2632    // At one time: the crossing point, the rod's direction and the turn's.
2633    let filled_at = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2634        let o = screw.apply(t, foot);
2635        let x = screw.apply(t, foot.add(w)).sub(o);
2636        let up = screw.e;
2637        let at = |rho: f64, s: f64| o.add(up.scale(rho)).add(x.scale(s));
2638        let n = up.cross(x);
2639        let (far_plus, far_minus) = (arms[0].hypot(r), arms[1].hypot(r));
2640        let profile = [
2641            arc(o, at(0.0, -far_minus), n, r.atan2(arms[1]))?,
2642            line(at(r, -arms[1]), at(r, arms[0]))?,
2643            arc(o, at(r, arms[0]), n, r.atan2(arms[0]))?,
2644            line(at(0.0, far_plus), at(0.0, -far_minus))?,
2645        ];
2646        frag(crate::revolve_profile_brep(&profile, o, x, TAU), "rod_across")
2647    };
2648    let o = screw.apply(screw.t0, foot);
2649    let x = screw.apply(screw.t0, foot.add(w)).sub(o);
2650    let turn_axis = screw.e.scale(screw.omega.signum());
2651    let section = |direction: Vec3, length: f64| -> Result<BrepSolid, KernelRefusal> {
2652        let at = |rho: f64, z: f64| o.add(direction.scale(rho)).add(screw.e.scale(z));
2653        let half = (r / length.hypot(r)).asin();
2654        let profile = [
2655            line(at(0.0, -r), at(length, -r))?,
2656            arc(o, at(length, -r), direction.cross(screw.e), 2.0 * half)?,
2657            line(at(length, r), at(0.0, r))?,
2658            line(at(0.0, r), at(0.0, -r))?,
2659        ];
2660        frag(crate::revolve_profile_brep(&profile, o, turn_axis, theta), "rod_across")
2661    };
2662    let parts = [filled_at(screw.t0)?, filled_at(screw.t1)?, section(x, arms[0])?, section(x.scale(-1.0), arms[1])?];
2663    crate::boolean_operation_nary(&parts, crate::BooleanOperation::Union).map(Some)
2664}
2665
2666/// `BREP_SWEEP_RING_LENS_SEWN` (on by default; `=0` restores the booleans): a
2667/// ring slid flat short of its
2668/// hole's width is the filled ring's sweep less the lens its hole leaves open
2669/// at both ends. That lens is built here and sewn into the sweep's top and
2670/// bottom faces in place of the two booleans (the lens intersect and the
2671/// subtract): its caps are the two holes' top and bottom discs in common,
2672/// whose outlines become inner loops of the sweep's flat faces, and its walls
2673/// are the two holes' own tube surfaces, meeting in the slide's bisector
2674/// plane along `y(ψ) = √(ρ(ψ)² − D²/4)`, `ρ = R − r cos ψ`, `z = r sin ψ`
2675/// (the tube's section by that plane, interpolated through exact points and
2676/// read back against them). A lens that pinches at the tube's middle (`D ≥
2677/// 2 (R − r)`) or anything that does not validate is left to the booleans.
2678pub(crate) fn ring_lens_sewn_on() -> bool {
2679    crate::switch!("BREP_SWEEP_RING_LENS_SEWN", true)
2680}
2681
2682/// `BREP_SWEEP_RING_LENS_SEWN_CHECK` (default off): both built, the booleans'
2683/// body kept; the sewn one's volume and area compared with it
2684/// ([`ring_lens_check_take`]).
2685fn ring_lens_sewn_check_on() -> bool {
2686    crate::switch!("BREP_SWEEP_RING_LENS_SEWN_CHECK", false)
2687}
2688
2689thread_local! {
2690    static RING_LENS_CHECK: std::cell::Cell<(u64, u64, f64)> = const { std::cell::Cell::new((0, 0, 0.0)) };
2691}
2692
2693/// (bodies compared, sewn bodies missing or differing past `1e-7` relative
2694/// in volume or area, the worst relative difference) on this thread since the
2695/// last call. The bar is the booleans' own error, the bench's tier: the sewn
2696/// body reads the closed form to `1e-10` where the booleans' body reads it
2697/// `2.9e-9` off (tube 2 round 6, slid 6) and `3.8e-8` off (tube 1 round 5,
2698/// slid 3).
2699pub fn ring_lens_check_take() -> (u64, u64, f64) {
2700    RING_LENS_CHECK.with(|cell| cell.replace((0, 0, 0.0)))
2701}
2702
2703fn ring_lens_check_record(cut: &BrepSolid, sewn: Option<&BrepSolid>) {
2704    let worst = match (crate::solid_mass_properties(cut), sewn.map(crate::solid_mass_properties)) {
2705        (Ok(a), Some(Ok(b))) => ((a.volume - b.volume) / a.volume).abs().max(((a.surface_area - b.surface_area) / a.surface_area).abs()),
2706        _ => f64::INFINITY,
2707    };
2708    RING_LENS_CHECK.with(|cell| {
2709        let (n, bad, w) = cell.get();
2710        cell.set((n + 1, bad + u64::from(!(worst <= 1e-7)), w.max(worst)));
2711    });
2712}
2713
2714/// The filled ring's sweep `whole` (a slide of the ring's centre from `c0` to
2715/// `c1`, square to its axis `w`, its tube `tube` round the circle of radius
2716/// `big`) less the lens both holes share, built directly. `None` where it
2717/// does not apply or does not validate.
2718fn sewn_lens(whole: &BrepSolid, c0: Vec3, c1: Vec3, w: Vec3, big: f64, tube: f64) -> Option<BrepSolid> {
2719    let slide = c1.sub(c0);
2720    let d = slide.length();
2721    let scale = (big + tube + d).max(1e-300);
2722    if !(slide.dot(w).abs() <= 1e-12 * scale && d > 1e-9 * scale && d < 2.0 * (big - tube) * (1.0 - 1e-9)) {
2723        return None;
2724    }
2725    let ed = slide.scale(1.0 / d);
2726    let ey = w.cross(ed);
2727    let mid = c0.add(ed.scale(0.5 * d));
2728    let half = 0.5 * d;
2729    let alpha = (half / big).acos();
2730    let y_top = (big * big - half * half).sqrt();
2731    let corner = |side: f64, z: f64| mid.add(ey.scale(side * y_top)).add(w.scale(z));
2732    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));
2733    // The flat faces the caps sit in.
2734    let shell = whole.shells.first()?;
2735    let flat_at = |z: f64| -> Option<usize> {
2736        shell.faces.iter().position(|f| {
2737            f.loops.len() == 1
2738                && f.surface.degree_u == 1
2739                && f.surface.degree_v == 1
2740                && 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))
2741        })
2742    };
2743    let (top, bottom) = (flat_at(tube)?, flat_at(-tube)?);
2744    // Edges. Arcs: A on the circle about c0 (the lens's side away from c0's
2745    // far rim: angles −α..α from ed), B about c1 (π−α..π+α).
2746    let arc = |centre: Vec3, from: f64, to: f64| crate::make_arc(centre, ed, ey, big, from, to).ok();
2747    let a_top = arc(c0.add(w.scale(tube)), -alpha, alpha)?; // t_minus -> t_plus
2748    let b_top = arc(c1.add(w.scale(tube)), PI - alpha, PI + alpha)?; // t_plus -> t_minus
2749    let a_bot = arc(c0.add(w.scale(-tube)), -alpha, alpha)?; // b_minus -> b_plus
2750    let b_bot = arc(c1.add(w.scale(-tube)), PI - alpha, PI + alpha)?; // b_plus -> b_minus
2751    // The walls' carriers: each hole's inner tube half turned a whole turn
2752    // about its axis, its generatrix drawn opposite the lens (the turn's seam
2753    // away from the wall).
2754    let wall_surface = |centre: Vec3, away: Vec3| -> Option<NurbsSurface> {
2755        let n = w.cross(away);
2756        let at = |rho: f64, z: f64| centre.add(away.scale(rho)).add(w.scale(z));
2757        let from = at(big, -tube);
2758        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()?;
2759        crate::make_revolution(centre, w, &half_round, TAU).ok()
2760    };
2761    let (wall_a, wall_b) = (wall_surface(c0, ed.scale(-1.0))?, wall_surface(c1, ed)?);
2762    // Seams, bottom to top, through exact points of the bisector section, with
2763    // their pcurves on both walls interpolated through the same points' feet
2764    // at the same parameters; all three read back at the mid-samples.
2765    // (Each seam in two halves, split at the tube's waist ψ = 0: the walls'
2766    // half-round generatrix is two quarter arcs, its parameter speed jumps
2767    // there, and a pcurve through it would kink.)
2768    let seam = |side: f64, from: f64, to: f64| -> Option<(NurbsCurve, NurbsCurve, NurbsCurve)> {
2769        let at = |psi: f64| {
2770            let rho = big - tube * psi.cos();
2771            mid.add(ey.scale(side * (rho * rho - half * half).max(0.0).sqrt())).add(w.scale(tube * psi.sin()))
2772        };
2773        let feet = |surface: &NurbsSurface, points: &[Vec3]| -> Option<Vec<Vec3>> {
2774            let mut out: Vec<Vec3> = Vec::with_capacity(points.len());
2775            for point in points {
2776                // From the last foot; where that lands off the point (the tube
2777                // turning fast near its top and bottom), the global reading.
2778                let seeded = out.last().and_then(|last| crate::project_point_to_surface_seeded(surface, *point, last.x, last.y).ok());
2779                let q = match seeded {
2780                    Some(q) if q.distance <= 1e-7 * scale => q,
2781                    _ => crate::project_point_to_surface(surface, *point).ok()?,
2782                };
2783                // The projector stops near 1e-9; the point is on the carrier
2784                // exactly, so Gauss-Newton on |S(u, v) − p|² takes the foot to
2785                // rounding.
2786                let (mut u, mut v) = (q.u, q.v);
2787                for _ in 0..4 {
2788                    let d = surface.derivatives_small(u, v, 1).ok()?;
2789                    let (f, su, sv) = (d[0][0].sub(*point), d[1][0], d[0][1]);
2790                    let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv));
2791                    let (g0, g1) = (su.dot(f), sv.dot(f));
2792                    let det = a * c - b * b;
2793                    if !(det > 0.0) {
2794                        return None;
2795                    }
2796                    u -= (c * g0 - b * g1) / det;
2797                    v -= (a * g1 - b * g0) / det;
2798                }
2799                if !(surface.evaluate(u, v).ok()?.sub(*point).length() <= 1e-11 * scale) {
2800                    return None;
2801                }
2802                out.push(Vec3::new(u, v, 0.0));
2803            }
2804            Some(out)
2805        };
2806        let mut n = 16usize;
2807        loop {
2808            let psis: Vec<f64> = (0..=n).map(|k| from + (to - from) * k as f64 / n as f64).collect();
2809            let points: Vec<Vec3> = psis.iter().map(|&psi| at(psi)).collect();
2810            let params: Vec<f64> = psis.iter().map(|psi| (psi - from) / (to - from)).collect();
2811            let curve = crate::interpolate_curve(&points, 3, &params).ok()?;
2812            let on_a = crate::interpolate_curve(&feet(&wall_a, &points)?, 3, &params).ok()?;
2813            let on_b = crate::interpolate_curve(&feet(&wall_b, &points)?, 3, &params).ok()?;
2814            let mut worst = 0.0f64;
2815            for k in 0..n {
2816                let psi = 0.5 * (psis[k] + psis[k + 1]);
2817                let t = (psi - from) / (to - from);
2818                let p = curve.evaluate(t).ok()?;
2819                worst = worst.max(p.sub(at(psi)).length());
2820                for (surface, pcurve) in [(&wall_a, &on_a), (&wall_b, &on_b)] {
2821                    let uv = pcurve.evaluate(t).ok()?;
2822                    worst = worst.max(surface.evaluate(uv.x, uv.y).ok()?.sub(p).length());
2823                }
2824            }
2825            if worst <= 1e-10 * scale {
2826                return Some((curve, on_a, on_b));
2827            }
2828            if n >= 4096 {
2829                return None;
2830            }
2831            n *= 2;
2832        }
2833    };
2834    let (lower_plus, upper_plus) = (seam(1.0, -0.5 * PI, 0.0)?, seam(1.0, 0.0, 0.5 * PI)?);
2835    let (lower_minus, upper_minus) = (seam(-1.0, -0.5 * PI, 0.0)?, seam(-1.0, 0.0, 0.5 * PI)?);
2836    let waist = |side: f64| mid.add(ey.scale(side * ((big - tube).powi(2) - half * half).sqrt()));
2837    let (m_plus, m_minus) = (waist(1.0), waist(-1.0));
2838    // Ids past every existing one.
2839    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;
2840    let mut id = || {
2841        next += 1;
2842        next
2843    };
2844    let mut body = whole.clone();
2845    let vertex = |body: &mut BrepSolid, id: u64, point: Vec3| body.vertices.push(VertexRecord { id, point });
2846    let (vt_plus, vt_minus, vb_plus, vb_minus, vm_plus, vm_minus) = (id(), id(), id(), id(), id(), id());
2847    vertex(&mut body, vm_plus, m_plus);
2848    vertex(&mut body, vm_minus, m_minus);
2849    vertex(&mut body, vt_plus, t_plus);
2850    vertex(&mut body, vt_minus, t_minus);
2851    vertex(&mut body, vb_plus, b_plus);
2852    vertex(&mut body, vb_minus, b_minus);
2853    let mut edge = |body: &mut BrepSolid, curve: NurbsCurve, start: u64, end: u64| -> Option<u64> {
2854        let [t0, t1] = curve.domain().ok()?;
2855        let e = id();
2856        body.edges.push(EdgeRecord { id: e, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
2857        Some(e)
2858    };
2859    // The arcs' ends must be the corners they are named for.
2860    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)] {
2861        let [t0, t1] = curve.domain().ok()?;
2862        if curve.evaluate(t0).ok()?.sub(a).length() > 1e-9 * scale || curve.evaluate(t1).ok()?.sub(b).length() > 1e-9 * scale {
2863            return None;
2864        }
2865    }
2866    // The seams' pcurves, built with them: (edge, wall, pcurve along the edge).
2867    let mut given: Vec<(u64, usize, NurbsCurve)> = Vec::new();
2868    let e_a_top = edge(&mut body, a_top, vt_minus, vt_plus)?;
2869    let e_b_top = edge(&mut body, b_top, vt_plus, vt_minus)?;
2870    let e_a_bot = edge(&mut body, a_bot, vb_minus, vb_plus)?;
2871    let e_b_bot = edge(&mut body, b_bot, vb_plus, vb_minus)?;
2872    let mut seam_edge = |body: &mut BrepSolid, piece: (NurbsCurve, NurbsCurve, NurbsCurve), start: u64, end: u64, given: &mut Vec<(u64, usize, NurbsCurve)>| -> Option<u64> {
2873        let (curve, on_a, on_b) = piece;
2874        let e = edge(body, curve, start, end)?;
2875        given.extend([(e, 1, on_a), (e, 2, on_b)]);
2876        Some(e)
2877    };
2878    let e_lp = seam_edge(&mut body, lower_plus, vb_plus, vm_plus, &mut given)?;
2879    let e_up = seam_edge(&mut body, upper_plus, vm_plus, vt_plus, &mut given)?;
2880    let e_lm = seam_edge(&mut body, lower_minus, vb_minus, vm_minus, &mut given)?;
2881    let e_um = seam_edge(&mut body, upper_minus, vm_minus, vt_minus, &mut given)?;
2882    let curve_of = |body: &BrepSolid, e: u64| body.edges.iter().find(|x| x.id == e).map(|x| x.curve.clone());
2883    // A coedge of edge `e` on `surface`, forward or reversed, with its pcurve
2884    // fitted along the coedge.
2885    let coedge = |body: &BrepSolid, id: u64, surface: &NurbsSurface, e: u64, forward: bool, given: &[(u64, usize, NurbsCurve)], wall: usize| -> Option<CoedgeRecord> {
2886        if let Some((_, _, pcurve)) = given.iter().find(|(edge, on, _)| *edge == e && *on == wall) {
2887            let pcurve = if forward { pcurve.clone() } else { pcurve.reversed().ok()? };
2888            return Some(CoedgeRecord { id, edge_id: e, forward, pcurve });
2889        }
2890        let fit = crate::fit_pcurve_on_surface(surface, &curve_of(body, e)?).ok()?;
2891        if !(fit.report.residual <= 1e-7 * scale) {
2892            return None;
2893        }
2894        let pcurve = if forward { fit.curve } else { fit.curve.reversed().ok()? };
2895        Some(CoedgeRecord { id, edge_id: e, forward, pcurve })
2896    };
2897    // The loop's signed area in its face's parameters.
2898    let uv_area = |coedges: &[CoedgeRecord]| -> f64 {
2899        let mut area = 0.0;
2900        for c in coedges {
2901            let Ok([p0, p1]) = c.pcurve.domain() else { return f64::NAN };
2902            let samples = 64;
2903            let mut last = match c.pcurve.evaluate(p0) { Ok(p) => p, Err(_) => return f64::NAN };
2904            for k in 1..=samples {
2905                let Ok(p) = c.pcurve.evaluate(p0 + (p1 - p0) * k as f64 / samples as f64) else { return f64::NAN };
2906                area += last.x * p.y - p.x * last.y;
2907                last = p;
2908            }
2909        }
2910        0.5 * area
2911    };
2912    // Caps: the top's hole runs clockwise seen from outside (from +w), the
2913    // bottom's clockwise seen from −w.
2914    for (face_index, loop_edges) in [(top, [(e_a_top, false), (e_b_top, false)]), (bottom, [(e_a_bot, true), (e_b_bot, true)])] {
2915        let surface = body.shells[0].faces[face_index].surface.clone();
2916        let mut coedges = Vec::new();
2917        for (e, forward) in loop_edges {
2918            let c = id();
2919            coedges.push(coedge(&body, c, &surface, e, forward, &given, 0)?);
2920        }
2921        // An inner loop runs opposite its face's outer loop in the parameters.
2922        let outer = uv_area(&body.shells[0].faces[face_index].loops[0].coedges);
2923        let inner = uv_area(&coedges);
2924        if !(outer.is_finite() && inner.is_finite() && outer * inner < 0.0) {
2925            return None;
2926        }
2927        let loop_id = id();
2928        body.shells[0].faces[face_index].loops.push(LoopRecord { id: loop_id, coedges });
2929    }
2930    // Walls: A uses the arcs the caps reversed and B likewise, the seams once each way.
2931    for (wall, surface, centre, loop_edges) in [
2932        (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)]),
2933        (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)]),
2934    ] {
2935        let mut coedges = Vec::new();
2936        for (e, forward) in loop_edges {
2937            let c = id();
2938            coedges.push(coedge(&body, c, &surface, e, forward, &given, wall)?);
2939        }
2940        let area = uv_area(&coedges);
2941        if !(area.is_finite() && area != 0.0) {
2942            return None;
2943        }
2944        // Counter-clockwise in the parameters: the loop's outward is the
2945        // surface's normal side; it must face into the lens (towards the
2946        // hole's own axis).
2947        let same_sense = area > 0.0;
2948        let face_id = id();
2949        let loop_id = id();
2950        let face = FaceRecord { id: face_id, surface, same_sense, loops: vec![LoopRecord { id: loop_id, coedges }], name: None };
2951        // Sense check at the wall's middle: towards the hole's axis.
2952        let middle = mid.add(ed.scale(if centre.sub(c0).length() == 0.0 { big - tube - half } else { -(big - tube - half) }));
2953        let q = crate::project_point_to_surface(&face.surface, middle).ok()?;
2954        let n = face.surface.normal(q.u, q.v).ok()?;
2955        let n = if face.same_sense { n } else { n.scale(-1.0) };
2956        let toward_axis = centre.sub(middle);
2957        let toward_axis = toward_axis.sub(w.scale(toward_axis.dot(w)));
2958        if !(n.dot(toward_axis) > 0.0) {
2959            return None;
2960        }
2961        body.shells[0].faces.push(face);
2962    }
2963    // The lens runs through from the top face to the bottom: one handle more.
2964    body.genus = whole.genus + 1;
2965    body.mass_properties_cache = Default::default();
2966    if body.validate().iter().any(|issue| issue.severity == "error") {
2967        return None;
2968    }
2969    Some(body)
2970}
2971
2972/// A ring (or another tool with a hole about its axis walled straight
2973/// through) lying flat to its motion (a turn about an axis parallel to the
2974/// tool's, a slide square to it), if `meridian` is one and the motion such.
2975///
2976/// Every point then moves in its own plane square to the ring's axis, where
2977/// the ring's section is an annulus. The tube passes over where the hole was,
2978/// so the sweep does not pass each point once; but an annulus sweeps what its
2979/// filled disc sweeps as soon as it travels far enough that no point stays in
2980/// the hole from start to end (the hole at the start and at the end share
2981/// nothing: travel beyond the hole's greatest width, the tube's centre
2982/// circle). So the ring sweeps what the FILLED ring sweeps: a tool with a
2983/// half-round rim and flat faces, which is swept whole. A whole turn sweeps
2984/// the solid of revolution of that tool's shadow about the turn's axis.
2985fn flat_ring(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2986    if screw.frame.is_some() || screw.turns.is_some() || screw.c2 != 0.0 {
2987        return Ok(None);
2988    }
2989    let Ok(w) = axis.normalized() else { return Ok(None) };
2990    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 };
2991    if !flat {
2992        return Ok(None);
2993    }
2994    // The holed tool: a torus (`torus`: its tube), or straight-sided pieces
2995    // whose hole is one upright wall from the tool's top to its bottom.
2996    // `big`: half the hole's greatest width. `filled_meridian`: the tool
2997    // with its hole closed, flat across at its top and bottom.
2998    let (big, level, torus, filled_meridian): (f64, f64, Option<f64>, Vec<OutlinePiece>) = match meridian {
2999        [OutlinePiece::Arc { centre, radius, start, end }] => {
3000            let (big, tube, level) = (centre[0], *radius, centre[1]);
3001            if ((end - start).abs() - TAU).abs() >= 1e-12 || big <= tube {
3002                return Ok(None);
3003            }
3004            (
3005                big,
3006                level,
3007                Some(tube),
3008                vec![
3009                    OutlinePiece::Line { from: [0.0, level - tube], to: [big, level - tube] },
3010                    OutlinePiece::Arc { centre: [big, level], radius: tube, start: -0.5 * PI, end: 0.5 * PI },
3011                    OutlinePiece::Line { from: [big, level + tube], to: [0.0, level + tube] },
3012                    OutlinePiece::Line { from: [0.0, level + tube], to: [0.0, level - tube] },
3013                ],
3014            )
3015        }
3016        pieces => {
3017            let mut ends: Vec<([f64; 2], [f64; 2])> = Vec::with_capacity(pieces.len());
3018            for piece in pieces {
3019                let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
3020                ends.push((*from, *to));
3021            }
3022            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);
3023            let inner = ends.iter().flat_map(|(a, b)| [a[0], b[0]]).fold(f64::INFINITY, f64::min);
3024            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)));
3025            if ends.len() < 3 || inner <= 1e-9 * scale {
3026                return Ok(None);
3027            }
3028            let walls: Vec<usize> = (0..ends.len())
3029                .filter(|&k| {
3030                    let (a, b) = ends[k];
3031                    (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
3032                })
3033                .collect();
3034            let [wall] = walls.as_slice() else { return Ok(None) };
3035            let (from, to) = ends[*wall];
3036            // From the wall's end round the outside back to its start, then
3037            // across to the axis and along it.
3038            let mut filled = vec![OutlinePiece::Line { from: [0.0, to[1]], to }];
3039            for k in 1..pieces.len() {
3040                filled.push(pieces[(wall + k) % pieces.len()].clone());
3041            }
3042            filled.push(OutlinePiece::Line { from, to: [0.0, from[1]] });
3043            filled.push(OutlinePiece::Line { from: [0.0, from[1]], to: [0.0, to[1]] });
3044            (inner, 0.5 * (low + high), None, filled)
3045        }
3046    };
3047    let centre0 = origin.add(w.scale(level));
3048    let filled = SolidTool::Revolved { axis_origin: origin, axis_direction: w, radial, meridian: filled_meridian };
3049    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());
3050    if screw.omega == 0.0 {
3051        if screw.c.abs() * (screw.t1 - screw.t0) <= 2.0 * big * (1.0 + 1e-9) {
3052            let Some(tube) = torus else { return Err(short()) };
3053            // Short of its hole: what stays open, all the way through, is the
3054            // lens the hole shares where the ring starts and where it stops.
3055            // The hole at one place: inside the ring's inner half, between
3056            // its top and bottom planes.
3057            let hole = |t: f64| -> Result<BrepSolid, KernelRefusal> {
3058                let o = screw.apply(t, centre0);
3059                let u = frag(radial.sub(w.scale(radial.dot(w))).normalized(), "ring_flat")?;
3060                let at = |rho: f64, z: f64| o.add(u.scale(rho)).add(w.scale(z));
3061                let n = w.cross(u);
3062                let from = at(big, -tube);
3063                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")?;
3064                let profile = [
3065                    frag(make_line(at(0.0, -tube), at(big, -tube)), "ring_flat")?,
3066                    inner,
3067                    frag(make_line(at(big, tube), at(0.0, tube)), "ring_flat")?,
3068                    frag(make_line(at(0.0, tube), at(0.0, -tube)), "ring_flat")?,
3069                ];
3070                frag(crate::revolve_profile_brep(&profile, o, w, TAU), "ring_flat")
3071            };
3072            let (sewn_on, sewn_check) = (ring_lens_sewn_on(), ring_lens_sewn_check_on());
3073            if sewn_on || sewn_check {
3074                let whole = sweep_with(screw, &filled)?;
3075                let c0 = screw.apply(screw.t0, centre0);
3076                let c1 = screw.apply(screw.t1, centre0);
3077                let sewn = sewn_lens(&whole, c0, c1, w, big, tube);
3078                if sewn_check {
3079                    let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3080                    let cut = crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract)?;
3081                    ring_lens_check_record(&cut, sewn.as_ref());
3082                    return Ok(Some(cut));
3083                }
3084                if let Some(body) = sewn {
3085                    return Ok(Some(body));
3086                }
3087            }
3088            let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3089            let whole = sweep_with(screw, &filled)?;
3090            return crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract).map(Some);
3091        }
3092        return sweep_with(screw, &filled).map(Some);
3093    }
3094    // A turn: the ring's centre runs a circle of radius `reach` about the axis.
3095    let start_centre = screw.apply(screw.t0, centre0);
3096    let from_axis = start_centre.sub(screw.a);
3097    let across = from_axis.sub(screw.e.scale(from_axis.dot(screw.e)));
3098    let reach = across.length();
3099    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
3100    if theta >= TAU * (1.0 - 1e-12) {
3101        let Some(tube) = torus else {
3102            return Err(refuse("ring_flat", "a whole turn of a holed tool in its own plane is swept for a ring only".into()));
3103        };
3104        if reach <= (big + tube) * (1.0 + 1e-9) {
3105            return Err(refuse("ring_flat", "a ring turned a whole turn in its own plane reaches the turn's axis".into()));
3106        }
3107        let out = frag(across.normalized(), "ring_flat")?;
3108        let foot = start_centre.sub(across);
3109        let at = |rho: f64, z: f64| foot.add(out.scale(rho)).add(screw.e.scale(z));
3110        let half_round = |centre: Vec3, from: Vec3| -> Result<NurbsCurve, KernelRefusal> {
3111            let n = out.cross(screw.e);
3112            let surface = frag(make_revolution(centre, n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?;
3113            frag(surface.iso_curve_v(0.0), "ring_flat")
3114        };
3115        let profile = [
3116            frag(make_line(at(reach - big, -tube), at(reach + big, -tube)), "ring_flat")?,
3117            half_round(at(reach + big, 0.0), at(reach + big, -tube))?,
3118            frag(make_line(at(reach + big, tube), at(reach - big, tube)), "ring_flat")?,
3119            half_round(at(reach - big, 0.0), at(reach - big, tube))?,
3120        ];
3121        return frag(crate::revolve_profile_brep(&profile, foot, screw.e, TAU), "ring_flat").map(Some);
3122    }
3123    let covered = if theta >= PI { big < reach } else { reach * (0.5 * theta).sin() > big * (1.0 + 1e-9) };
3124    if !covered {
3125        return Err(short());
3126    }
3127    sweep_with(screw, &filled).map(Some)
3128}
3129
3130/// The sweep of `tool` along `motion`, where it lies in `clip` (the caller
3131/// cuts a workpiece inside that region). A TURN about the clip's own axis
3132/// whose two end positions stay outside the clip's wedge covers the wedge
3133/// wholly with the tool's shadow in (ρ, z): that shadow, turned over the wedge,
3134/// is the sweep there (a convex polyhedron's shadow is bounded by conic arcs
3135/// from its edges and straight lines from its faces, so every surface is
3136/// exact); a turn about that axis whose ends reach the wedge is refused. A
3137/// screw or turn about the region's axis whose tool reaches far past the
3138/// region's radius sweeps only the tool's part that can reach it (see
3139/// `trim_to_clip`). Any other motion gets the whole sweep ([`sweep_solid`]).
3140pub fn sweep_solid_clipped(tool: &SolidTool, motion: &SolidMotion, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3141    let screw = Screw::from_motion(motion)?;
3142    if let (SolidTool::Polyhedron { vertices, faces }, Some(wedge)) = (tool, clip.angle) {
3143        let axis = clip.axis_direction.normalized().map_err(|_| input("clip_axis", "the clip's axis has no direction".into()))?;
3144        let same_axis = screw.c == 0.0 && screw.c2 == 0.0
3145            && screw.e.cross(axis).length() < 1e-12
3146            && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3147        if same_axis {
3148            return turn_shadow(&screw, vertices, faces, clip, axis, wedge);
3149        }
3150    }
3151    if let SolidTool::Polyhedron { vertices, faces } = tool {
3152        if let Some((vertices, faces)) = trim_to_clip(&screw, vertices, faces, clip)? {
3153            return sweep_solid(&SolidTool::Polyhedron { vertices, faces }, motion);
3154        }
3155    }
3156    sweep_solid(tool, motion)
3157}
3158
3159/// The sweep of `tool` along a turn whose rise grows as it turns, where it lies
3160/// in `clip` (as [`sweep_solid_clipped`]). Its front and back are those at
3161/// the middle of the motion; a tool whose faces change side along it is refused.
3162pub fn sweep_solid_rising(tool: &SolidTool, motion: &RisingTurn, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3163    let screw = Screw::from_rising(motion)?;
3164    let SolidTool::Polyhedron { vertices, faces } = tool else {
3165        return Err(refuse("rising_tool", "a growing rise sweeps a polyhedron only".into()));
3166    };
3167    let (vertices, faces) = trim_to_clip(&screw, vertices, faces, clip)?.unwrap_or_else(|| (vertices.clone(), faces.clone()));
3168    sweep_with(&screw, &SolidTool::Polyhedron { vertices, faces })
3169}
3170
3171/// The sweep of `tool` along `motion` as parts whose union it is (a caller cuts
3172/// a workpiece by all of them). One part where the whole sweep passes once. A
3173/// convex polyhedron whose sweep folds over itself (a face facing away from a
3174/// screw's or turn's axis grazes along a line inside it, and the faces beyond
3175/// that line are swept over again) is split by the plane through the axis and
3176/// that line: each half grazes that face only along its cut edge, and is swept
3177/// whole. The halves' walls share cylinders about the axis.
3178pub fn sweep_solid_parts(tool: &SolidTool, motion: &SolidMotion) -> Result<Vec<BrepSolid>, KernelRefusal> {
3179    let folded = match sweep_solid(tool, motion) {
3180        Ok(body) => return Ok(vec![body]),
3181        Err(error) if refused_as(&error) == Some("folds") => error,
3182        Err(error) => return Err(error),
3183    };
3184    let SolidTool::Polyhedron { vertices, faces } = tool else { return Err(folded) };
3185    let screw = Screw::from_motion(motion)?;
3186    if screw.omega == 0.0 {
3187        return Err(folded);
3188    }
3189    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);
3190    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3191    for face in faces {
3192        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3193        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3194        if n.dot(p.sub(centroid)) < 0.0 {
3195            n = n.scale(-1.0);
3196        }
3197        planes.push((n, n.dot(p)));
3198    }
3199    // A face square to the axis' plane through it (its normal square to the
3200    // axis) graze along the line through its foot from the axis; it folds if
3201    // it faces away from the axis and that line crosses it.
3202    for (n, d) in planes.clone() {
3203        if n.dot(screw.e).abs() > 1e-12 {
3204            continue;
3205        }
3206        let foot = screw.a.add(n.scale(d - n.dot(screw.a)));
3207        let radial = foot.sub(screw.a).sub(screw.e.scale(foot.sub(screw.a).dot(screw.e)));
3208        if radial.dot(n) <= 0.0 {
3209            continue; // faces the axis: its grazing line is the sweep's inner wall
3210        }
3211        let cut = match screw.e.cross(radial).normalized() {
3212            Ok(m) => m,
3213            Err(_) => continue,
3214        };
3215        let offset = cut.dot(screw.a);
3216        let mut parts = Vec::with_capacity(2);
3217        for sense in [1.0, -1.0] {
3218            let mut half = planes.clone();
3219            half.push((cut.scale(sense), offset * sense));
3220            let (corners, loops) = polyhedron_of_planes(&half)?;
3221            if corners.len() < 4 || loops.len() < 4 {
3222                parts.clear();
3223                break;
3224            }
3225            match sweep_solid(&SolidTool::Polyhedron { vertices: corners, faces: loops }, motion) {
3226                Ok(body) => parts.push(body),
3227                Err(_) => {
3228                    parts.clear();
3229                    break;
3230                }
3231            }
3232        }
3233        if parts.len() == 2 {
3234            return Ok(parts);
3235        }
3236    }
3237    Err(folded)
3238}
3239
3240/// A screw or turn about the clip's axis maps the clip's cylinder (radius
3241/// ≤ R) onto itself, so inside it the sweep of the tool is the sweep of any
3242/// part of the tool holding the tool's part inside the cylinder. A tool
3243/// reaching far past it (a bar pointing at the axis) is replaced by its part
3244/// inside the prism over the shadow's piece of a slightly larger disc, with
3245/// that disc's arc replaced by the two tangents at its ends: those faces graze
3246/// only along their own end edges, where the far ends of a long tool would
3247/// fold the sweep over itself. None when the tool needs no trim.
3248fn trim_to_clip(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip) -> Result<Option<(Vec<Vec3>, Vec<Vec<usize>>)>, KernelRefusal> {
3249    let Ok(axis) = clip.axis_direction.normalized() else { return Ok(None) };
3250    let same_axis = screw.omega != 0.0
3251        && screw.e.cross(axis).length() < 1e-12
3252        && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3253    if !same_axis || !clip.radius[1].is_finite() {
3254        return Ok(None);
3255    }
3256    let ez = axis;
3257    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))?;
3258    let ey = ez.cross(ex);
3259    let flat = |p: Vec3| {
3260        let r = p.sub(clip.axis_origin);
3261        [r.dot(ex), r.dot(ey)]
3262    };
3263    let radius = clip.radius[1] * 1.02;
3264    let shadow: Vec<[f64; 2]> = vertices.iter().map(|&p| flat(p)).collect();
3265    if shadow.iter().all(|q| q[0].hypot(q[1]) <= radius) {
3266        return Ok(None);
3267    }
3268    // The shadow's convex hull, counter-clockwise.
3269    let mut points = shadow.clone();
3270    points.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
3271    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]);
3272    let mut hull: Vec<[f64; 2]> = Vec::new();
3273    for pass in 0..2 {
3274        let start = hull.len();
3275        let ordered: Vec<[f64; 2]> = if pass == 0 { points.clone() } else { points.iter().rev().copied().collect() };
3276        for p in ordered {
3277            while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
3278                hull.pop();
3279            }
3280            hull.push(p);
3281        }
3282        hull.pop();
3283    }
3284    // Where the hull's boundary leaves and re-enters the disc.
3285    let m = hull.len();
3286    let inside = |q: [f64; 2]| q[0].hypot(q[1]) <= radius;
3287    // Leave a tool that does not reach the disc, or wraps the axis.
3288    let mut nearest = f64::INFINITY;
3289    let mut wraps = true;
3290    for k in 0..m {
3291        let (a, b) = (hull[k], hull[(k + 1) % m]);
3292        let d = [b[0] - a[0], b[1] - a[1]];
3293        let t = (-(a[0] * d[0] + a[1] * d[1]) / (d[0] * d[0] + d[1] * d[1])).clamp(0.0, 1.0);
3294        nearest = nearest.min((a[0] + d[0] * t).hypot(a[1] + d[1] * t));
3295        if cross(a, b, [0.0, 0.0]) < 0.0 {
3296            wraps = false;
3297        }
3298    }
3299    if wraps || nearest >= radius || (0..m).all(|k| inside(hull[k])) {
3300        return Ok(None);
3301    }
3302    let mut leave: Vec<f64> = Vec::new();
3303    let mut enter: Vec<f64> = Vec::new();
3304    for k in 0..m {
3305        let (a, b) = (hull[k], hull[(k + 1) % m]);
3306        let d = [b[0] - a[0], b[1] - a[1]];
3307        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);
3308        let disc = qb * qb - 4.0 * qa * qc;
3309        if disc <= 0.0 {
3310            continue;
3311        }
3312        for t in [(-qb - disc.sqrt()) / (2.0 * qa), (-qb + disc.sqrt()) / (2.0 * qa)] {
3313            if t > 0.0 && t < 1.0 {
3314                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3315                let outward = 2.0 * (q[0] * d[0] + q[1] * d[1]) > 0.0;
3316                (if outward { &mut leave } else { &mut enter }).push(q[1].atan2(q[0]));
3317            }
3318        }
3319    }
3320    let ([a], [b]) = (leave.as_slice(), enter.as_slice()) else {
3321        return Err(refuse("clip_trim", "the tool's shadow leaves the clip's disc more than once".into()));
3322    };
3323    let width = (b - a).rem_euclid(TAU);
3324    if width >= 0.9 * PI {
3325        return Err(refuse("clip_trim", "the tool's shadow spans too much of the clip's circle to be trimmed".into()));
3326    }
3327    // Planes of the tool, and the two tangents (outward normals in the plane).
3328    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3329    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);
3330    for face in faces {
3331        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3332        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3333        if n.dot(p.sub(centroid)) < 0.0 {
3334            n = n.scale(-1.0);
3335        }
3336        planes.push((n, n.dot(p)));
3337    }
3338    for angle in [*a, *b] {
3339        let n = ex.scale(angle.cos()).add(ey.scale(angle.sin()));
3340        planes.push((n, n.dot(clip.axis_origin) + radius));
3341    }
3342    Ok(Some(polyhedron_of_planes(&planes)?))
3343}
3344
3345/// `BREP_SWEEP_SLID_POLYHEDRON_HULL` (default on; `=0` restores the refusal): a convex polyhedron slid
3346/// straight sweeps exactly the convex hull of its two end positions (every
3347/// point between is on a segment from one to the other), so the sweep is that
3348/// hull. The grazing split refused a face the slide moves in its own plane (a
3349/// block slid along one of its faces: the face's sweep is flat).
3350fn slid_hull_on() -> bool {
3351    crate::switch!("BREP_SWEEP_SLID_POLYHEDRON_HULL", true)
3352}
3353
3354/// The convex hull of the polyhedron at the screw's two ends, the screw being a
3355/// straight slide. The polyhedron must be the convex one its faces bound (the
3356/// hull of a concave tool is not its sweep), so its faces are read first: each
3357/// flat, the set closed, and every corner on the inner side of every face.
3358fn slid_polyhedron_hull(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3359    if vertices.len() < 4 || faces.len() < 4 || vertices.len() > 256 {
3360        return Err(input("polyhedron", "the tool needs at least four corners and four faces (and at most 256 corners)".into()));
3361    }
3362    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);
3363    let extent = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max);
3364    if !(extent > 0.0) {
3365        return Err(input("polyhedron", "the tool's corners coincide".into()));
3366    }
3367    let slack = 1e-9 * extent;
3368    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
3369    // Either winding is a face's (as the grazing split reads it): each is
3370    // turned to run counter-clockwise from outside before the faces are read.
3371    let mut oriented: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
3372    let mut normals: Vec<Vec3> = Vec::with_capacity(faces.len());
3373    for (index, face) in faces.iter().enumerate() {
3374        if face.len() < 3 || face.iter().any(|&k| k >= vertices.len()) {
3375            return Err(input("face", format!("face {index} names fewer than three corners or one past the tool's")));
3376        }
3377        // Newell's normal, then outward by the centroid.
3378        let mut normal = Vec3::new(0.0, 0.0, 0.0);
3379        for k in 0..face.len() {
3380            let (a, b) = (vertices[face[k]].sub(centroid), vertices[face[(k + 1) % face.len()]].sub(centroid));
3381            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)));
3382        }
3383        // Against the tool's own size, not an absolute floor.
3384        let length = normal.length();
3385        if !(length > 1e-18 * extent * extent) {
3386            return Err(input("face", format!("face {index} has no area")));
3387        }
3388        let mut normal = normal.scale(1.0 / length);
3389        let mut face = face.clone();
3390        let d = normal.dot(vertices[face[0]].sub(centroid));
3391        let d = if d < 0.0 {
3392            normal = normal.scale(-1.0);
3393            face.reverse();
3394            -d
3395        } else {
3396            d
3397        };
3398        for &k in &face {
3399            if (normal.dot(vertices[k].sub(centroid)) - d).abs() > slack {
3400                return Err(input("face", format!("face {index}'s corners are not in one plane")));
3401            }
3402        }
3403        if vertices.iter().any(|p| normal.dot(p.sub(centroid)) - d > slack) {
3404            return Err(input("convex", "the tool is not convex: a corner lies outside one of its faces".into()));
3405        }
3406        for k in 0..face.len() {
3407            let (a, b) = (face[k], face[(k + 1) % face.len()]);
3408            if owner.insert((a, b), index).is_some() {
3409                return Err(input("closed", "an edge is used more than once the same way".into()));
3410            }
3411        }
3412        oriented.push(face);
3413        normals.push(normal);
3414    }
3415    for &(a, b) in owner.keys() {
3416        if !owner.contains_key(&(b, a)) {
3417            return Err(input("closed", "the polyhedron's faces do not close".into()));
3418        }
3419    }
3420    // The faces must bound one closed part (the polyhedron builder's own
3421    // reading: faces given twice, once each way, close into separate parts).
3422    crate::make_polyhedron_brep(vertices, &oriented)?;
3423    // The sweep is the tool's Minkowski sum with the slide [0, s]: faces it
3424    // leaves behind at the start (n · s < 0), faces it leads with at the end
3425    // (n · s > 0), faces it slides in their own plane stretched to the hull of
3426    // their two copies, and one parallelogram per edge where the faces either
3427    // side face opposite ways. Built from the tool's own faces, no plane is
3428    // searched for and no tolerance grows with the slide.
3429    let n = vertices.len();
3430    let start: Vec<Vec3> = vertices.iter().map(|&p| screw.apply(screw.t0, p)).collect();
3431    let end: Vec<Vec3> = vertices.iter().map(|&p| screw.apply(screw.t1, p)).collect();
3432    let slide = end[0].sub(start[0]);
3433    let travel = slide.length();
3434    if !(travel > 0.0 && travel.is_finite()) {
3435        return Err(input("still", "the slide does not move".into()));
3436    }
3437    let along = slide.scale(1.0 / travel);
3438    // The polyhedron builder reads its faces against its whole extent, so a
3439    // slide far longer than the tool's thinnest width is beyond what it
3440    // builds (that width: the least spread of the corners along a face's
3441    // normal).
3442    let width = normals.iter().map(|nf| {
3443        let reach: Vec<f64> = vertices.iter().map(|p| nf.dot(*p)).collect();
3444        reach.iter().copied().fold(f64::NEG_INFINITY, f64::max) - reach.iter().copied().fold(f64::INFINITY, f64::min)
3445    }).fold(f64::INFINITY, f64::min);
3446    if slide.length() > 1e6 * width {
3447        return Err(refuse("slid_hull", format!("the slide ({:.3e}) is more than 1e6 times the tool's thinnest width ({width:.3e})", slide.length())));
3448    }
3449    let side: Vec<i8> = normals.iter().map(|nf| {
3450        let c = nf.dot(along);
3451        if c.abs() <= 1e-12 { 0 } else if c > 0.0 { 1 } else { -1 }
3452    }).collect();
3453    let corners: Vec<Vec3> = start.iter().chain(end.iter()).copied().collect();
3454    // A corner the slide carries onto another (a block slid by its own width)
3455    // is one corner: every index is read as its first coincident one.
3456    let canonical: Vec<usize> = (0..corners.len())
3457        .map(|k| (0..k).find(|&j| corners[j].sub(corners[k]).length() <= slack).unwrap_or(k))
3458        .collect();
3459    let mut pool: Vec<usize> = canonical.clone();
3460    pool.sort_unstable();
3461    pool.dedup();
3462    let canon = |set: Vec<usize>| -> Vec<usize> {
3463        let mut out: Vec<usize> = set.into_iter().map(|k| canonical[k]).collect();
3464        out.sort_unstable();
3465        out.dedup();
3466        out
3467    };
3468    // A ring of corner indices, ordered as the convex hull of its points
3469    // counter-clockwise about `normal` (corners inside it or on its sides
3470    // dropped).
3471    let ring = |set: &[usize], normal: Vec3| -> Option<Vec<usize>> {
3472        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);
3473        // The longest offset in the plane, divided by its own length (no
3474        // absolute floor: a small face is as good as a large one).
3475        let u = set
3476            .iter()
3477            .map(|&k| corners[k].sub(middle))
3478            .map(|r| r.sub(normal.scale(r.dot(normal))))
3479            .max_by(|a, b| a.length().total_cmp(&b.length()))?;
3480        let u = (u.length() > 0.0).then(|| u.scale(1.0 / u.length()))?;
3481        let v = normal.cross(u);
3482        let flat = |k: usize| {
3483            let r = corners[k].sub(middle);
3484            (r.dot(u), r.dot(v))
3485        };
3486        let mut order = set.to_vec();
3487        order.sort_by(|&a, &b| {
3488            let (pa, pb) = (flat(a), flat(b));
3489            pa.0.total_cmp(&pb.0).then(pa.1.total_cmp(&pb.1))
3490        });
3491        // A point is on the line through two others when it stands off it by
3492        // no more than the tool's tolerance (a distance, whatever the slide's
3493        // length): twice the triangle's area over the base.
3494        let left = |o: usize, a: usize, b: usize| {
3495            let (po, pa, pb) = (flat(o), flat(a), flat(b));
3496            let cross = (pa.0 - po.0) * (pb.1 - po.1) - (pa.1 - po.1) * (pb.0 - po.0);
3497            cross > slack * (pb.0 - po.0).hypot(pb.1 - po.1)
3498        };
3499        let mut hull: Vec<usize> = Vec::new();
3500        for pass in [false, true] {
3501            let begin = hull.len();
3502            let sequence: Vec<usize> = if pass { order.iter().rev().copied().collect() } else { order.clone() };
3503            for k in sequence {
3504                while hull.len() >= begin + 2 && !left(hull[hull.len() - 2], hull[hull.len() - 1], k) {
3505                    hull.pop();
3506                }
3507                hull.push(k);
3508            }
3509            hull.pop();
3510        }
3511        if hull.len() < 3 {
3512            return None;
3513        }
3514        // Every corner of the sweep on a side of this ring stays on it, in
3515        // order: whichever face it came from, the neighbour across that side
3516        // reads the same corners there, so the two rings carry the same edges.
3517        let mut out: Vec<usize> = Vec::with_capacity(set.len());
3518        for k in 0..hull.len() {
3519            let (p, q) = (hull[k], hull[(k + 1) % hull.len()]);
3520            out.push(p);
3521            let (a, d) = (corners[p], corners[q].sub(corners[p]));
3522            let length = d.length();
3523            let mut between: Vec<(f64, usize)> = pool
3524                .iter()
3525                .filter(|&&m| m != p && m != q)
3526                .filter_map(|&m| {
3527                    let r = corners[m].sub(a);
3528                    let t = r.dot(d) / (length * length);
3529                    let off = r.sub(d.scale(t)).length();
3530                    (t > 0.0 && t < 1.0 && off <= slack).then_some((t, m))
3531                })
3532                .collect();
3533            between.sort_by(|x, y| x.0.total_cmp(&y.0));
3534            out.extend(between.into_iter().map(|(_, m)| m));
3535        }
3536        Some(out)
3537    };
3538    // Coplanar faces of a convex polyhedron are one face of it: grouped by
3539    // plane, each group read as one (the union of its corners).
3540    let offsets: Vec<f64> = oriented.iter().zip(&normals).map(|(face, nf)| nf.dot(vertices[face[0]].sub(centroid))).collect();
3541    let mut group = vec![usize::MAX; oriented.len()];
3542    let mut groups: Vec<Vec<usize>> = Vec::new();
3543    for f in 0..oriented.len() {
3544        if group[f] != usize::MAX {
3545            continue;
3546        }
3547        group[f] = groups.len();
3548        let mut members = vec![f];
3549        for g in f + 1..oriented.len() {
3550            // One face only if the slide reads them alike too: two faces a
3551            // hair apart in angle can face it opposite ways, and then their
3552            // shared edge is a silhouette of its own.
3553            if group[g] == usize::MAX && side[g] == side[f] && normals[g].sub(normals[f]).length() <= 1e-9 && (offsets[g] - offsets[f]).abs() <= slack {
3554                group[g] = groups.len();
3555                members.push(g);
3556            }
3557        }
3558        groups.push(members);
3559    }
3560    let mut hull_faces: Vec<Vec<usize>> = Vec::new();
3561    for (index, members) in groups.iter().enumerate() {
3562        let f = members[0];
3563        let mut corners_of: Vec<usize> = members.iter().flat_map(|&m| oriented[m].iter().copied()).collect();
3564        corners_of.sort_unstable();
3565        corners_of.dedup();
3566        let set: Vec<usize> = canon(match side[f] {
3567            -1 => corners_of,
3568            1 => corners_of.iter().map(|&k| k + n).collect(),
3569            _ => corners_of.iter().flat_map(|&k| [k, k + n]).collect(),
3570        });
3571        hull_faces.push(ring(&set, normals[f]).ok_or_else(|| refuse("slid_hull", format!("face group {index}'s sweep has no area")))?);
3572    }
3573    // In a fixed order, so the same tool builds the same body.
3574    let mut edges: Vec<(usize, usize)> = owner.keys().copied().filter(|&(a, b)| a < b).collect();
3575    edges.sort_unstable();
3576    for (a, b) in edges {
3577        let (f, g) = (owner[&(a, b)], owner[&(b, a)]);
3578        // Once per edge between two faces of the hull's own (not two
3579        // coplanar pieces of one), where the face on its left leads and the
3580        // one on its right trails (or the other way): the edge's own sweep is
3581        // a face.
3582        if group[f] != group[g] && side[f] * side[g] < 0 {
3583            let edge = start[b].sub(start[a]);
3584            // Against the edge's own length (an edge of a silhouette is never
3585            // along the slide: its faces would both slide in their planes).
3586            let cross = edge.cross(along);
3587            let length = cross.length();
3588            if !(length > 1e-12 * edge.length()) {
3589                return Err(refuse("slid_hull", "a silhouette edge runs along the slide".into()));
3590            }
3591            let mut normal = cross.scale(1.0 / length);
3592            if normal.dot(start[a].sub(centroid)) < 0.0 {
3593                normal = normal.scale(-1.0);
3594            }
3595            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()))?);
3596        }
3597    }
3598    crate::make_polyhedron_brep(&corners, &hull_faces)
3599}
3600
3601/// The convex polyhedron {n · p ≤ d for every plane}: its corners (where three
3602/// planes meet inside all) and a face per plane that bounds it.
3603pub fn polyhedron_of_planes(planes: &[(Vec3, f64)]) -> Result<(Vec<Vec3>, Vec<Vec<usize>>), KernelRefusal> {
3604    let k = planes.len();
3605    let mut corners: Vec<Vec3> = Vec::new();
3606    let scale = planes.iter().map(|p| p.1.abs()).fold(1.0f64, f64::max);
3607    for i in 0..k {
3608        for j in i + 1..k {
3609            for l in j + 1..k {
3610                let (a, b, c) = (planes[i].0, planes[j].0, planes[l].0);
3611                let det = a.dot(b.cross(c));
3612                if det.abs() < 1e-12 {
3613                    continue;
3614                }
3615                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);
3616                if planes.iter().all(|(n, d)| n.dot(p) - d <= 1e-9 * scale) && !corners.iter().any(|q| q.sub(p).length() <= 1e-9 * scale) {
3617                    corners.push(p);
3618                }
3619            }
3620        }
3621    }
3622    let mut faces = Vec::new();
3623    for (n, d) in planes {
3624        let on: Vec<usize> = (0..corners.len()).filter(|&c| (n.dot(corners[c]) - d).abs() <= 1e-9 * scale).collect();
3625        if on.len() < 3 {
3626            continue;
3627        }
3628        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);
3629        let u = frag(corners[on[0]].sub(middle).normalized(), "face_axis")?;
3630        let v = n.cross(u);
3631        let mut ordered = on.clone();
3632        ordered.sort_by(|&p, &q| {
3633            let (rp, rq) = (corners[p].sub(middle), corners[q].sub(middle));
3634            rp.dot(v).atan2(rp.dot(u)).total_cmp(&rq.dot(v).atan2(rq.dot(u)))
3635        });
3636        faces.push(ordered);
3637    }
3638    Ok((corners, faces))
3639}
3640
3641fn turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip, axis: Vec3, wedge: [f64; 2]) -> Result<BrepSolid, KernelRefusal> {
3642    let ez = axis;
3643    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()))?;
3644    let ey = ez.cross(ex);
3645    // Turning by ω t about e = ±ez moves angles about ez by ±ω t.
3646    let rate = screw.omega * screw.e.dot(ez).signum();
3647    let local = |p: Vec3| {
3648        let r = p.sub(clip.axis_origin);
3649        [r.dot(ex), r.dot(ey), r.dot(ez)]
3650    };
3651    let corners: Vec<[f64; 3]> = vertices.iter().map(|&p| local(p)).collect();
3652    // The tool's angular extent about the axis (its corners'; the tool must
3653    // keep off the axis, so its shadow on the plane misses the origin).
3654    let mid = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
3655    let mid_angle = mid[1].atan2(mid[0]);
3656    let angles: Vec<f64> = corners.iter().map(|c| mid_angle + (c[1].atan2(c[0]) - mid_angle + PI).rem_euclid(TAU) - PI).collect();
3657    let (low, high) = (angles.iter().copied().fold(f64::INFINITY, f64::min), angles.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3658    if high - low >= PI {
3659        return Err(refuse("turn_shadow", "the tool reaches round the turn's axis".into()));
3660    }
3661    let (start, end) = (rate * screw.t0, rate * screw.t1);
3662    let (first, last) = if rate > 0.0 { (start, end) } else { (end, start) };
3663    let reference = 0.5 * (wedge[0] + wedge[1]);
3664    let near = |a: f64| reference + (a - reference + PI).rem_euclid(TAU) - PI;
3665    // Before the wedge at one end, after it at the other (angles taken near the wedge).
3666    let clear = near(high + first) < wedge[0] - 1e-9 && near(low + last) > wedge[1] + 1e-9 && (last - first) < TAU;
3667    if !clear {
3668        return Err(refuse("turn_shadow", "the turned tool's ends reach the clip's wedge; its sweep there is not its turned shadow".into()));
3669    }
3670    let profile = polyhedron_shadow(&corners, faces, false)?;
3671    // The profile in the half-plane at the wedge's start angle.
3672    let (c0, s0) = (wedge[0].cos(), wedge[0].sin());
3673    let world = |rho: f64, z: f64| clip.axis_origin.add(ez.scale(z)).add(ex.scale(rho * c0)).add(ey.scale(rho * s0));
3674    let mut curves = Vec::with_capacity(profile.len());
3675    for piece in &profile {
3676        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3677        let curve = if points.len() == 2 {
3678            frag(make_line(frag(points[0].point(), "point")?, frag(points[1].point(), "point")?), "line")?
3679        } else {
3680            frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")?
3681        };
3682        curves.push(curve);
3683    }
3684    frag(crate::revolve_profile_brep(&curves, clip.axis_origin, ez, wedge[1] - wedge[0]), "turn_shadow")
3685}
3686
3687/// A convex polyhedron turned a whole turn (no advance): the solid of
3688/// revolution of its shadow {(ρ, z)} about the turn's axis, which may pass
3689/// through it. Its corners' paths bound it only where an edge is farthest
3690/// from the axis; an edge skew to the axis turns a hyperboloid.
3691fn whole_turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3692    let ez = screw.e;
3693    let ex = frag(ez.perpendicular(), "turn_shadow")?;
3694    let ex = frag(ex.sub(ez.scale(ex.dot(ez))).normalized(), "turn_shadow")?;
3695    let ey = ez.cross(ex);
3696    let corners: Vec<[f64; 3]> = vertices
3697        .iter()
3698        .map(|&p| {
3699            let r = screw.apply(screw.t0, p).sub(screw.a);
3700            [r.dot(ex), r.dot(ey), r.dot(ez)]
3701        })
3702        .collect();
3703    let profile = polyhedron_shadow(&corners, faces, true)?;
3704    // A point of the outline on the axis to round-off is on it.
3705    let reach = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(0.0f64, f64::max);
3706    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 }));
3707    let mut curves = Vec::with_capacity(profile.len());
3708    // The outline's stretch along the axis, as one edge (it comes a piece per
3709    // corner height).
3710    let on_axis = |piece: &ShadowPiece| piece.iter().all(|&(rho, _, _)| rho.abs() <= 1e-10 * reach);
3711    let mut along: Option<(f64, f64)> = None;
3712    for piece in &profile {
3713        if on_axis(piece) {
3714            let (za, zb) = (piece[0].1, piece[piece.len() - 1].1);
3715            along = Some(match along {
3716                Some((from, _)) => (from, zb),
3717                None => (za, zb),
3718            });
3719            continue;
3720        }
3721        if let Some((from, to)) = along.take() {
3722            curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3723        }
3724        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3725        let (first, last) = (frag(points[0].point(), "point")?, frag(points[points.len() - 1].point(), "point")?);
3726        if first.sub(last).length() <= 1e-12 * (1.0 + first.length()) {
3727            continue;
3728        }
3729        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")? };
3730        curves.push(curve);
3731    }
3732    if let Some((from, to)) = along.take() {
3733        curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3734    }
3735    frag(crate::revolve_profile_brep(&curves, screw.a, ez, TAU), "turn_shadow")
3736}
3737
3738/// One piece of the shadow's outline: a segment (two points) or a rational
3739/// quadratic arc (three, the middle with its weight), as (ρ, z, weight).
3740type ShadowPiece = Vec<(f64, f64, f64)>;
3741
3742/// The shadow {(ρ, z)} of a convex polyhedron (corners in the axis frame):
3743/// at each z its section is a convex polygon, the ρ it reaches an interval
3744/// from the section's nearest point to its farthest corner. The farthest is
3745/// always on an edge (ρ² = quadratic in z: a conic arc); the nearest is on a
3746/// face (ρ linear in z: a segment) or an edge.
3747///
3748/// `through`: the axis may pass through the tool (its nearest ρ is then 0 and
3749/// the outline runs along the axis there); refused otherwise.
3750fn polyhedron_shadow(corners: &[[f64; 3]], faces: &[Vec<usize>], through: bool) -> Result<Vec<ShadowPiece>, KernelRefusal> {
3751    let zs: Vec<f64> = corners.iter().map(|c| c[2]).collect();
3752    let (z_low, z_high) = (zs.iter().copied().fold(f64::INFINITY, f64::min), zs.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3753    let scale = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(1.0f64, f64::max);
3754    // The hull's edges (from the faces' loops) and the faces beside each.
3755    let mut edge_faces: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
3756    for (f, face) in faces.iter().enumerate() {
3757        for k in 0..face.len() {
3758            let (i, j) = (face[k], face[(k + 1) % face.len()]);
3759            edge_faces.entry((i.min(j), i.max(j))).or_default().push(f);
3760        }
3761    }
3762    let mut edges: Vec<(usize, usize)> = edge_faces.keys().copied().collect();
3763    edges.sort_unstable();
3764    // Each face's plane in the axis frame: n · p = d.
3765    let planes: Vec<([f64; 3], f64)> = faces
3766        .iter()
3767        .map(|face| {
3768            let (a, b, c) = (corners[face[0]], corners[face[1]], corners[face[2]]);
3769            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]]);
3770            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]];
3771            (n, n[0] * a[0] + n[1] * a[1] + n[2] * a[2])
3772        })
3773        .collect();
3774    #[derive(Clone, Copy, PartialEq, Debug)]
3775    enum Source {
3776        /// The crossing of edge k.
3777        Edge(usize),
3778        /// The nearest point of face f's section line.
3779        Face(usize),
3780        /// The axis itself, where it passes through the tool.
3781        Axis,
3782    }
3783    let edge_at = |k: usize, z: f64| -> [f64; 2] {
3784        let (a, b) = (corners[edges[k].0], corners[edges[k].1]);
3785        let t = (z - a[2]) / (b[2] - a[2]);
3786        [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
3787    };
3788    let crossing = |z: f64| -> Vec<usize> {
3789        (0..edges.len()).filter(|&k| (corners[edges[k].0][2] - z) * (corners[edges[k].1][2] - z) < 0.0).collect()
3790    };
3791    let farthest = |z: f64| -> (Source, f64) {
3792        let mut best = (Source::Edge(0), f64::NEG_INFINITY);
3793        for k in crossing(z) {
3794            let p = edge_at(k, z);
3795            let r = p[0].hypot(p[1]);
3796            if r > best.1 {
3797                best = (Source::Edge(k), r);
3798            }
3799        }
3800        best
3801    };
3802    // The section polygon: edge crossings ordered by angle about their mean.
3803    let nearest = |z: f64| -> Result<(Source, f64), KernelRefusal> {
3804        let list = crossing(z);
3805        let points: Vec<[f64; 2]> = list.iter().map(|&k| edge_at(k, z)).collect();
3806        let m = points.len();
3807        if m < 3 {
3808            return Err(refuse("turn_shadow", "a section of the tool is not a polygon".into()));
3809        }
3810        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]);
3811        let mut order: Vec<usize> = (0..m).collect();
3812        order.sort_by(|&a, &b| {
3813            let (pa, pb) = (points[a], points[b]);
3814            (pa[1] - centre[1]).atan2(pa[0] - centre[0]).total_cmp(&(pb[1] - centre[1]).atan2(pb[0] - centre[0]))
3815        });
3816        let mut inside = true;
3817        let mut best = (Source::Edge(0), f64::INFINITY);
3818        for k in 0..m {
3819            let (ia, ib) = (order[k], order[(k + 1) % m]);
3820            let (a, b) = (points[ia], points[ib]);
3821            let d = [b[0] - a[0], b[1] - a[1]];
3822            if d[0] * (0.0 - a[1]) - d[1] * (0.0 - a[0]) < 0.0 {
3823                inside = false;
3824            }
3825            let length2 = d[0] * d[0] + d[1] * d[1];
3826            let t = -(a[0] * d[0] + a[1] * d[1]) / length2;
3827            let (source, r) = if t > 0.0 && t < 1.0 {
3828                let (ea, eb) = (edges[list[ia]], edges[list[ib]]);
3829                let shared = edge_faces[&ea].iter().find(|f| edge_faces[&eb].contains(f)).copied();
3830                let Some(face) = shared else {
3831                    return Err(refuse("turn_shadow", "a section side does not lie on one face".into()));
3832                };
3833                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3834                (Source::Face(face), q[0].hypot(q[1]))
3835            } else {
3836                let q = if t <= 0.0 { a } else { b };
3837                (Source::Edge(list[if t <= 0.0 { ia } else { ib }]), q[0].hypot(q[1]))
3838            };
3839            if r < best.1 {
3840                best = (source, r);
3841            }
3842        }
3843        if inside {
3844            if !through {
3845                return Err(refuse("turn_shadow", "the turn's axis passes through the tool".into()));
3846            }
3847            return Ok((Source::Axis, 0.0));
3848        }
3849        Ok(best)
3850    };
3851    // ρ of a source at z, from its own geometry (smooth across the piece).
3852    let value = |source: Source, z: f64| -> f64 {
3853        match source {
3854            Source::Edge(k) => {
3855                let p = edge_at(k, z);
3856                p[0].hypot(p[1])
3857            }
3858            Source::Face(f) => {
3859                let (n, d) = planes[f];
3860                (d - n[2] * z).abs() / n[0].hypot(n[1])
3861            }
3862            Source::Axis => 0.0,
3863        }
3864    };
3865    // Breaks: corner heights, and where the farthest or nearest source changes.
3866    let mut heights: Vec<f64> = zs.clone();
3867    heights.sort_by(|a, b| a.total_cmp(b));
3868    heights.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * scale);
3869    let mut pieces_far: Vec<(f64, f64, Source)> = Vec::new();
3870    let mut pieces_near: Vec<(f64, f64, Source)> = Vec::new();
3871    for window in heights.windows(2) {
3872        let (za, zb) = (window[0], window[1]);
3873        let samples = 400;
3874        let inner = |k: usize| za + (zb - za) * (k as f64 + 0.5) / samples as f64;
3875        for near in [false, true] {
3876            let source_at = |z: f64| -> Result<Source, KernelRefusal> { Ok(if near { nearest(z)?.0 } else { farthest(z).0 }) };
3877            let mut runs: Vec<(f64, Source)> = vec![(za, source_at(inner(0))?)];
3878            for k in 1..samples {
3879                let (z0, z1) = (inner(k - 1), inner(k));
3880                let (s0, s1) = (source_at(z0)?, source_at(z1)?);
3881                // Two sources tied over the stretch (edges equally far from
3882                // the axis) are one piece of the outline.
3883                let tied = [z0, 0.5 * (z0 + z1), z1].iter().all(|&z| (value(s0, z) - value(s1, z)).abs() <= 1e-12 * scale);
3884                if s0 == s1 || tied {
3885                    continue;
3886                }
3887                // Where the source changes, by bisection (a side handing over
3888                // to its corner touches it, so their values do not cross).
3889                let (mut lo, mut hi) = (z0, z1);
3890                for _ in 0..200 {
3891                    let midz = 0.5 * (lo + hi);
3892                    if source_at(midz)? == s0 { lo = midz } else { hi = midz }
3893                }
3894                runs.push((0.5 * (lo + hi), s1));
3895            }
3896            let list = if near { &mut pieces_near } else { &mut pieces_far };
3897            for k in 0..runs.len() {
3898                let z_end = if k + 1 < runs.len() { runs[k + 1].0 } else { zb };
3899                list.push((runs[k].0, z_end, runs[k].1));
3900            }
3901        }
3902    }
3903    // Exact pieces: a pair's ρ(z) is a conic arc, a side's a segment.
3904    let piece = |source: Source, za: f64, zb: f64| -> Vec<ShadowPiece> {
3905        let (ra, rb) = (value(source, za), value(source, zb));
3906        if matches!(source, Source::Face(..) | Source::Axis) {
3907            return vec![vec![(ra, za, 1.0), (rb, zb, 1.0)]];
3908        }
3909        // ρ² = α z² + β z + γ; split so each arc turns little.
3910        let rho = |z: f64| value(source, z);
3911        // Differences kept inside the piece (an edge through the axis has a
3912        // corner in ρ at its end there).
3913        let (z_min, z_max) = (za.min(zb), za.max(zb));
3914        let slope = |z: f64| {
3915            let h = 1e-6 * (zb - za).abs().max(1e-300);
3916            let (zp, zm) = ((z + h).min(z_max), (z - h).max(z_min));
3917            (rho(zp) - rho(zm)) / (zp - zm)
3918        };
3919        let parts = 4;
3920        let mut out = Vec::new();
3921        for k in 0..parts {
3922            let (z0, z1) = (za + (zb - za) * k as f64 / parts as f64, za + (zb - za) * (k + 1) as f64 / parts as f64);
3923            let (a, b) = ((rho(z0), z0), (rho(z1), z1));
3924            // Straight (an edge meeting the axis): a segment.
3925            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);
3926            if bend <= 1e-12 * scale {
3927                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3928                continue;
3929            }
3930            let (ta, tb) = ((slope(z0), 1.0), (slope(z1), 1.0));
3931            // Tangent lines' intersection.
3932            let det = ta.0 * (-tb.1) - ta.1 * (-tb.0);
3933            if det.abs() < 1e-12 {
3934                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3935                continue;
3936            }
3937            let rhs = (b.0 - a.0, b.1 - a.1);
3938            let s = (rhs.0 * (-tb.1) - rhs.1 * (-tb.0)) / det;
3939            let c = (a.0 + ta.0 * s, a.1 + ta.1 * s);
3940            // Shoulder: the conic's point on the line from the chord's middle to c.
3941            let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
3942            let on = |u: f64| {
3943                let p = (m.0 + (c.0 - m.0) * u, m.1 + (c.1 - m.1) * u);
3944                p.0 - rho(p.1)
3945            };
3946            let (mut lo, mut hi) = (0.0, 1.0);
3947            let sign_lo = on(lo);
3948            for _ in 0..200 {
3949                let mid = 0.5 * (lo + hi);
3950                if (on(mid) > 0.0) == (sign_lo > 0.0) { lo = mid } else { hi = mid }
3951            }
3952            let u = 0.5 * (lo + hi);
3953            let weight = u / (1.0 - u);
3954            out.push(vec![(a.0, a.1, 1.0), (c.0, c.1, weight), (b.0, b.1, 1.0)]);
3955        }
3956        out
3957    };
3958    // Outline: up the near side, across the top, down the far side, across the bottom.
3959    let mut outline: Vec<ShadowPiece> = Vec::new();
3960    for &(za, zb, source) in &pieces_near {
3961        outline.extend(piece(source, za, zb));
3962    }
3963    let (near_top, far_top) = (value(pieces_near.last().expect("near").2, z_high), value(pieces_far.last().expect("far").2, z_high));
3964    if far_top - near_top > 1e-12 * scale {
3965        outline.push(vec![(near_top, z_high, 1.0), (far_top, z_high, 1.0)]);
3966    }
3967    for &(za, zb, source) in pieces_far.iter().rev() {
3968        for mut arc in piece(source, za, zb).into_iter().rev() {
3969            arc.reverse();
3970            outline.push(arc);
3971        }
3972    }
3973    let (near_bottom, far_bottom) = (value(pieces_near[0].2, z_low), value(pieces_far[0].2, z_low));
3974    if far_bottom - near_bottom > 1e-12 * scale {
3975        outline.push(vec![(far_bottom, z_low, 1.0), (near_bottom, z_low, 1.0)]);
3976    }
3977    // Snap consecutive ends together.
3978    for k in 0..outline.len() {
3979        let next = (k + 1) % outline.len();
3980        let end = *outline[k].last().expect("piece");
3981        outline[next][0] = (end.0, end.1, 1.0);
3982    }
3983    Ok(outline)
3984}
3985
3986/// A ball TURNED about an axis that passes through it. Its grazing circle (in
3987/// the plane of the axis and the centre) crosses the axis at two poles N and S;
3988/// the part beyond the axis turns inside the sweep, and near the axis the ends
3989/// overlap. So the sweep has three faces: the wall, the outer arc of that
3990/// circle turned (a spindle torus's outer part, pinched at N and S); the
3991/// ball's back at the start less the ball at the end; and its front at the end
3992/// less the ball at the start. The two caps meet along the far arc, from S to
3993/// N, of the circle where the two spheres meet. None when the motion or tool
3994/// is not of that kind.
3995fn ball_whole_turn_on() -> bool {
3996    crate::switch!("BREP_SWEEP_BALL_WHOLE_TURN", true)
3997}
3998
3999fn ball_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
4000    let [OutlinePiece::Arc { centre, radius, start, end }, OutlinePiece::Line { .. }] = meridian else { return Ok(None) };
4001    let (centre, r) = (*centre, *radius);
4002    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 {
4003        return Ok(None);
4004    }
4005    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
4006    let centre_tool = origin.add(w.scale(centre[1]));
4007    let turned = screw.omega * (screw.t1 - screw.t0);
4008    if turned.abs() >= TAU - 1e-9 {
4009        // `BREP_SWEEP_BALL_WHOLE_TURN` (default on; `=0` restores the refusal): a ball turned a whole
4010        // turn about an axis that misses it sweeps the torus its great circle
4011        // in the axis' half-plane turns: that circle, revolved about the axis.
4012        let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
4013        let unit = |p: Vec3| finite(p) && (p.length() - 1.0).abs() <= 1e-9;
4014        if ball_whole_turn_on() && turned.is_finite() && finite(radial) && finite(origin) && finite(axis) && unit(w) && finite(screw.a) && unit(screw.e) {
4015            // The tool's own frame must be one (as every route reads it), and
4016            // its meridian the half disc: the arc closed by the diameter back
4017            // from the arc's end to its start.
4018            radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
4019            let [_, OutlinePiece::Line { from, to }] = meridian else { return Ok(None) };
4020            let at = |angle: f64| [centre[0] + r * angle.cos(), centre[1] + r * angle.sin()];
4021            let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-12 * r;
4022            if !(near(*from, at(*end)) && near(*to, at(*start)) && from[0].abs() <= 1e-12 * r && to[0].abs() <= 1e-12 * r) {
4023                return Err(input("meridian", "the ball's meridian is not the half disc closed by its diameter on the axis".into()));
4024            }
4025            let e = screw.e;
4026            let off = centre_tool.sub(screw.a);
4027            let radial = off.sub(e.scale(off.dot(e)));
4028            // Whole only if the shortfall leaves no gap the ball's own size
4029            // would see: the arc it misses, out at the ball's far side.
4030            let gap = (TAU - turned.abs()).max(0.0) * (radial.length() + r);
4031            if radial.length() > r * (1.0 + 1e-9) && gap <= 1e-9 * r {
4032                let normal = frag(e.cross(radial).normalized(), "ball_turn")?;
4033                let circle = frag(crate::make_circle(centre_tool, normal, r), "ball_turn")?;
4034                return Ok(Some(frag(crate::revolve_profile_brep(&[circle], screw.a, e, TAU), "ball_turn")?));
4035            }
4036        }
4037        return Ok(None);
4038    }
4039    let e = screw.e.scale(screw.omega.signum()); // the sense the ball turns about
4040    let c0 = screw.apply(screw.t0, centre_tool);
4041    let c1 = screw.apply(screw.t1, centre_tool);
4042    let foot = |c: Vec3| screw.a.add(e.scale(c.sub(screw.a).dot(e)));
4043    let rho = c0.sub(foot(c0)).length();
4044    if rho >= r * (1.0 - 1e-9) || rho <= 1e-9 * r {
4045        return Ok(None);
4046    }
4047    let h0 = frag(c0.sub(foot(c0)).normalized(), "radial")?;
4048    let height = (r * r - rho * rho).sqrt();
4049    let (north, south) = (foot(c0).add(e.scale(height)), foot(c0).sub(e.scale(height)));
4050    // An arc from `from` turned about `axis` through `centre` by `angle`.
4051    let arc = |about: Vec3, k: Vec3, from: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
4052        let surface = frag(make_revolution(about, k, &frag(make_line(from, from.add(k)), "line")?, angle), "arc")?;
4053        frag(surface.iso_curve_v(0.0), "arc")
4054    };
4055    // The outer arc of the grazing circle, S -> N through c0 + r h0: in the
4056    // (h0, e) plane about c0, from angle -α to α through 0, α = atan2(height, -ρ).
4057    let alpha = height.atan2(-rho);
4058    let outer = arc(c0, h0.cross(e), south, 2.0 * alpha)?;
4059    let wall = frag(make_revolution(screw.a, e, &outer, turned.abs()), "wall")?;
4060    let outer_end = frag(wall.iso_curve_u(1.0), "wall_end")?;
4061    // The far arc where the spheres meet, S -> N beyond the axis.
4062    let mid = c0.add(c1).scale(0.5);
4063    let towards = frag(mid.sub(foot(mid)).normalized(), "bisector")?;
4064    let rho_mid = mid.sub(foot(mid)).length();
4065    let beta = height.atan2(rho_mid); // S and N seen from mid, off the far direction
4066    // From S at angle β − π (in the (towards, e) plane about mid) down through
4067    // π to N at π − β: the decreasing sense, about e × towards.
4068    let meet = arc(mid, e.cross(towards), south, 2.0 * beta)?;
4069    {
4070        // The arc must pass beyond the axis (its middle on the far side).
4071        let [d0, d1] = frag(meet.domain(), "domain")?;
4072        let middle = frag(meet.evaluate(0.5 * (d0 + d1)), "middle")?;
4073        if middle.sub(foot(middle)).dot(towards) > 0.0 {
4074            return Err(refuse("ball_across_axis", "the spheres' common circle runs the wrong way round".into()));
4075        }
4076    }
4077    // A trimmed sphere cap: a chart whose poles and seam lie where the cap is not.
4078    let cap = |c: Vec3, inward: Vec3, side: Vec3, other: Vec3| -> Result<(NurbsSurface, Box<dyn Fn(Vec3) -> Vec3>), KernelRefusal> {
4079        // South pole just off the far end of the grazing circle, on the removed
4080        // side (inside the other end's ball); the seam crosses the grazing
4081        // circle beyond the axis only.
4082        let toward_south = frag(inward.add(side.scale(-0.3)).normalized(), "pole")?;
4083        let polar = toward_south.scale(-1.0);
4084        let seam = frag(side.sub(polar.scale(side.dot(polar))).normalized(), "seam")?;
4085        for k in 0..=64 {
4086            // The seam's part on the cap's side of the grazing circle must lie
4087            // inside the other ball (where the cap is not).
4088            let a = PI * k as f64 / 64.0;
4089            let q = c.add(polar.scale(-r * a.cos())).add(seam.scale(r * a.sin()));
4090            if q.sub(c).dot(side) < 0.0 && q.sub(other).length() >= r * (1.0 - 1e-9) {
4091                return Err(refuse("ball_across_axis", "no seam place for a cap".into()));
4092            }
4093        }
4094        let south_pole = c.sub(polar.scale(r));
4095        if south_pole.sub(other).length() >= r * (1.0 - 1e-6) {
4096            return Err(refuse("ball_across_axis", "no pole place for a cap".into()));
4097        }
4098        let generatrix = arc(c, polar.scale(-1.0).cross(seam), south_pole, PI)?;
4099        let surface = frag(make_revolution(c, polar, &generatrix, TAU), "cap")?;
4100        let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
4101        let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
4102        let around = polar.cross(seam);
4103        let inverse = move |x: Vec3| -> Vec3 {
4104            let d = x.sub(c).scale(1.0 / r);
4105            let latitude = d.dot(polar).clamp(-1.0, 1.0).asin();
4106            let longitude = d.dot(around).atan2(d.dot(seam)).rem_euclid(TAU);
4107            Vec3::new(
4108                crate::circle_angle_to_parameter(spans_u, TAU, longitude),
4109                crate::circle_angle_to_parameter(spans_v, PI, latitude + 0.5 * PI),
4110                0.0,
4111            )
4112        };
4113        Ok((surface, Box::new(inverse)))
4114    };
4115    let moving0 = e.cross(h0);
4116    let h1 = frag(c1.sub(foot(c1)).normalized(), "radial")?;
4117    let moving1 = e.cross(h1);
4118    // The back cap at the start (its removed part near c0 − r h0 on the back);
4119    // the front cap at the end.
4120    let (back, back_inverse) = cap(c0, h0.scale(-1.0), moving0.scale(1.0), c1)?;
4121    let (front, front_inverse) = cap(c1, h1.scale(-1.0), moving1.scale(-1.0), c0)?;
4122    let (back_joints, front_joints) = (surface_joints(&back), surface_joints(&front));
4123    let pcurve = |inverse: &dyn Fn(Vec3) -> Vec3, curve: &NurbsCurve, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
4124        let [d0, d1] = frag(curve.domain(), "domain")?;
4125        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
4126        let uv: Vec<Vec3> = ts.iter().map(|&t| curve.evaluate(t).map(|x| inverse(x))).collect::<Result<_, _>>().map_err(|e| refuse("pcurve", e))?;
4127        if pcurve_joints_on() {
4128            // The two caps share their structure (one make_revolution each).
4129            let (ju, jv) = (&back_joints.0, &back_joints.1);
4130            debug_assert_eq!(back_joints, front_joints);
4131            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
4132                let p = inverse(frag(curve.evaluate(t), "point")?);
4133                Ok([p.x, p.y])
4134            };
4135            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, ju, jv, curve)? {
4136                return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
4137            }
4138        }
4139        let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "cap_pcurve")?;
4140        if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
4141    };
4142    let mut shell = Shell::new();
4143    let (vn, vs) = (shell.vertex(north), shell.vertex(south));
4144    let k0 = shell.edge(outer.clone(), vs, vn, false)?;
4145    let k1 = shell.edge(outer_end.clone(), vs, vn, false)?;
4146    let c = shell.edge(meet.clone(), vs, vn, false)?;
4147    let ds = shell.edge(frag(make_line(south, south), "point")?, vs, vs, true)?;
4148    let dn = shell.edge(frag(make_line(north, north), "point")?, vn, vn, true)?;
4149    // Wall: u turns, v runs S -> N; outward needs v the other way round the
4150    // circle's normal, so test and pick the loop's sense.
4151    let wall_outward = {
4152        let p = frag(wall.evaluate(0.5, 0.5), "probe")?;
4153        let su = frag(wall.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(wall.evaluate(0.5 - 1e-6, 0.5), "probe")?);
4154        let sv = frag(wall.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(wall.evaluate(0.5, 0.5 - 1e-6), "probe")?);
4155        su.cross(sv).dot(p.sub(foot(p))) > 0.0
4156    };
4157    let [g0, g1] = frag(outer.domain(), "domain")?;
4158    let wall_loop = vec![
4159        (ds, true, uv_line([0.0, g0], [1.0, g0])?),
4160        (k1, true, uv_line([1.0, g0], [1.0, g1])?),
4161        (dn, true, uv_line([1.0, g1], [0.0, g1])?),
4162        (k0, false, uv_line([0.0, g1], [0.0, g0])?),
4163    ];
4164    let reversed = |list: Vec<(u64, bool, NurbsCurve)>| -> Result<Vec<(u64, bool, NurbsCurve)>, KernelRefusal> {
4165        list.into_iter().rev().map(|(e, f, p)| Ok((e, !f, frag(p.reversed(), "reversed")?))).collect()
4166    };
4167    shell.face(wall.clone(), if wall_outward { wall_loop } else { reversed(wall_loop)? });
4168    // Caps: loop (grazing arc S -> N, then the meeting arc N -> S), sense by
4169    // the signed area of its parameters (the charts' u × v points outward).
4170    for (surface, inverse, k_edge, k_curve) in [(back, &back_inverse, k0, &outer), (front, &front_inverse, k1, &outer_end)] {
4171        let mut lp = vec![(k_edge, true, pcurve(inverse.as_ref(), k_curve, true)?), (c, false, pcurve(inverse.as_ref(), &meet, false)?)];
4172        let mut area = 0.0;
4173        for (_, _, pc) in &lp {
4174            let [d0, d1] = frag(pc.domain(), "domain")?;
4175            for j in 0..64 {
4176                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")?);
4177                area += a.x * b.y - b.x * a.y;
4178            }
4179        }
4180        if area < 0.0 {
4181            lp = reversed(lp)?;
4182        }
4183        shell.face(surface, lp);
4184    }
4185    let body = shell.solid();
4186    let issues = body.validate();
4187    if !issues.is_empty() {
4188        return Err(refuse("assembly", format!("the turned ball's sweep is not valid: {:?}", issues.first())));
4189    }
4190    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() } };
4191    check_single_pass(screw, &probe, &body, &std::collections::HashSet::new())?;
4192    Ok(Some(body))
4193}
4194
4195/// A frame riding a cubic Bézier curve (`control`, in a plane square to
4196/// `up`): its origin on the curve, its first axis along the curve's tangent,
4197/// `up` fixed. The tool is given in the frame at the curve's start and carried
4198/// by it over the whole curve.
4199#[derive(Clone, Copy, Debug)]
4200pub struct FrameCurve {
4201    pub control: [Vec3; 4],
4202    pub up: Vec3,
4203}
4204
4205/// The whole sweep of a solid of revolution carried by a frame along a
4206/// curve. In the riding frame the velocity field is the speed along the
4207/// tangent plus the turn about `up`, so the grazing loop moves on the tool with
4208/// the curve's curvature. It is split at sample times (its structure must not
4209/// change), each piece sampled exactly, and the walls lofted through those
4210/// samples (quintic both ways; the samples' count doubles until the wall is
4211/// within `LOFT_TARGET` of the exact loop at the times between). Caps are the tool's
4212/// back at the start and front at the end.
4213pub fn sweep_solid_along(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4214    // An upright solid of revolution on a planar curve is translated by it:
4215    // its sweep is the planar distance to the curve within the tool's radius,
4216    // folds and crossings included (`BREP_SWEEP_UPRIGHT_SLOT`). With the
4217    // direct build on (`BREP_SWEEP_UPRIGHT_DIRECT`) the route answers only
4218    // where the general routes refuse and the curve may turn tighter than the
4219    // tool, built face by face; every sweep the general routes build is theirs
4220    // as before, and where the direct build declines their refusal stands.
4221    // With the direct build off the route takes every upright sweep.
4222    if crate::solid_sweep_upright::upright_slot_on() {
4223        if let Some(slot) = crate::solid_sweep_upright::upright_slot(tool, path) {
4224            if !crate::solid_sweep_upright::upright_direct_on() {
4225                return slot.solid();
4226            }
4227            let general = sweep_solid_along_general(tool, path);
4228            if general.is_err() && slot.turns_tighter() {
4229                if let Ok(solid) = slot.direct_solid() {
4230                    return Ok(solid);
4231                }
4232            }
4233            return general;
4234        }
4235    }
4236    sweep_solid_along_general(tool, path)
4237}
4238
4239/// [`sweep_solid_along`] by its general routes (the planar ring, the lofted
4240/// grazing loop), without the upright route.
4241fn sweep_solid_along_general(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4242    // A ring on a planar curve, from its slices (`BREP_SWEEP_PLANAR_RING`).
4243    if let Some(ring) = crate::solid_sweep_planar_ring::planar_ring_on().then(|| crate::solid_sweep_planar_ring::planar_ring_sweep(tool, path)).flatten() {
4244        return ring;
4245    }
4246    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
4247    let base = path.control[0];
4248    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
4249        return Err(input("plane", "the curve is not in a plane square to up".into()));
4250    }
4251    let tangent = path.control[1].sub(base);
4252    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
4253    let start_tangent = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
4254    let frame = Frame { control: path.control, up, start_tangent };
4255    let (mut speed, mut rate, mut extent) = (0.0f64, 0.0f64, 0.0f64);
4256    let mut previous = 0.0;
4257    for k in 0..=512 {
4258        let t = k as f64 / 512.0;
4259        let first = frame.first(t);
4260        if first.length() <= 1e-12 {
4261            return Err(input("tangent", "the curve stops (zero tangent)".into()));
4262        }
4263        speed = speed.max(first.length());
4264        rate = rate.max(frame.angle_rate(t).abs());
4265        extent = extent.max(frame.point(t).sub(base).length());
4266        let angle = frame.angle(t);
4267        if (angle - previous).abs() > 0.5 {
4268            return Err(refuse("frame_turns", "the frame turns half way round".into()));
4269        }
4270        previous = angle;
4271    }
4272    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,
4273        loop_samples: LOFT_SAMPLES, extent };
4274    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
4275        return Err(refuse("along_tool", "a frame along a curve carries a solid of revolution only".into()));
4276    };
4277    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
4278    // The splits name their pieces by angle about the tool's axis from its
4279    // radial direction: a grazing angle passing that reference renames them,
4280    // so try a few references.
4281    let mut last = None;
4282    for k in 0..8 {
4283        let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
4284        match lofted(&screw, *axis_origin, axis, reference, meridian) {
4285            Err(error) if refused_as(&error) == Some("loft_structure") => last = Some(error),
4286            other => return other,
4287        }
4288    }
4289    Err(last.expect("tried"))
4290}
4291
4292/// The whole sweep of a prism carried by a frame along a planar curve (its
4293/// axis along the frame's up): the prism `outline` (a convex polygon in the
4294/// start frame: first coordinate along the start tangent, second along
4295/// up × tangent) between `from` and `to` along up. The motion is planar, so the
4296/// sweep is the plane region the moving outline covers, extruded. That region
4297/// is found exactly: its boundary lies on the outline's corner paths, the paths
4298/// of each edge's grazing point (where the edge's normal is square to the
4299/// velocity), and the outline's edges at the two ends; these are split where
4300/// they meet, and a piece is kept where one side of it is covered and the other
4301/// not (folds, where a corner digs past a side, come out right).
4302pub fn sweep_prism_along(outline: &[[f64; 2]], from: f64, to: f64, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4303    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
4304    let base = path.control[0];
4305    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
4306        return Err(input("plane", "the curve is not in a plane square to up".into()));
4307    }
4308    let tangent = path.control[1].sub(base);
4309    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
4310    let e1 = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
4311    let e2 = up.cross(e1);
4312    let frame = Frame { control: path.control, up, start_tangent: e1 };
4313    // The frame in plane coordinates: origin c(s), turned by φ(s).
4314    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
4315    let pose = |s: f64| (flat(frame.point(s)), frame.angle(s));
4316    let rates = |s: f64| {
4317        let first = frame.first(s);
4318        ([first.dot(e1), first.dot(e2)], frame.angle_rate(s))
4319    };
4320    prism_region_sweep(outline, from, to, base, e1, e2, up, &pose, &rates, false)
4321}
4322
4323/// The whole sweep of a prism (the convex polygon `outline` in the plane
4324/// through `base` spanned by `e1`, `e2`, between `from` and `to` along `up`)
4325/// under a planar rigid motion: at s ∈ [0, 1] a point q of the plane (in the
4326/// tool's own coordinates) is at origin(s) + R(angle(s)) q, `pose` giving
4327/// (origin, angle) and `rates` their derivatives in s. The sweep is the plane
4328/// region the moving outline covers, extruded. That region is found exactly:
4329/// its boundary lies on the outline's corner paths, the paths of each edge's
4330/// grazing point (where the edge's normal is square to the velocity), and,
4331/// unless the motion is `closed` (it ends where it starts), the outline's
4332/// edges at the two ends; these are split where they meet or cross
4333/// themselves, and a piece is kept where one side of it is covered and the
4334/// other not. The region may have holes.
4335#[allow(clippy::too_many_arguments)]
4336pub fn prism_region_sweep(
4337    outline: &[[f64; 2]],
4338    from: f64,
4339    to: f64,
4340    base: Vec3,
4341    e1: Vec3,
4342    e2: Vec3,
4343    up: Vec3,
4344    pose: &dyn Fn(f64) -> ([f64; 2], f64),
4345    rates: &dyn Fn(f64) -> ([f64; 2], f64),
4346    closed: bool,
4347) -> Result<BrepSolid, KernelRefusal> {
4348    if outline.len() < 3 || !(to > from) {
4349        return Err(input("prism", "a prism needs three corners and a positive height".into()));
4350    }
4351    // Counter-clockwise, convex.
4352    let n = outline.len();
4353    let mut corners = outline.to_vec();
4354    let area: f64 = (0..n).map(|k| corners[k][0] * corners[(k + 1) % n][1] - corners[(k + 1) % n][0] * corners[k][1]).sum();
4355    if area < 0.0 {
4356        corners.reverse();
4357    }
4358    for k in 0..n {
4359        let (a, b, c) = (corners[k], corners[(k + 1) % n], corners[(k + 2) % n]);
4360        if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= 0.0 {
4361            return Err(input("prism", "the outline is not convex".into()));
4362        }
4363    }
4364    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
4365    let place = |s: f64, q: [f64; 2]| -> [f64; 2] {
4366        let (o, angle) = pose(s);
4367        let (sn, cs) = angle.sin_cos();
4368        [o[0] + cs * q[0] - sn * q[1], o[1] + sn * q[0] + cs * q[1]]
4369    };
4370    let local = |s: f64, p: [f64; 2]| -> [f64; 2] {
4371        let (o, angle) = pose(s);
4372        let (sn, cs) = angle.sin_cos();
4373        let d = [p[0] - o[0], p[1] - o[1]];
4374        [cs * d[0] + sn * d[1], -sn * d[0] + cs * d[1]]
4375    };
4376    // Edges: outward normals and offsets in the start frame.
4377    let edges: Vec<([f64; 2], f64)> = (0..n)
4378        .map(|k| {
4379            let (a, b) = (corners[k], corners[(k + 1) % n]);
4380            let d = [b[0] - a[0], b[1] - a[1]];
4381            let length = d[0].hypot(d[1]);
4382            let normal = [d[1] / length, -d[0] / length];
4383            (normal, normal[0] * a[0] + normal[1] * a[1])
4384        })
4385        .collect();
4386    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);
4387    // Is p covered at some time? The least signed distance over the motion.
4388    let depth = |p: [f64; 2]| -> f64 {
4389        let samples = 2000;
4390        let f = |s: f64| inside(local(s, p));
4391        let mut best = (f64::INFINITY, 0usize);
4392        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4393        for (k, &v) in values.iter().enumerate() {
4394            if v < best.0 {
4395                best = (v, k);
4396            }
4397        }
4398        // Refine every local minimum near the least.
4399        let mut least = best.0;
4400        for k in 0..=samples {
4401            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4402            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4403            if values[k] <= left && values[k] <= right && values[k] < best.0 + 1e-3 * scale {
4404                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);
4405                for _ in 0..80 {
4406                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4407                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4408                }
4409                least = least.min(f(0.5 * (lo + hi)));
4410            }
4411        }
4412        least
4413    };
4414    // Candidate boundary paths, each a map [0, 1] -> plane.
4415    #[derive(Clone, Copy)]
4416    enum Path {
4417        Corner(usize),
4418        /// Edge k's grazing point over the times [s0, s1].
4419        Graze(usize, f64, f64),
4420        /// Edge k at the start (false) or end (true).
4421        End(usize, bool),
4422    }
4423    // Where along edge k's line (0 at its start corner, 1 at its end) the
4424    // grazing point is at s, on the edge or beyond it.
4425    let graze_at = |k: usize, s: f64| -> Option<f64> {
4426        // Along edge k at x (in the tool's coordinates) the velocity's part
4427        // along the edge's normal n is w·n + φ' (ẑ × x)·n, w the origin's
4428        // velocity read in the tool's frame.
4429        let (a, b) = (corners[k], corners[(k + 1) % n]);
4430        let (nn, _) = edges[k];
4431        let (velocity, rate) = rates(s);
4432        let (sn, cs) = pose(s).1.sin_cos();
4433        let w = [cs * velocity[0] + sn * velocity[1], -sn * velocity[0] + cs * velocity[1]];
4434        let along = w[0] * nn[0] + w[1] * nn[1];
4435        let rot = |x: [f64; 2]| -x[1] * nn[0] + x[0] * nn[1]; // (ẑ × x)·n
4436        // An edge the origin moves along grazes where (ẑ × x)·n = 0 whatever
4437        // the turning rate (also where it is zero, at an inflection).
4438        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)) };
4439        if ga == gb {
4440            return None;
4441        }
4442        Some(ga / (ga - gb))
4443    };
4444    let graze_point = |k: usize, s: f64| -> Option<f64> { graze_at(k, s).filter(|&u| u > 0.0 && u < 1.0) };
4445    let mut paths: Vec<Path> = (0..n).map(Path::Corner).collect();
4446    // Where a grazing point enters or leaves its edge it is at a corner:
4447    // (that corner, the time), a place its path is split at.
4448    let mut junctions: Vec<(usize, f64)> = Vec::new();
4449    for k in 0..n {
4450        // Where along the motion edge k has a grazing point inside it, each
4451        // run's ends found where the point passes a corner.
4452        let steps = 2000;
4453        let mut run: Option<f64> = None;
4454        let mut passes = |inside: f64, outside: f64| -> f64 {
4455            let (mut a, mut b) = (inside, outside);
4456            for _ in 0..80 {
4457                let mid = 0.5 * (a + b);
4458                if graze_point(k, mid).is_some() { a = mid } else { b = mid }
4459            }
4460            let corner = if graze_at(k, a).is_some_and(|u| u < 0.5) { k } else { (k + 1) % n };
4461            junctions.push((corner, a));
4462            a
4463        };
4464        for j in 0..=steps {
4465            let s = j as f64 / steps as f64;
4466            let on = graze_point(k, s).is_some();
4467            match (on, run) {
4468                (true, None) => run = Some(if j == 0 { s } else { passes(s, s - 1.0 / steps as f64) }),
4469                (false, Some(s0)) => {
4470                    paths.push(Path::Graze(k, s0, passes(s - 1.0 / steps as f64, s)));
4471                    run = None;
4472                }
4473                _ => {}
4474            }
4475        }
4476        if let Some(s0) = run {
4477            paths.push(Path::Graze(k, s0, 1.0));
4478        }
4479        if !closed {
4480            paths.push(Path::End(k, false));
4481            paths.push(Path::End(k, true));
4482        }
4483    }
4484    let eval = |path: Path, t: f64| -> [f64; 2] {
4485        match path {
4486            Path::Corner(k) => place(t, corners[k]),
4487            Path::Graze(k, s0, s1) => {
4488                let s = s0 + (s1 - s0) * t;
4489                let u = graze_at(k, s).map_or(0.5, |u| u.clamp(0.0, 1.0));
4490                let (a, b) = (corners[k], corners[(k + 1) % n]);
4491                place(s, [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u])
4492            }
4493            Path::End(k, at_end) => {
4494                let (a, b) = (corners[k], corners[(k + 1) % n]);
4495                place(if at_end { 1.0 } else { 0.0 }, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])
4496            }
4497        }
4498    };
4499    let count = paths.len();
4500    region_from_paths(
4501        count,
4502        &|index: usize, t: f64| eval(paths[index], t),
4503        &|index: usize| matches!(paths[index], Path::End(..)),
4504        &|_: usize| closed,
4505        &junctions,
4506        &depth,
4507        scale,
4508        (base, e1, e2, up),
4509        (from, to),
4510    )
4511}
4512
4513/// Everything a tube (the ball of `radius` swept along the curve
4514/// `centreline(s)`, s ∈ [0, 1], its ends included) passes through as it slides
4515/// by `slide`, inside the slab `slab[0] ≤ (x − slab_origin)·n ≤ slab[1]` (`n` =
4516/// `slab_normal` normalised), which the tube must cross wholly: before the
4517/// slab at the start, past it at the end (checked at 8001 points of the
4518/// centreline, with a margin of the longest step between them). The
4519/// returned prism along the slide agrees with the sweep inside the slab; the
4520/// caller cuts a workpiece that lies within it.
4521///
4522/// The centreline must be resolved by its samples (as every path of the plane
4523/// region arrangement is): smooth, its height changing between two of the
4524/// 8001 checking samples by no more than the step between them, so that the
4525/// samples bound it. A curve that wanders between samples is outside this
4526/// contract.
4527///
4528/// Why a prism: a point x of the slab is in the sweep iff the line through x
4529/// along the slide meets the tube. If it does, `n·` grows along the line, so
4530/// its topmost point y of the starting tube lies before x, and y + slide (a
4531/// point of the final tube) past it: x − y is a multiple of the slide in
4532/// [0, 1). So the sweep in the slab is the slab's part of the prism over the
4533/// tube's shadow along the slide: in the plane square to it the union of the
4534/// discs of `radius` about the shadow γ of the centreline. That region is
4535/// bounded by γ's two offset curves (each disc's grazing points, γ ± radius
4536/// along its normal) and the end discs' circles, built exactly by the plane
4537/// region arrangement of [`sweep_prism_along`].
4538pub fn sweep_tube_slid_across(
4539    centreline: &dyn Fn(f64) -> Vec3,
4540    radius: f64,
4541    slide: Vec3,
4542    slab_origin: Vec3,
4543    slab_normal: Vec3,
4544    slab: [f64; 2],
4545) -> Result<BrepSolid, KernelRefusal> {
4546    if !(radius.is_finite() && radius > 0.0) {
4547        return Err(input("tube_radius", "the tube's radius must be positive".into()));
4548    }
4549    let up = slide.normalized().map_err(|_| input("slide", "the slide has no length".into()))?;
4550    let normal = slab_normal.normalized().map_err(|_| input("slab", "the slab's normal has no direction".into()))?;
4551    if !(slab[1] > slab[0]) || up.dot(normal).abs() < 1e-9 {
4552        return Err(input("slab", "the slab must have thickness and the slide must cross it".into()));
4553    }
4554    // Orient so the slide runs up the slab's normal.
4555    let (normal, slab) = if up.dot(normal) > 0.0 { (normal, slab) } else { (normal.scale(-1.0), [-slab[1], -slab[0]]) };
4556    let points: Vec<Vec3> = (0..=8000).map(|k| centreline(k as f64 / 8000.0)).collect();
4557    if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) {
4558        return Err(input("centreline", "the centreline has a point that is not finite".into()));
4559    }
4560    let step = points.windows(2).map(|w| w[1].sub(w[0]).length()).fold(0.0f64, f64::max);
4561    let heights: Vec<f64> = points.iter().map(|q| q.sub(slab_origin).dot(normal)).collect();
4562    let (low, high) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &h| (a.min(h), b.max(h)));
4563    let rise = slide.dot(normal);
4564    if !(high + radius + step < slab[0] && low - radius - step + rise > slab[1]) {
4565        return Err(refuse("tube_slab", "the tube does not pass wholly through the slab (it starts or ends within reach of it)".into()));
4566    }
4567    let e1 = {
4568        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) };
4569        seed.sub(up.scale(seed.dot(up))).normalized().map_err(|_| input("slide", "no frame".into()))?
4570    };
4571    let e2 = up.cross(e1);
4572    // The plane's origin on the centreline itself, so that every tolerance
4573    // reads the tube's own size, wherever it lies.
4574    let base = points[0];
4575    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
4576    let centre = |s: f64| -> [f64; 2] { flat(centreline(s)) };
4577    let velocity = |s: f64| -> [f64; 2] {
4578        let h = 1e-7;
4579        let (a, b) = ((s - h).max(0.0), (s + h).min(1.0));
4580        let (p, q) = (centre(a), centre(b));
4581        [(q[0] - p[0]) / (b - a), (q[1] - p[1]) / (b - a)]
4582    };
4583    // The shadow must keep moving (a disc standing still has no grazing points).
4584    for k in 0..=2000 {
4585        let w = velocity(k as f64 / 2000.0);
4586        if w[0].hypot(w[1]) < 1e-9 * (1.0 + radius) {
4587            return Err(refuse("tube_shadow", "the tube's shadow along the slide stops (its centreline runs along the slide)".into()));
4588        }
4589    }
4590    // Tolerances read the tube's radius (a probe beside a boundary must stay
4591    // within the tube), never more than its extent; a tube longer than 1e6
4592    // radii is beyond what the coordinates resolve at that size.
4593    let extent = (0..=64).map(|k| { let c = centre(k as f64 / 64.0); c[0].hypot(c[1]) }).fold(radius, f64::max);
4594    if extent > 1e6 * radius {
4595        return Err(refuse("tube_shadow", "the tube is too long for its radius (over a million radii)".into()));
4596    }
4597    let scale = extent.min(1e3 * radius);
4598    // Paths: the two offset curves, then the two end circles.
4599    let eval = |index: usize, t: f64| -> [f64; 2] {
4600        match index {
4601            0 | 1 => {
4602                let c = centre(t);
4603                let w = velocity(t);
4604                let length = w[0].hypot(w[1]);
4605                let side = if index == 0 { 1.0 } else { -1.0 };
4606                [c[0] - side * radius * w[1] / length, c[1] + side * radius * w[0] / length]
4607            }
4608            _ => {
4609                let c = centre(if index == 2 { 0.0 } else { 1.0 });
4610                let angle = TAU * t;
4611                [c[0] + radius * angle.cos(), c[1] + radius * angle.sin()]
4612            }
4613        }
4614    };
4615    // Inside: nearer than `radius` to the shadow at some time.
4616    let depth = |p: [f64; 2]| -> f64 {
4617        let samples = 4000;
4618        let f = |s: f64| { let c = centre(s); (p[0] - c[0]).hypot(p[1] - c[1]) - radius };
4619        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4620        let mut least = values.iter().cloned().fold(f64::INFINITY, f64::min);
4621        for k in 0..=samples {
4622            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4623            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4624            if values[k] <= left && values[k] <= right && values[k] < least + 1e-3 * scale {
4625                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);
4626                for _ in 0..80 {
4627                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4628                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4629                }
4630                least = least.min(f(0.5 * (lo + hi)));
4631            }
4632        }
4633        least
4634    };
4635    // The prism spans the slab's crossing of every line through the region:
4636    // from below the starting tube to past the final one, along the slide.
4637    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)));
4638    let margin = radius + step + 1e-3 * scale;
4639    // Each offset curve ends on its end circle, tangent to it there (both run
4640    // along the velocity), which no crossing test finds: split the circles at
4641    // those points (the angles of ±the normal there).
4642    let mut touches: Vec<(usize, f64)> = Vec::new();
4643    for (circle, s) in [(2usize, 0.0f64), (3, 1.0)] {
4644        let w = velocity(s);
4645        for side in [1.0f64, -1.0] {
4646            let angle = (side * w[0]).atan2(-side * w[1]);
4647            touches.push((circle, angle.rem_euclid(TAU) / TAU));
4648        }
4649    }
4650    region_from_paths(
4651        4,
4652        &eval,
4653        &|_| false,
4654        &|index| index >= 2,
4655        &touches,
4656        &depth,
4657        scale,
4658        (base, e1, e2, up),
4659        (a0 - margin, a1 + slide.length() + margin),
4660    )
4661}
4662
4663/// The crossing search's box culling in [`region_from_paths`]
4664/// (`BREP_SWEEP_REGION_CROSS_BOXES`, default on; `=0` visits every segment
4665/// pair, the same crossings found more slowly: square-on-a-planet-carrier
4666/// tests 74.4M pairs without it, 0.75M with it, for the same 74 Newton runs).
4667fn region_cross_boxes_on() -> bool {
4668    crate::switch!("BREP_SWEEP_REGION_CROSS_BOXES", true)
4669}
4670
4671/// The plane region bounded by pieces of the candidate `count` paths (each
4672/// `eval(index, t)`, t ∈ [0, 1]), extruded along `up` from `heights.0` to
4673/// `heights.1`: the paths are split where they cross each other or
4674/// themselves (and at `extra_cuts`), a piece is kept where `depth` (negative
4675/// inside the region) reads one side covered and the other not, and the kept
4676/// pieces chain into one outer loop and its holes. `straight_path(index)`: the
4677/// path is a segment (built as a line); `closed_path(index)`: its two ends
4678/// meet (neighbours for the self-crossing test).
4679#[allow(clippy::too_many_arguments)]
4680fn region_from_paths(
4681    count: usize,
4682    eval: &dyn Fn(usize, f64) -> [f64; 2],
4683    straight_path: &dyn Fn(usize) -> bool,
4684    closed_path: &dyn Fn(usize) -> bool,
4685    extra_cuts: &[(usize, f64)],
4686    depth: &dyn Fn([f64; 2]) -> f64,
4687    scale: f64,
4688    frame: (Vec3, Vec3, Vec3, Vec3),
4689    heights: (f64, f64),
4690) -> Result<BrepSolid, KernelRefusal> {
4691    let (base, e1, e2, up) = frame;
4692    let (from, to) = heights;
4693    // Split parameters: mutual crossings (polyline, then Newton), and each
4694    // path's ends lying on another.
4695    let m = 400;
4696    let polylines: Vec<Vec<[f64; 2]>> = (0..count).map(|p| (0..=m).map(|i| eval(p, i as f64 / m as f64)).collect()).collect();
4697    let mut cuts: Vec<Vec<f64>> = vec![vec![0.0, 1.0]; count];
4698    let tol = 1e-10 * scale;
4699    // Under `BREP_SWEEP_REGION_CROSS_BOXES` the segment pairs are visited
4700    // chunk by chunk (16 segments each), a chunk pair only where their boxes,
4701    // grown by 1e-6 of the scale and by the pair test's own reach past a
4702    // segment's ends, overlap: a crossing the test takes lies in both boxes,
4703    // and none is missed. The cuts are
4704    // sorted after, so the order they are found in does not matter.
4705    const CHUNK: usize = 16;
4706    let boxed = region_cross_boxes_on();
4707    let chunks = (m + CHUNK - 1) / CHUNK;
4708    let grow = 1e-6 * scale;
4709    let boxes: Vec<Vec<[f64; 4]>> = polylines
4710        .iter()
4711        .filter(|_| boxed)
4712        .map(|line| {
4713            (0..chunks)
4714                .map(|c| {
4715                    let (lo, hi) = (c * CHUNK, ((c + 1) * CHUNK).min(m));
4716                    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])]);
4717                    // The pair test takes a crossing up to 1e-9 of a segment's
4718                    // length past its end: grow by twice that of the chunk's
4719                    // longest segment, so every crossing it takes lies in both
4720                    // segments' boxes.
4721                    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);
4722                    let g = grow + 2e-9 * longest;
4723                    [b[0] - g, b[1] - g, b[2] + g, b[3] + g]
4724                })
4725                .collect()
4726        })
4727        .collect();
4728    let overlap = |a: &[f64; 4], b: &[f64; 4]| a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
4729    for a in 0..count {
4730        for b in a..count {
4731            // One segment pair: a crossing of the polylines, polished by Newton on the exact paths.
4732            let mut test = |i: usize, j: usize| {
4733                    // A path against itself: only where it crosses over
4734                    // (stretches apart along it; a closed path's ends are
4735                    // neighbours too).
4736                    if a == b && (j < i + 3 || (closed_path(a) && i < 3 && j + 3 > m)) {
4737                        return;
4738                    }
4739                    let (p0, p1, q0, q1) = (polylines[a][i], polylines[a][i + 1], polylines[b][j], polylines[b][j + 1]);
4740                    let d1 = [p1[0] - p0[0], p1[1] - p0[1]];
4741                    let d2 = [q1[0] - q0[0], q1[1] - q0[1]];
4742                    let det = d1[0] * d2[1] - d1[1] * d2[0];
4743                    if det.abs() < 1e-300 {
4744                        return;
4745                    }
4746                    let r = [q0[0] - p0[0], q0[1] - p0[1]];
4747                    let (x, y) = ((r[0] * d2[1] - r[1] * d2[0]) / det, (r[0] * d1[1] - r[1] * d1[0]) / det);
4748                    if !(-1e-9..=1.0 + 1e-9).contains(&x) || !(-1e-9..=1.0 + 1e-9).contains(&y) {
4749                        return;
4750                    }
4751                    // Newton on the exact paths.
4752                    let (mut ta, mut tb) = ((i as f64 + x) / m as f64, (j as f64 + y) / m as f64);
4753                    for _ in 0..50 {
4754                        let (pa, pb) = (eval(a, ta), eval(b, tb));
4755                        let h = 1e-7;
4756                        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] };
4757                        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] };
4758                        let f = [pa[0] - pb[0], pa[1] - pb[1]];
4759                        let det = -da[0] * db[1] + da[1] * db[0];
4760                        if det.abs() < 1e-300 {
4761                            break;
4762                        }
4763                        let dta = (-f[0] * db[1] + f[1] * db[0]) / det;
4764                        let dtb = (da[0] * f[1] - da[1] * f[0]) / det;
4765                        ta = (ta - dta).clamp(0.0, 1.0);
4766                        tb = (tb - dtb).clamp(0.0, 1.0);
4767                        if dta.abs() + dtb.abs() < 1e-15 {
4768                            break;
4769                        }
4770                    }
4771                    let (pa, pb) = (eval(a, ta), eval(b, tb));
4772                    if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < tol && !(a == b && (ta - tb).abs() < 1.0 / m as f64) {
4773                        cuts[a].push(ta);
4774                        cuts[b].push(tb);
4775                    }
4776            };
4777            if boxed {
4778                // Only the segment pairs of chunks whose boxes overlap.
4779                for ca in 0..chunks {
4780                    for cb in 0..chunks {
4781                        if !overlap(&boxes[a][ca], &boxes[b][cb]) {
4782                            continue;
4783                        }
4784                        for i in ca * CHUNK..((ca + 1) * CHUNK).min(m) {
4785                            for j in cb * CHUNK..((cb + 1) * CHUNK).min(m) {
4786                                test(i, j);
4787                            }
4788                        }
4789                    }
4790                }
4791            } else {
4792                for i in 0..m {
4793                    for j in 0..m {
4794                        test(i, j);
4795                    }
4796                }
4797            }
4798        }
4799    }
4800    // Extra splits the caller names (a corner's path where a grazing point passes it).
4801    for &(path, t) in extra_cuts {
4802        cuts[path].push(t);
4803    }
4804    for c in &mut cuts {
4805        c.sort_by(|x, y| x.total_cmp(y));
4806        c.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
4807    }
4808    // Pieces on the boundary: covered on exactly one side.
4809    struct Piece {
4810        path: usize,
4811        t0: f64,
4812        t1: f64,
4813    }
4814    let eps = 1e-7 * scale;
4815    let mut pieces: Vec<Piece> = Vec::new();
4816    for (index, c) in cuts.iter().enumerate() {
4817        for w in c.windows(2) {
4818            let (t0, t1) = (w[0], w[1]);
4819            if t1 - t0 < 1e-9 {
4820                continue;
4821            }
4822            let (pa, pb) = (eval(index, t0), eval(index, t1));
4823            if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < 1e-9 * scale {
4824                continue;
4825            }
4826            let tm = 0.5 * (t0 + t1);
4827            let (p, q) = (eval(index, tm), eval(index, (tm + 1e-6).min(1.0)));
4828            let d = [q[0] - p[0], q[1] - p[1]];
4829            let length = d[0].hypot(d[1]);
4830            if length == 0.0 {
4831                continue;
4832            }
4833            let left = [p[0] - d[1] / length * eps, p[1] + d[0] / length * eps];
4834            let right = [p[0] + d[1] / length * eps, p[1] - d[0] / length * eps];
4835            let (l, r) = (depth(left) < -1e-12 * scale, depth(right) < -1e-12 * scale);
4836            match (l, r) {
4837                (true, false) => pieces.push(Piece { path: index, t0, t1 }),
4838                (false, true) => pieces.push(Piece { path: index, t0: t1, t1: t0 }),
4839                _ => {}
4840            }
4841        }
4842    }
4843    // Chain into loops, the region on their left (the outer one runs
4844    // counter-clockwise, a hole's clockwise).
4845    if pieces.is_empty() {
4846        return Err(refuse("prism_along", "no boundary found".into()));
4847    }
4848    let mut used = vec![false; pieces.len()];
4849    let mut loops: Vec<Vec<usize>> = Vec::new();
4850    while let Some(first) = (0..pieces.len()).find(|&k| !used[k]) {
4851        let mut order = vec![first];
4852        used[first] = true;
4853        loop {
4854            let last = &pieces[*order.last().expect("order")];
4855            let end = eval(last.path, last.t1);
4856            let start = eval(pieces[order[0]].path, pieces[order[0]].t0);
4857            if (end[0] - start[0]).hypot(end[1] - start[1]) < 1e-8 * scale {
4858                break;
4859            }
4860            let next = (0..pieces.len()).filter(|&k| !used[k]).min_by(|&x, &y| {
4861                let (px, py) = (eval(pieces[x].path, pieces[x].t0), eval(pieces[y].path, pieces[y].t0));
4862                (px[0] - end[0]).hypot(px[1] - end[1]).total_cmp(&(py[0] - end[0]).hypot(py[1] - end[1]))
4863            });
4864            let Some(next) = next else {
4865                return Err(refuse("prism_along", "the boundary does not close".into()));
4866            };
4867            let p = eval(pieces[next].path, pieces[next].t0);
4868            if (p[0] - end[0]).hypot(p[1] - end[1]) > 1e-8 * scale {
4869                return Err(refuse("prism_along", format!("the boundary does not close (gap {:e})", (p[0] - end[0]).hypot(p[1] - end[1]))));
4870            }
4871            used[next] = true;
4872            order.push(next);
4873        }
4874        loops.push(order);
4875    }
4876    // The outer loop first: the one of greatest area.
4877    let area_of = |order: &Vec<usize>| -> f64 {
4878        let mut points: Vec<[f64; 2]> = Vec::new();
4879        for &k in order {
4880            let piece = &pieces[k];
4881            for i in 0..32 {
4882                points.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 32.0));
4883            }
4884        }
4885        (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
4886    };
4887    let areas: Vec<f64> = loops.iter().map(area_of).collect();
4888    let outer = (0..loops.len()).max_by(|&x, &y| areas[x].abs().total_cmp(&areas[y].abs())).expect("loops");
4889    if areas[outer] <= 0.0 || (0..loops.len()).any(|k| k != outer && areas[k] >= 0.0) {
4890        return Err(refuse("prism_along", "the swept region is not one region with holes".into()));
4891    }
4892    loops.swap(0, outer);
4893    // Plane curves of the loops, then the extrusion.
4894    let world = |q: [f64; 2], h: f64| base.add(e1.scale(q[0])).add(e2.scale(q[1])).add(up.scale(h));
4895    let mut shell = Shell::new();
4896    let mut top_loops = Vec::with_capacity(loops.len());
4897    let mut bottom_loops = Vec::with_capacity(loops.len());
4898    let mut extent: Vec<[f64; 2]> = Vec::new();
4899    for order in &loops {
4900        let mut loop_points: Vec<[f64; 2]> = order.iter().map(|&k| eval(pieces[k].path, pieces[k].t0)).collect();
4901        loop_points.push(loop_points[0]);
4902        let count = order.len();
4903        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();
4904        let mut bottom_e = Vec::with_capacity(count);
4905        let mut top_e = Vec::with_capacity(count);
4906        let mut curves2d = Vec::with_capacity(count);
4907        for (slot, &k) in order.iter().enumerate() {
4908            let piece = &pieces[k];
4909            let straight = straight_path(piece.path);
4910            let next = (slot + 1) % count;
4911            for i in 0..=16 {
4912                extent.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 16.0));
4913            }
4914            let curve_at = |h: f64| -> Result<NurbsCurve, KernelRefusal> {
4915                if straight {
4916                    return frag(make_line(world(loop_points[slot], h), world(loop_points[next], h)), "line");
4917                }
4918                let samples = 192;
4919                let ts: Vec<f64> = (0..=samples).map(|i| i as f64 / samples as f64).collect();
4920                let mut points: Vec<Vec3> = ts.iter().map(|&t| world(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * t), h)).collect();
4921                points[0] = world(loop_points[slot], h);
4922                points[samples] = world(loop_points[next], h);
4923                frag(crate::interpolate_curve(&points, 5, &ts), "plane_path")
4924            };
4925            let (cb, ct) = (curve_at(from)?, curve_at(to)?);
4926            bottom_e.push(shell.edge(cb.clone(), bottom_v[slot], bottom_v[next], false)?);
4927            top_e.push(shell.edge(ct.clone(), top_v[slot], top_v[next], false)?);
4928            curves2d.push((cb, ct));
4929        }
4930        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<_, _>>()?;
4931        // Top (outward up) and bottom (outward down) loops.
4932        let mut coedges = Vec::with_capacity(count);
4933        for k in 0..count {
4934            coedges.push((top_e[k], true, plane_pcurve(world([0.0, 0.0], to), e1, e2, &curves2d[k].1, true)?));
4935        }
4936        top_loops.push(coedges);
4937        let mut coedges = Vec::with_capacity(count);
4938        for k in (0..count).rev() {
4939            coedges.push((bottom_e[k], false, plane_pcurve(world([0.0, 0.0], from), e2, e1, &curves2d[k].0, false)?));
4940        }
4941        bottom_loops.push(coedges);
4942        // Sides: the bottom curve extruded (u along it, v up), outward on its right.
4943        for k in 0..count {
4944            let next = (k + 1) % count;
4945            let (cb, _) = &curves2d[k];
4946            let rows: Vec<Vec<Vec4>> = cb
4947                .control_points
4948                .iter()
4949                .map(|p| {
4950                    let x = p.point().expect("point");
4951                    vec![Vec4::from_point(x, p.w), Vec4::from_point(x.add(up.scale(to - from)), p.w)]
4952                })
4953                .collect();
4954            let surface = frag(NurbsSurface::new(cb.degree, 1, cb.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows), "side")?;
4955            let [u0, u1] = frag(cb.domain(), "domain")?;
4956            let coedges = vec![
4957                (bottom_e[k], true, uv_line([u0, 0.0], [u1, 0.0])?),
4958                (verticals[next], true, uv_line([u1, 0.0], [u1, 1.0])?),
4959                (top_e[k], false, uv_line([u1, 1.0], [u0, 1.0])?),
4960                (verticals[k], false, uv_line([u0, 1.0], [u0, 0.0])?),
4961            ];
4962            shell.face(surface, coedges);
4963        }
4964    }
4965    let top_points: Vec<Vec3> = extent.iter().map(|&q| world(q, to)).collect();
4966    shell.face_loops(plane_patch(world([0.0, 0.0], to), e1, e2, &top_points)?, top_loops);
4967    let bottom_points: Vec<Vec3> = extent.iter().map(|&q| world(q, from)).collect();
4968    shell.face_loops(plane_patch(world([0.0, 0.0], from), e2, e1, &bottom_points)?, bottom_loops);
4969    let body = shell.solid();
4970    let issues = body.validate();
4971    if !issues.is_empty() {
4972        return Err(refuse("assembly", format!("the swept prism is not valid: {:?}", issues.first())));
4973    }
4974    Ok(body)
4975}
4976
4977/// A prism whose section is a convex polygon, carried by turns about axes
4978/// all along its own (a planar motion: a planet on its carrier) that ends
4979/// where it starts: its whole sweep (`prism_region_sweep`), or None when the
4980/// tool or motion is not of that kind. `steps`: each turn's axis point,
4981/// direction and rate, applied in order at every t ∈ [t0, t1].
4982#[allow(clippy::too_many_arguments)]
4983pub fn closed_planar_prism(
4984    origin: Vec3,
4985    normal: Vec3,
4986    x_axis: Vec3,
4987    outline: &[OutlinePiece],
4988    from: f64,
4989    to: f64,
4990    steps: &[(Vec3, Vec3, f64, f64)],
4991    t0: f64,
4992    t1: f64,
4993) -> Result<Option<BrepSolid>, KernelRefusal> {
4994    let Ok(up) = normal.normalized() else { return Ok(None) };
4995    let Ok(e1) = x_axis.sub(up.scale(x_axis.dot(up))).normalized() else { return Ok(None) };
4996    let e2 = up.cross(e1);
4997    // A polygon of straight sides, in order.
4998    let mut corners: Vec<[f64; 2]> = Vec::with_capacity(outline.len());
4999    for (k, piece) in outline.iter().enumerate() {
5000        let OutlinePiece::Line { from: a, to: b } = piece else { return Ok(None) };
5001        let OutlinePiece::Line { from: next, .. } = &outline[(k + 1) % outline.len()] else { return Ok(None) };
5002        if (b[0] - next[0]).hypot(b[1] - next[1]) > 1e-9 * (1.0 + b[0].hypot(b[1])) {
5003            return Ok(None);
5004        }
5005        corners.push(*a);
5006    }
5007    if corners.len() < 3 || steps.is_empty() || !(t1 > t0) {
5008        return Ok(None);
5009    }
5010    // Convex (either way round), or it is another engine's.
5011    let turn_of = |k: usize| {
5012        let (a, b, c) = (corners[k], corners[(k + 1) % corners.len()], corners[(k + 2) % corners.len()]);
5013        (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
5014    };
5015    let first_turn = turn_of(0);
5016    if first_turn == 0.0 || (1..corners.len()).any(|k| turn_of(k) * first_turn <= 0.0) {
5017        return Ok(None);
5018    }
5019    // Turns only, about axes along the prism's own: (centre in the plane, rate about +up).
5020    let mut turns: Vec<([f64; 2], f64)> = Vec::with_capacity(steps.len());
5021    for &(point, direction, turn, advance) in steps {
5022        let Ok(axis) = direction.normalized() else { return Ok(None) };
5023        if advance != 0.0 || axis.cross(up).length() > 1e-12 {
5024            return Ok(None);
5025        }
5026        let r = point.sub(origin);
5027        turns.push(([r.dot(e1), r.dot(e2)], turn * axis.dot(up).signum()));
5028    }
5029    let moved = |t: f64, q: [f64; 2]| -> [f64; 2] {
5030        let mut x = q;
5031        for &(c, rate) in &turns {
5032            let (sn, cs) = (rate * t).sin_cos();
5033            let d = [x[0] - c[0], x[1] - c[1]];
5034            x = [c[0] + cs * d[0] - sn * d[1], c[1] + sn * d[0] + cs * d[1]];
5035        }
5036        x
5037    };
5038    let total: f64 = turns.iter().map(|t| t.1).sum();
5039    // The turns compose to one rigid motion of the plane: a point q (where
5040    // it stands before any motion) is at moved(t, 0) + R(total t) q.
5041    let pose = |s: f64| -> ([f64; 2], f64) {
5042        let t = t0 + (t1 - t0) * s;
5043        (moved(t, [0.0, 0.0]), total * t)
5044    };
5045    // The turns are defined at every t, so the origin's velocity is a
5046    // centred difference at the motion's ends too.
5047    let rates = |s: f64| -> ([f64; 2], f64) {
5048        let h = 1e-6;
5049        let (pa, pb) = (pose(s - h).0, pose(s + h).0);
5050        ([(pb[0] - pa[0]) / (2.0 * h), (pb[1] - pa[1]) / (2.0 * h)], total * (t1 - t0))
5051    };
5052    // Ends where it starts: the same turn (mod 2π) and place.
5053    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
5054    let closes = corners.iter().all(|&c| {
5055        let (a, b) = (moved(t0, c), moved(t1, c));
5056        (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-9 * scale
5057    });
5058    if !closes {
5059        return Ok(None);
5060    }
5061    prism_region_sweep(&corners, from, to, origin, e1, e2, up, &pose, &rates, true).map(Some)
5062}
5063
5064/// Two turns driven by one parameter t: first by `rates[0]·t` about the
5065/// first axis (point, direction), then by `rates[1]·t` about the second; both
5066/// axes fixed in the world; t from `from` to `to`.
5067#[derive(Clone, Copy, Debug)]
5068pub struct TwoTurns {
5069    pub axes: [(Vec3, Vec3); 2],
5070    pub rates: [f64; 2],
5071    pub from: f64,
5072    pub to: f64,
5073}
5074
5075/// The whole sweep of a solid of revolution tumbled by two turns about skew
5076/// axes. The grazing loop moves on the tool (the instantaneous screw changes
5077/// with t), so the walls are lofted through exact samples. Where the tumble
5078/// passes over a point twice (the one-pass probe), the time is bisected into
5079/// spans each passing once, and the spans' sweeps are joined (consecutive
5080/// spans meet along a grazing loop; distant ones overlap).
5081pub fn sweep_solid_tumbled(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
5082    let (solid, by_tube) = sweep_solid_tumbled_any_route(tool, motion)?;
5083    // A ring's sweep is recorded with its motion (and whether the tube route
5084    // built it), so a boolean of two can take the dedicated two-tube route
5085    // (BREP_SWEEP_TUBE_BOOLEAN, on unless =0).
5086    if crate::solid_sweep_tube::boolean::tube_boolean_on() {
5087        if let Some(tube) = ring_tube(tool, motion) {
5088            crate::solid_sweep_tube::boolean::record(&solid, tube, by_tube);
5089        }
5090    }
5091    Ok(solid)
5092}
5093
5094/// The sweep, and whether the tube route built it.
5095fn sweep_solid_tumbled_any_route(tool: &SolidTool, motion: &TwoTurns) -> Result<(BrepSolid, bool), KernelRefusal> {
5096    // A ring whose swept tube K bounds the solid outright, by the tube route
5097    // (BREP_SWEEP_TORUS_TUBE, default off); it declines anything else.
5098    if crate::solid_sweep_tube::torus_tube_on() {
5099        if let Some(tube) = ring_tube(tool, motion) {
5100            if let Ok(solid) = crate::solid_sweep_tube::sweep_torus_tube(&tube) {
5101                return Ok((solid, true));
5102            }
5103        }
5104    }
5105    let mut tube_declined = false;
5106    let built = sweep_solid_tumbled_routes(tool, motion, &mut tube_declined);
5107    // A ring every route above refuses, by the tube route as a rescue
5108    // (BREP_SWEEP_TORUS_TUBE_RESCUE, on unless =0): it runs only after a
5109    // refusal and answers only with a body that validates, else that refusal
5110    // stands. brep-bench swept/tumbling-torus-crossed-reverse (-100..100): the
5111    // routes refuse in 0.4 s ("the ring's grazing curves turn too fast"), the
5112    // tube builds it in 14 s (one core).
5113    let Err(refusal) = built else { return built };
5114    if crate::solid_sweep_tube::torus_tube_rescue_on() && !crate::solid_sweep_tube::torus_tube_on() && !tube_declined {
5115        if let Some(tube) = ring_tube(tool, motion) {
5116            if let Ok(solid) = crate::solid_sweep_tube::sweep_torus_tube(&tube) {
5117                return Ok((solid, true));
5118            }
5119        }
5120    }
5121    Err(refusal)
5122}
5123
5124/// The tumbled sweep by the lofted walls, then (a ring they refuse) by the
5125/// ring's trim route.
5126/// (The body, and whether the tube route built it; `tube_declined` is set
5127/// where the tube route was tried here and declined.)
5128fn sweep_solid_tumbled_routes(tool: &SolidTool, motion: &TwoTurns, tube_declined: &mut bool) -> Result<(BrepSolid, bool), KernelRefusal> {
5129    let lofted = sweep_solid_tumbled_lofted(tool, motion);
5130    // A ring (a whole circle off its axis) the lofted walls refuse, by the
5131    // trim engine (BREP_SWEEP_RING_TRIM); the lofted refusal stands where it
5132    // refuses too. Rows the walls build are left to them.
5133    let Err(refusal) = lofted else {
5134        return lofted.map(|mut solid| {
5135            if cusp_first_on() {
5136                start_loops_at_cusps(&mut solid);
5137            }
5138            (solid, false)
5139        });
5140    };
5141    // A wall whose double curve reaches a corner: the trim route meets that
5142    // double curve's tip, which it does not yet write so a reader integrates
5143    // round it, and refuses after the work; declined before it.
5144    if !crate::solid_sweep_trim::ring_trim_on() || (refusal.to_string().contains(DOUBLE_CURVE_CORNER) && !crate::solid_sweep_trim::tip_splice_on()) {
5145        return Err(refusal);
5146    }
5147    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return Err(refusal) };
5148    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return Err(refusal) };
5149    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius) {
5150        return Err(refusal);
5151    }
5152    let (Ok(axis), Ok(d0), Ok(d1)) = (axis_direction.normalized(), motion.axes[0].1.normalized(), motion.axes[1].1.normalized()) else { return Err(refusal) };
5153    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
5154    let ring_centre = axis_origin.add(axis.scale(centre[1]));
5155    // A ring whose grazing curves turn too fast for the lofted walls, by the
5156    // tube route first (BREP_SWEEP_TORUS_TUBE_GRAZING, on unless =0): the
5157    // tube is made for such a ring, and the trim route, where it builds one at
5158    // all, takes several times as long (brep-bench swept/tumbling-torus-
5159    // crossed-forward: 30 s by the trim route, 5 s by the tube, one core). The
5160    // lofted walls refuse so where the grazing curve's base angle steps over
5161    // 0.5 rad between samples: 1.25 for that case and 2.90 for crossed-reverse,
5162    // 0.41 at most for the rest of the tumbling family, which never comes here.
5163    if crate::solid_sweep_tube::torus_tube_grazing_on() && refusal.to_string().contains(GRAZING_TURNS_TOO_FAST) {
5164        if let Some(tube) = ring_tube(tool, motion) {
5165            match crate::solid_sweep_tube::sweep_torus_tube(&tube) {
5166                Ok(solid) => return Ok((solid, true)),
5167                Err(_) => *tube_declined = true,
5168            }
5169        }
5170    }
5171    crate::solid_sweep_trim::sweep_ring_tumbled(ring_centre, axis, centre[0], *radius, &two, motion.from, motion.to).map(|solid| (solid, false)).or(Err(refusal))
5172}
5173
5174/// `BREP_SWEEP_CUSP_FIRST` (on unless =0): each loop of a tumbled sweep starts
5175/// at its cusp corner, where it has one.
5176fn cusp_first_on() -> bool {
5177    crate::switch!("BREP_SWEEP_CUSP_FIRST", true)
5178}
5179
5180/// Each loop rotated to start at its cusp corner (a zero-angle corner: the
5181/// edge leaving it runs back along the edge arriving, within 0.05 rad), where
5182/// it has one; the sharpest such corner where it has several. Topology and
5183/// geometry are unchanged. A reader that places a loop on its surface by
5184/// inverting the edges' points, each edge seeded from the last one's end,
5185/// mislays a corner where an edge creeps into a cusp (its point all but still
5186/// while its parameters still move): from the cusp it starts clean.
5187pub(crate) fn start_loops_at_cusps(solid: &mut BrepSolid) {
5188    let ends: HashMap<u64, [(Vec3, Vec3); 2]> = solid
5189        .edges
5190        .iter()
5191        .filter_map(|e| {
5192            let span = e.t1 - e.t0;
5193            let at = |t: f64| e.curve.evaluate(t).ok();
5194            let (p0, p1) = (at(e.t0)?, at(e.t1)?);
5195            let (q0, q1) = (at(e.t0 + 1e-2 * span)?, at(e.t1 - 1e-2 * span)?);
5196            // (point, direction into the edge) at its start and at its end
5197            Some((e.id, [(p0, q0.sub(p0)), (p1, q1.sub(p1))]))
5198        })
5199        .collect();
5200    for face in solid.shells.iter_mut().flat_map(|s| s.faces.iter_mut()) {
5201        for l in face.loops.iter_mut() {
5202            let n = l.coedges.len();
5203            if n < 2 {
5204                continue;
5205            }
5206            let mut best: Option<(f64, usize)> = None;
5207            for k in 0..n {
5208                let (before, after) = (&l.coedges[(k + n - 1) % n], &l.coedges[k]);
5209                let (Some(b), Some(a)) = (ends.get(&before.edge_id), ends.get(&after.edge_id)) else { continue };
5210                // into the corner back along the edge arriving, and out along the edge leaving
5211                let back = if before.forward { b[1].1 } else { b[0].1 };
5212                let out = if after.forward { a[0].1 } else { a[1].1 };
5213                let (lb, lo) = (back.length(), out.length());
5214                if !(lb > 0.0 && lo > 0.0) {
5215                    continue;
5216                }
5217                let along = back.dot(out) / (lb * lo);
5218                if along > (0.05f64).cos() && best.map_or(true, |(x, _)| along > x) {
5219                    best = Some((along, k));
5220                }
5221            }
5222            if let Some((_, k)) = best {
5223                l.coedges.rotate_left(k);
5224            }
5225        }
5226    }
5227}
5228
5229/// The tube route's reading of a ring tool (a whole circle off its axis) under two turns.
5230fn ring_tube(tool: &SolidTool, motion: &TwoTurns) -> Option<crate::solid_sweep_tube::Tube> {
5231    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return None };
5232    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return None };
5233    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius && motion.from.is_finite() && motion.to > motion.from) {
5234        return None;
5235    }
5236    let (axis, d0, d1) = (axis_direction.normalized().ok()?, motion.axes[0].1.normalized().ok()?, motion.axes[1].1.normalized().ok()?);
5237    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
5238    crate::solid_sweep_tube::Tube::new(axis_origin.add(axis.scale(centre[1])), axis, centre[0], *radius, two, motion.from, motion.to)
5239}
5240
5241/// The lofted walls' refusal where a wall's double curve reaches a corner of
5242/// its grazing loop (the tumbled sweep reads it to skip the ring's trim route).
5243#[doc(hidden)]
5244pub const DOUBLE_CURVE_CORNER: &str = "the double curve of a wall reaches a corner of its grazing loop";
5245
5246/// The tumbled sweep by the lofted walls (a polyhedron by the trim engine).
5247fn sweep_solid_tumbled_lofted(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
5248    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
5249        return Err(input("range", "the motion's range must run forward".into()));
5250    }
5251    let mut points = [Vec3::new(0.0, 0.0, 0.0); 2];
5252    let mut directions = [Vec3::new(0.0, 0.0, 1.0); 2];
5253    for k in 0..2 {
5254        points[k] = motion.axes[k].0;
5255        directions[k] = motion.axes[k].1.normalized().map_err(|_| input("axis", "a turn's axis has no direction".into()))?;
5256    }
5257    let turns = Turns { points, directions, rates: motion.rates };
5258    // A convex polyhedron, by the trim engine (default off).
5259    if let SolidTool::Polyhedron { vertices, faces } = tool {
5260        if crate::solid_sweep_trim::trim_engine_on() {
5261            let two = crate::solid_sweep_trim::TwoTurnMotion { points, directions, rates: motion.rates };
5262            return crate::solid_sweep_trim::sweep_convex_tumbled(vertices, faces, &two, motion.from, motion.to);
5263        }
5264    }
5265    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
5266        return Err(refuse("tumble_tool", "a tumble sweeps a solid of revolution only".into()));
5267    };
5268    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
5269    let base = Screw {
5270        a: points[0],
5271        e: directions[0],
5272        omega: motion.rates[0].abs() + motion.rates[1].abs(),
5273        c: 0.0,
5274        c2: 0.0,
5275        t0: motion.from,
5276        t1: motion.to,
5277        frame: None,
5278        turns: Some(turns),
5279        frozen: None,
5280        loop_samples: LOFT_SAMPLES,
5281        extent: points[1].sub(points[0]).length(),
5282    };
5283    let span = |t0: f64, t1: f64| -> Result<BrepSolid, KernelRefusal> {
5284        let mut screw = base;
5285        screw.t0 = t0;
5286        screw.t1 = t1;
5287        let mut last = None;
5288        // The loop's sampling doubles while the walls' rows miss between
5289        // samples (a thin ring's loop bends sharply before it folds).
5290        'samples: while screw.loop_samples <= 16 * LOFT_SAMPLES {
5291            for k in 0..8 {
5292                let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
5293                match lofted(&screw, *axis_origin, axis, reference, meridian) {
5294                    // A bulge that crosses a seam high up reads on the next
5295                    // wall as a part held away from its end: other seams too.
5296                    Err(error) if matches!(refused_as(&error), Some("loft_structure") | Some("end_trim_corner") | Some("end_trim_deep")) => last = Some(error),
5297                    Err(error) if refused_as(&error) == Some("loft_rows") => {
5298                        last = Some(error);
5299                        screw.loop_samples *= 2;
5300                        continue 'samples;
5301                    }
5302                    other => return other,
5303                }
5304            }
5305            break;
5306        }
5307        Err(last.expect("tried"))
5308    };
5309    // Bisect where the sweep folds over itself.
5310    let mut pending = vec![(motion.from, motion.to, 0usize)];
5311    let mut spans: Vec<(f64, BrepSolid)> = Vec::new();
5312    while let Some((t0, t1, depth)) = pending.pop() {
5313        match span(t0, t1) {
5314            Ok(body) => spans.push((t0, body)),
5315            Err(error) if refused_as(&error) == Some("folds") && depth < 6 => {
5316                let middle = 0.5 * (t0 + t1);
5317                pending.push((middle, t1, depth + 1));
5318                pending.push((t0, middle, depth + 1));
5319            }
5320            Err(error) => return Err(error),
5321        }
5322    }
5323    spans.sort_by(|a, b| a.0.total_cmp(&b.0));
5324    let mut bodies: Vec<BrepSolid> = spans.into_iter().map(|(_, body)| body).collect();
5325    if bodies.len() == 1 {
5326        return Ok(bodies.pop().expect("one"));
5327    }
5328    crate::boolean_operation_nary(&bodies, crate::BooleanOperation::Union)
5329}
5330
5331/// A cap's pcurve for a lofted edge through the cap's exact chart (the edge
5332/// read back into the tool's frame at the cap's time).
5333fn charted_pcurve(chart: &Chart, screw: &Screw, t: f64, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
5334    let [d0, d1] = frag(curve.domain(), "domain")?;
5335    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
5336    let mut uv = Vec::with_capacity(ts.len());
5337    let mut poles = Vec::with_capacity(ts.len());
5338    for &tt in &ts {
5339        let x = screw.invert(t, frag(curve.evaluate(tt), "point")?);
5340        let [u, v] = chart.invert(x);
5341        uv.push(Vec3::new(u, v, 0.0));
5342        poles.push(chart.at_pole(x));
5343    }
5344    // Where the path crosses a span joint of the chart, one quintic through
5345    // it rings between samples (the parameter's second derivative jumps
5346    // there): by the run between joints instead (`BREP_SWEEP_PCURVE_JOINTS`).
5347    if pcurve_joints_on() && !poles.iter().any(|&p| p) {
5348        let (joints_u, joints_v) = chart.joints();
5349        let at = |tt: f64| -> Result<[f64; 2], KernelRefusal> { Ok(chart.invert(screw.invert(t, frag(curve.evaluate(tt), "point")?))) };
5350        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints_u, &joints_v, curve)? {
5351            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
5352        }
5353    }
5354    continue_pole_angles(&mut uv, &ts, &poles)?;
5355    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "charted_pcurve")?;
5356    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
5357}
5358
5359/// A surface's joints in each parameter: its interior knots that leave it C1
5360/// or less (a rational circle's spans meet at double knots), where a chart's
5361/// parameter bends.
5362fn surface_joints(surface: &NurbsSurface) -> (Vec<f64>, Vec<f64>) {
5363    let joints = |knots: &[f64], degree: usize| -> Vec<f64> {
5364        let (first, last) = (knots[0], knots[knots.len() - 1]);
5365        let mut out: Vec<f64> = Vec::new();
5366        for (i, &k) in knots.iter().enumerate() {
5367            if k > first && k < last && (i == 0 || knots[i - 1] != k) && knots.iter().filter(|&&x| x == k).count() + 1 >= degree {
5368                out.push(k);
5369            }
5370        }
5371        out
5372    };
5373    (joints(&surface.knots_u, surface.degree_u), joints(&surface.knots_v, surface.degree_v))
5374}
5375
5376thread_local! {
5377    /// Set while a split is read only for its curves and structure (a loft's
5378    /// interior times): its caps' pcurves are then never used.
5379    static PCURVES_SKIPPED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5380}
5381
5382/// The switch for skipping the cap pcurves of a loft's interior splits
5383/// (default on, `=0` fits them all; the body is the same either way).
5384fn loft_splits_lean_on() -> bool {
5385    crate::switch!("BREP_SWEEP_LOFT_SPLITS_LEAN", true)
5386}
5387
5388/// `action` with the split's cap pcurves read at their ends only: a split at
5389/// a loft's interior time is read for its curves, samples and structure, its
5390/// caps' pcurves never (only the end poses' caps are built).
5391fn with_pcurves_skipped<T>(action: impl FnOnce() -> T) -> T {
5392    // Restored on the way out, an unwind too, so a caught panic leaves no
5393    // later sweep on this thread building its end caps' pcurves as lines.
5394    struct Restore(bool);
5395    impl Drop for Restore {
5396        fn drop(&mut self) {
5397            PCURVES_SKIPPED.with(|cell| cell.set(self.0));
5398        }
5399    }
5400    let _restore = Restore(PCURVES_SKIPPED.with(|cell| cell.replace(true)));
5401    action()
5402}
5403
5404/// A grazing curve through its exact samples (quintic); in a split read only
5405/// for its curves' samples and structure ([`with_pcurves_skipped`]: a loft's
5406/// interior times), the line between its ends, never read as a curve.
5407fn fit_tool_curve(points: &[Vec3], params: &[f64]) -> Result<NurbsCurve, String> {
5408    if PCURVES_SKIPPED.with(|cell| cell.get()) && points.len() >= 2 && params.len() == points.len() {
5409        let (a, b) = (params[0], params[params.len() - 1]);
5410        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)]);
5411    }
5412    crate::interpolate_curve(points, 5, params)
5413}
5414
5415/// A cap pcurve's stations: the whole set, or its two ends where the pcurve
5416/// is never used ([`with_pcurves_skipped`]).
5417fn pcurve_stations(d0: f64, d1: f64) -> Vec<f64> {
5418    if PCURVES_SKIPPED.with(|cell| cell.get()) {
5419        return vec![d0, d1];
5420    }
5421    (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect()
5422}
5423
5424/// The quintic through a cap pcurve's stations; through two (a skipped
5425/// pcurve), the line between its ends.
5426fn fit_pcurve(uv: &[Vec3], ts: &[f64]) -> Result<NurbsCurve, String> {
5427    if ts.len() == 2 {
5428        return NurbsCurve::new(1, vec![ts[0], ts[0], ts[1], ts[1]], uv.iter().map(|&p| Vec4::from_point(p, 1.0)).collect());
5429    }
5430    crate::interpolate_curve(uv, 5, ts)
5431}
5432
5433/// The switch for [`jointed_pcurve`] (default on; `=0` fits one quintic as before).
5434fn pcurve_joints_on() -> bool {
5435    crate::switch!("BREP_SWEEP_PCURVE_JOINTS", true)
5436}
5437
5438/// A cap's pcurve broken where its path crosses a span joint of its chart:
5439/// the edge's parameter at each crossing found by bisection (`at` reads the
5440/// path's chart parameters at an edge parameter), each run between them
5441/// sampled as densely as the whole and interpolated (quintic) on its own, the
5442/// runs joined C0 at the crossings, so each run interpolates a smooth function
5443/// and the trim keeps to its edge at the same parameter, not only at the
5444/// samples. `ts`, `uv`: the whole's samples; `edge`: the curve the path
5445/// reads (its own C1-or-less knots are cut too). None where the path crosses
5446/// no joint (the one quintic is smooth there).
5447fn 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> {
5448    if ts.len() < 3 || ts.len() != uv.len() {
5449        return Ok(None);
5450    }
5451    let (d0, d1) = (ts[0], ts[ts.len() - 1]);
5452    // The edge's own joints: an interior knot that leaves it C1 or less (a
5453    // rational arc's spans) kinks its parameter, so the path's too.
5454    let mut cuts: Vec<f64> = Vec::new();
5455    for (index, &k) in edge.knots.iter().enumerate() {
5456        if k > d0 && k < d1 && (index == 0 || edge.knots[index - 1] != k) {
5457            let multiplicity = edge.knots.iter().filter(|&&x| x == k).count();
5458            if multiplicity + 1 >= edge.degree {
5459                cuts.push(k);
5460            }
5461        }
5462    }
5463    for j in 0..ts.len() - 1 {
5464        let (a, b) = (uv[j], uv[j + 1]);
5465        for (coord, joints) in [(0usize, joints_u), (1, joints_v)] {
5466            let (ca, cb) = if coord == 0 { (a.x, b.x) } else { (a.y, b.y) };
5467            for &k in joints {
5468                // A sample on the joint itself is the cut (a path that only
5469                // touches it is cut there too, harmlessly).
5470                if ca == k && j > 0 {
5471                    cuts.push(ts[j]);
5472                    continue;
5473                }
5474                if (ca - k) * (cb - k) < 0.0 {
5475                    // Bisect the edge's parameter for the crossing.
5476                    let (mut lo, mut hi) = (ts[j], ts[j + 1]);
5477                    let side = ca < k;
5478                    for _ in 0..80 {
5479                        let mid = 0.5 * (lo + hi);
5480                        if mid <= lo || mid >= hi {
5481                            break;
5482                        }
5483                        if (at(mid)?[coord] < k) == side { lo = mid } else { hi = mid }
5484                    }
5485                    cuts.push(0.5 * (lo + hi));
5486                }
5487            }
5488        }
5489    }
5490    if cuts.is_empty() {
5491        return Ok(None);
5492    }
5493    // Each run at least a millionth of the whole: a cut nearer an end or
5494    // another than that is dropped (its run would be too short to fit).
5495    let least = 1e-6 * (d1 - d0);
5496    cuts.sort_by(f64::total_cmp);
5497    let mut bounds = vec![d0];
5498    for c in cuts {
5499        if c - bounds[bounds.len() - 1] >= least && d1 - c >= least {
5500            bounds.push(c);
5501        }
5502    }
5503    if bounds.len() == 1 {
5504        return Ok(None);
5505    }
5506    bounds.push(d1);
5507    let samples = ts.len() - 1;
5508    let degree = 5;
5509    let mut knots: Vec<f64> = Vec::new();
5510    let mut poles: Vec<Vec4> = Vec::new();
5511    let runs = bounds.len() - 1;
5512    for (index, run) in bounds.windows(2).enumerate() {
5513        let (a, b) = (run[0], run[1]);
5514        let count = ((samples as f64 * (b - a) / (d1 - d0)).ceil() as usize).max(degree + 1);
5515        let params: Vec<f64> = (0..=count).map(|i| if i == count { b } else { a + (b - a) * i as f64 / count as f64 }).collect();
5516        let points: Vec<Vec3> = params.iter().map(|&tt| at(tt).map(|[u, v]| Vec3::new(u, v, 0.0))).collect::<Result<_, _>>()?;
5517        // A run that does not fit falls back to the one quintic, never a refusal.
5518        let Ok(piece) = crate::interpolate_curve(&points, degree, &params) else { return Ok(None) };
5519        if piece.degree != degree {
5520            return Ok(None);
5521        }
5522        let n = piece.knots.len();
5523        if index == 0 {
5524            knots.extend_from_slice(&piece.knots[..n - (degree + 1)]);
5525            poles.extend_from_slice(&piece.control_points);
5526        } else {
5527            // The joint: its parameter `degree` times (C0), this run's interior
5528            // knots; its first pole is the previous run's last.
5529            knots.extend(std::iter::repeat_n(a, degree));
5530            knots.extend_from_slice(&piece.knots[degree + 1..n - (degree + 1)]);
5531            poles.extend_from_slice(&piece.control_points[1..]);
5532        }
5533        if index + 1 == runs {
5534            knots.extend(std::iter::repeat_n(b, degree + 1));
5535        }
5536    }
5537    Ok(NurbsCurve::new(degree, knots, poles).ok())
5538}
5539
5540/// An edge through its surface's pole (a ball carried square to its own
5541/// axis: every grazing circle runs pole to pole) has no angle there, and the
5542/// inverse returns any. Each sample at a pole (`poles`) takes the first
5543/// parameter its neighbours run to, continued in a line.
5544fn continue_pole_angles(uv: &mut [Vec3], ts: &[f64], poles: &[bool]) -> Result<(), KernelRefusal> {
5545    for j in 0..uv.len() {
5546        if !poles[j] {
5547            continue;
5548        }
5549        let near = if j + 2 < uv.len() && !poles[j + 1] && !poles[j + 2] {
5550            [j + 1, j + 2]
5551        } else if j >= 2 && !poles[j - 1] && !poles[j - 2] {
5552            [j - 1, j - 2]
5553        } else {
5554            return Err(refuse("cap_pole", "a lofted edge stays on its cap's pole".into()));
5555        };
5556        let (a, b) = (uv[near[0]].x, uv[near[1]].x);
5557        uv[j].x = a + (a - b) * (ts[j] - ts[near[0]]) / (ts[near[0]] - ts[near[1]]);
5558    }
5559    Ok(())
5560}
5561
5562/// A cap's pcurve for a lofted edge: its dense image on the cap's surface.
5563fn projected_pcurve(surface: &NurbsSurface, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
5564    let [d0, d1] = frag(curve.domain(), "domain")?;
5565    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
5566    let mut uv = Vec::with_capacity(ts.len());
5567    let mut poles = Vec::with_capacity(ts.len());
5568    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5569    let step = 1e-3 * (u1 - u0);
5570    for &t in &ts {
5571        let x = frag(curve.evaluate(t), "point")?;
5572        let foot = frag(crate::project_point_to_surface(surface, x), "project")?;
5573        if foot.distance > 1e-6 * (1.0 + x.length()) {
5574            return Err(refuse("loft_cap", format!("a lofted edge leaves its cap by {} at {x:?}", foot.distance)));
5575        }
5576        uv.push(Vec3::new(foot.u, foot.v, 0.0));
5577        // A pole of the surface: its points do not move with the first
5578        // parameter there.
5579        let aside = if foot.u + step <= u1 { foot.u + step } else { foot.u - step };
5580        let moved = frag(surface.evaluate(aside, foot.v), "point")?.sub(frag(surface.evaluate(foot.u, foot.v), "point")?).length();
5581        poles.push(moved <= 1e-9 * (1.0 + x.length()));
5582    }
5583    continue_pole_angles(&mut uv, &ts, &poles)?;
5584    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "projected_pcurve")?;
5585    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
5586}
5587
5588type Signature = (Vec<(usize, usize, bool)>, Vec<(bool, Vec<(usize, bool)>)>, Vec<(usize, bool)>);
5589
5590fn signature(split: &Split) -> Result<Signature, KernelRefusal> {
5591    Ok((
5592        split.curves.iter().map(|c| (c.start, c.end, c.degenerate)).collect(),
5593        split.caps.iter().map(|cap| (cap.front, cap.coedges.iter().map(|&(c, f, _)| (c, f)).collect())).collect(),
5594        split.grazing()?,
5595    ))
5596}
5597
5598fn lofted(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<BrepSolid, KernelRefusal> {
5599    let split_at = |t: f64| -> Result<Split, KernelRefusal> {
5600        let mut frozen = *screw;
5601        frozen.frozen = Some(t);
5602        split_revolved(&frozen, origin, axis, radial, meridian)
5603    };
5604    let mut lambdas: Vec<f64> = (0..=LOFT_SAMPLES).map(|i| i as f64 / LOFT_SAMPLES as f64).collect();
5605    // World samples of grazing curve c at time t, in the wall's direction.
5606    let samples_of = |split: &Split, c: usize, back_forward: bool, t: f64| -> Result<Vec<Vec3>, KernelRefusal> {
5607        let Some(list) = &split.curves[c].samples else {
5608            return Err(refuse("loft_samples", "a grazing curve has no exact samples to loft".into()));
5609        };
5610        let mut world: Vec<Vec3> = list.iter().map(|&x| screw.apply(t, x)).collect();
5611        if back_forward {
5612            world.reverse();
5613        }
5614        Ok(world)
5615    };
5616    // Time breaks start even and are refined only in the spans whose middle
5617    // misses, by the quintic's h^6 error: a smooth stretch of the motion keeps
5618    // its long spans (doubling everywhere tripled the wall for one bend).
5619    let mut fractions: Vec<f64> = (0..=15).map(|j| j as f64 / 15.0).collect();
5620    loop {
5621        let count = fractions.len() - 1;
5622        // The walls' second parameter runs 0 -> 1 over the motion.
5623        let times: Vec<f64> = fractions.iter().map(|&f| if f == 1.0 { screw.t1 } else { screw.t0 + (screw.t1 - screw.t0) * f }).collect();
5624        // Only the end poses' caps are built: the interior splits are read
5625        // for their curves and structure, their caps' pcurves skipped
5626        // (`BREP_SWEEP_LOFT_SPLITS_LEAN`).
5627        let lean = loft_splits_lean_on();
5628        let splits: Vec<Split> = times
5629            .iter()
5630            .enumerate()
5631            .map(|(j, &t)| if lean && j != 0 && j != count { with_pcurves_skipped(|| split_at(t)) } else { split_at(t) })
5632            .collect::<Result<_, _>>()?;
5633        if splits.iter().any(|split| !split.slides.is_empty() || !split.slide_sides.is_empty()) {
5634            return Err(refuse("loft_structure", "a flat end that slides within its own plane is not lofted".into()));
5635        }
5636        let shape = signature(&splits[0])?;
5637        for split in &splits[1..] {
5638            if signature(split)? != shape {
5639                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5640            }
5641        }
5642        let grazing = shape.2.clone();
5643        if grazing.is_empty() {
5644            return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
5645        }
5646        let scale = splits[0].scale + screw.extent;
5647        let target = LOFT_TARGET * scale;
5648        // Walls: per grazing curve, rows along it at each time, then across time.
5649        let mut walls = Vec::with_capacity(grazing.len());
5650        // Every wall's exact samples at every time.
5651        let mut sampled: Vec<Vec<Vec<Vec3>>> = Vec::with_capacity(grazing.len());
5652        for &(c, back_forward) in &grazing {
5653            let mut at_times = Vec::with_capacity(times.len());
5654            for (j, split) in splits.iter().enumerate() {
5655                let points = samples_of(split, c, back_forward, times[j])?;
5656                if points.len() != lambdas.len() {
5657                    if points.len() < 13 || points.len() % 2 == 0 {
5658                        return Err(refuse("loft_samples", "a grazing curve's exact samples cannot be lofted".into()));
5659                    }
5660                    lambdas = (0..points.len()).map(|i| i as f64 / (points.len() - 1) as f64).collect();
5661                }
5662                at_times.push(points);
5663            }
5664            sampled.push(at_times);
5665        }
5666        // A row through every `stride`-th sample: its worst miss at the
5667        // samples it leaves out, over every wall and time.
5668        let thinned = |stride: usize| -> Result<f64, KernelRefusal> {
5669            let coarse_lambdas: Vec<f64> = lambdas.iter().step_by(stride).copied().collect();
5670            let mut worst = 0.0f64;
5671            for at_times in &sampled {
5672                for points in at_times {
5673                    let coarse_points: Vec<Vec3> = points.iter().step_by(stride).copied().collect();
5674                    let coarse = frag(crate::interpolate_curve(&coarse_points, 5, &coarse_lambdas), "loft_row")?;
5675                    for (i, x) in points.iter().enumerate().filter(|(i, _)| i % stride != 0) {
5676                        worst = worst.max(frag(coarse.evaluate(lambdas[i]), "loft_row")?.sub(*x).length());
5677                    }
5678                }
5679            }
5680            Ok(worst)
5681        };
5682        // Each wall's rows pass through as few of its samples as hold every
5683        // exact sample within a quarter of the target, at every time (a loop
5684        // smooth but for one sharp bend needs its samples only there, and the
5685        // wall's size is what the solid's users pay for): from every 16th,
5686        // a stretch that misses at a sample it leaves out gets its middle one.
5687        let spans = lambdas.len() - 1;
5688        let mut kept: Vec<Vec<usize>> = Vec::with_capacity(sampled.len());
5689        for at_times in &sampled {
5690            let coarsest = if spans % 16 == 0 && spans >= 96 { 16 } else { 1 };
5691            let mut subset: Vec<usize> = (0..=spans).step_by(coarsest).collect();
5692            loop {
5693                let subset_lambdas: Vec<f64> = subset.iter().map(|&i| lambdas[i]).collect();
5694                let mut misses = vec![0.0f64; subset.len() - 1];
5695                for points in at_times {
5696                    let row_points: Vec<Vec3> = subset.iter().map(|&i| points[i]).collect();
5697                    let row = frag(crate::interpolate_curve(&row_points, 5, &subset_lambdas), "loft_row")?;
5698                    for k in 0..subset.len() - 1 {
5699                        for i in subset[k] + 1..subset[k + 1] {
5700                            misses[k] = misses[k].max(frag(row.evaluate(lambdas[i]), "loft_row")?.sub(points[i]).length());
5701                        }
5702                    }
5703                }
5704                let mut refined = Vec::with_capacity(2 * subset.len());
5705                for k in 0..subset.len() - 1 {
5706                    refined.push(subset[k]);
5707                    if misses[k] > 0.25 * target {
5708                        refined.push((subset[k] + subset[k + 1]) / 2);
5709                    }
5710                }
5711                refined.push(spans);
5712                if refined.len() == subset.len() {
5713                    break;
5714                }
5715                subset = refined;
5716            }
5717            kept.push(subset);
5718        }
5719        // Where a wall keeps neighbouring samples there is none left out
5720        // between them to measure at: a row passes through its samples, and
5721        // between them it is as good as the loop is smooth at that spacing.
5722        // Its miss there is estimated from the rows through every other
5723        // sample, scaled by the quintic's 2^-6.
5724        let dense = kept.iter().any(|subset| subset.windows(2).any(|pair| pair[1] == pair[0] + 1));
5725        let between = if dense { thinned(2)? / 64.0 } else { 0.0 };
5726        for (index, &(c, back_forward)) in grazing.iter().enumerate() {
5727            let row_lambdas: Vec<f64> = kept[index].iter().map(|&i| lambdas[i]).collect();
5728            let mut rows: Vec<NurbsCurve> = Vec::with_capacity(times.len());
5729            for points in &sampled[index] {
5730                let row_points: Vec<Vec3> = kept[index].iter().map(|&i| points[i]).collect();
5731                rows.push(frag(crate::interpolate_curve(&row_points, 5, &row_lambdas), "loft_row")?);
5732            }
5733            let knots_u = rows[0].knots.clone();
5734            let mut net: Vec<Vec<Vec4>> = Vec::with_capacity(rows[0].control_points.len());
5735            let mut knots_v = Vec::new();
5736            for k in 0..rows[0].control_points.len() {
5737                let column: Vec<Vec3> = rows.iter().map(|row| row.control_points[k].point()).collect::<Result<_, _>>().map_err(|e| refuse("loft", e))?;
5738                let across = frag(crate::interpolate_curve(&column, 5, &fractions), "loft_column")?;
5739                knots_v = across.knots.clone();
5740                net.push(across.control_points.clone());
5741            }
5742            let surface = frag(NurbsSurface::new(5, 5, knots_u, knots_v, net), "loft_wall")?;
5743            walls.push((c, back_forward, surface, rows.first().cloned().expect("rows"), rows.last().cloned().expect("rows")));
5744        }
5745        if between > target {
5746            return Err(refuse("loft_rows", format!("the lofted wall's rows stay about {between:e} off the grazing loop between its samples")));
5747        }
5748        // Against the exact loop in the middle of each span, every sample.
5749        let mut misses = vec![0.0f64; count];
5750        for j in 0..count {
5751            let t = 0.5 * (times[j] + times[j + 1]);
5752            let fraction = 0.5 * (fractions[j] + fractions[j + 1]);
5753            let split = if lean { with_pcurves_skipped(|| split_at(t))? } else { split_at(t)? };
5754            if signature(&split)? != shape {
5755                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5756            }
5757            for (c, back_forward, surface, _, _) in &walls {
5758                let exact = samples_of(&split, *c, *back_forward, t)?;
5759                for (i, x) in exact.iter().enumerate() {
5760                    misses[j] = misses[j].max(frag(surface.evaluate(lambdas[i], fraction), "loft_check")?.sub(*x).length());
5761                }
5762            }
5763        }
5764        let worst = misses.iter().copied().fold(0.0f64, f64::max);
5765        if worst > target {
5766            if count > 2000 {
5767                return Err(refuse("loft_accuracy", format!("the lofted wall stays {worst:e} off the grazing loop")));
5768            }
5769            // A span missing by more than half the target is cut into
5770            // ceil((e / (target / 4))^(1/6)) pieces; the rest stay.
5771            let mut refined = Vec::with_capacity(2 * fractions.len());
5772            for j in 0..count {
5773                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 };
5774                for k in 0..pieces {
5775                    refined.push(fractions[j] + (fractions[j + 1] - fractions[j]) * k as f64 / pieces as f64);
5776                }
5777            }
5778            refined.push(1.0);
5779            fractions = refined;
5780            continue;
5781        }
5782        // Each K corner's path through the sample times.
5783        let mut paths: HashMap<usize, Vec<Vec3>> = HashMap::new();
5784        for &(c, _) in &grazing {
5785            for r in [splits[0].curves[c].start, splits[0].curves[c].end] {
5786                paths.entry(r).or_insert_with(|| splits.iter().zip(&times).map(|(split, &t)| screw.apply(t, split.points[r])).collect());
5787            }
5788        }
5789        return assemble_lofted(screw, &splits[0], &splits[count], &walls, &fractions, &paths, target);
5790    }
5791}
5792
5793/// Refuse a lofted wall with an edge of regression: across one the wall's
5794/// normal turns over, and the band beside it lies inside nearby poses (the
5795/// sweep folds within a few degrees of the motion, which no probe walk is
5796/// dense enough to be sure of seeing). Normals are compared between
5797/// neighbours on every time row and between rows, outside what the end trims
5798/// take away (`removed`, chart rings) and a few columns off its edge (a fold
5799/// line meets the end at the cut's own ends). `fit`: how near the wall keeps
5800/// to its exact loop (a length).
5801fn wall_regular(surface: &NurbsSurface, fractions: &[f64], removed: &[&[[f64; 2]]], fit: f64) -> Result<(), KernelRefusal> {
5802    const COLUMNS: usize = 4 * LOFT_SAMPLES;
5803    let mut rows: Vec<f64> = Vec::with_capacity(2 * fractions.len());
5804    for j in 0..fractions.len() {
5805        rows.push(fractions[j]);
5806        if j + 1 < fractions.len() {
5807            rows.push(0.5 * (fractions[j] + fractions[j + 1]));
5808        }
5809    }
5810    let normal = |u: f64, v: f64| -> Result<Option<Vec3>, KernelRefusal> {
5811        let h = 1e-6;
5812        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));
5813        let du = frag(surface.evaluate(ub, v), "regular")?.sub(frag(surface.evaluate(ua, v), "regular")?).scale(1.0 / (ub - ua));
5814        let dv = frag(surface.evaluate(u, vb), "regular")?.sub(frag(surface.evaluate(u, va), "regular")?).scale(1.0 / (vb - va));
5815        // Where the wall's two directions all but line up, or it is no
5816        // wider than its own fit's ripple (a corner it pinches to), it has
5817        // no normal to speak of: the fit's noise would turn it.
5818        let cross = du.cross(dv);
5819        if cross.length() <= 1e-6 * du.length() * dv.length() || du.length().min(dv.length()) <= 1e3 * fit {
5820            return Ok(None);
5821        }
5822        Ok(cross.normalized().ok())
5823    };
5824    // Each trimmed-away ring's box, grown by the reach of `near_ring` and a hair: a point
5825    // outside it is neither inside the ring (a closed polygon) nor that near it, so the box
5826    // answers for it as the ring's own tests would.
5827    let reach = 4.0 / COLUMNS as f64;
5828    let boxes: Vec<[f64; 4]> = removed
5829        .iter()
5830        .map(|ring| {
5831            let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
5832            for p in ring.iter() {
5833                lo = [lo[0].min(p[0]), lo[1].min(p[1])];
5834                hi = [hi[0].max(p[0]), hi[1].max(p[1])];
5835            }
5836            let pad = reach * (1.0 + 1e-9) + 1e-12;
5837            [lo[0] - pad, hi[0] + pad, lo[1] - pad, hi[1] + pad]
5838        })
5839        .collect();
5840    let mut previous: Option<Vec<Option<Vec3>>> = None;
5841    for &v in &rows {
5842        // What a trim takes away is not part of the body.
5843        let row: Vec<Option<Vec3>> = (0..=COLUMNS)
5844            .map(|i| {
5845                let u = i as f64 / COLUMNS as f64;
5846                let taken = removed.iter().zip(&boxes).any(|(ring, b)| {
5847                    !(u < b[0] || u > b[1] || v < b[2] || v > b[3]) && (inside_ring(ring, [u, v]) || near_ring(ring, [u, v], reach))
5848                });
5849                if taken { Ok(None) } else { normal(u, v) }
5850            })
5851            .collect::<Result<_, _>>()?;
5852        for i in 0..COLUMNS {
5853            if let (Some(a), Some(b)) = (row[i], row[i + 1]) {
5854                if a.dot(b) < -0.5 {
5855                    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)));
5856                }
5857            }
5858            if let Some(Some(Some(a))) = previous.as_ref().map(|p| p.get(i).copied()) {
5859                if let Some(b) = row[i] {
5860                    if a.dot(b) < -0.5 {
5861                        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)));
5862                    }
5863                }
5864            }
5865        }
5866        previous = Some(row);
5867    }
5868    Ok(())
5869}
5870
5871/// A stretch of a wall's row at v, from u = a to u = b, as an edge's curve.
5872fn row_piece(wall: &NurbsSurface, v: f64, a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
5873    let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5874    let along: Vec<Vec3> = ts.iter().map(|&s| frag(wall.evaluate((a + (b - a) * s).clamp(0.0, 1.0), v), "wall")).collect::<Result<_, _>>()?;
5875    frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
5876}
5877
5878/// A wall's end row in pieces around its trims and breaks (one more than the
5879/// spans), at v.
5880fn row_pieces(wall: &NurbsSurface, v: f64, spans: &[TrimSpan]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
5881    let mut pieces = Vec::with_capacity(spans.len() + 1);
5882    let mut from = 0.0;
5883    for span in spans {
5884        pieces.push(row_piece(wall, v, from, span.lambdas[0])?);
5885        from = span.lambdas[1];
5886    }
5887    pieces.push(row_piece(wall, v, from, 1.0)?);
5888    Ok(pieces)
5889}
5890
5891/// The wall over u ∈ [a, b] only, in the same parameters.
5892/// Can `pcurve` (in a wall's chart) meet the split segment u = tip.u, v in
5893/// [v_lo, v_hi], anywhere but at the tip itself? A pcurve that ENDS at the
5894/// tip (a side of the double curve) touches it there: a short stub at that end
5895/// must leave the tip into one side of the line or away from the segment, and
5896/// the rest is tested. Every other piece is decided on the convex hull of its
5897/// control points (positive weights), halved where a hull straddles the
5898/// segment; one still straddling after 24 halvings counts as meeting it.
5899fn hull_meets_segment(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64) -> Result<bool, KernelRefusal> {
5900    let uv = |p: &Vec4| [p.x / p.w, p.y / p.w];
5901    let near_tip = |p: [f64; 2]| (p[0] - tip[0]).abs() <= 1e-9 && (p[1] - tip[1]).abs() <= 1e-9;
5902    let (first, last) = (uv(&pcurve.control_points[0]), uv(&pcurve.control_points[pcurve.control_points.len() - 1]));
5903    if !(near_tip(first) || near_tip(last)) {
5904        return hull_straddles(pcurve, tip, v_lo, v_hi, 0);
5905    }
5906    if near_tip(first) && near_tip(last) {
5907        return Ok(true);
5908    }
5909    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5910    let at = if near_tip(first) { d0 + 1e-3 * (d1 - d0) } else { d1 - 1e-3 * (d1 - d0) };
5911    let (a, b) = frag(pcurve.split(at), "split")?;
5912    let (stub, rest) = if near_tip(first) { (a, b) } else { (b, a) };
5913    let side: Vec<f64> = stub.control_points.iter().map(|p| uv(p)[0] - tip[0]).collect();
5914    let one_side = side.iter().all(|d| *d >= -1e-12) || side.iter().all(|d| *d <= 1e-12);
5915    // The segment runs from the tip towards the far row: away is the other way.
5916    let segment_below = v_lo < tip[1] - 1e-12;
5917    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 });
5918    if !(one_side || away) {
5919        return Ok(true);
5920    }
5921    hull_straddles(&rest, tip, v_lo, v_hi, 0)
5922}
5923
5924fn hull_straddles(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64, depth: usize) -> Result<bool, KernelRefusal> {
5925    let points: Vec<[f64; 2]> = pcurve.control_points.iter().map(|p| [p.x / p.w, p.y / p.w]).collect();
5926    let (u_min, u_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[0]), hi.max(p[0])));
5927    let (w_min, w_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[1]), hi.max(p[1])));
5928    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 {
5929        return Ok(false);
5930    }
5931    if depth >= 24 {
5932        return Ok(true);
5933    }
5934    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5935    match pcurve.split(0.5 * (d0 + d1)) {
5936        Ok((a, b)) => Ok(hull_straddles(&a, tip, v_lo, v_hi, depth + 1)? || hull_straddles(&b, tip, v_lo, v_hi, depth + 1)?),
5937        // Too short to halve: count it as meeting the segment.
5938        Err(_) => Ok(true),
5939    }
5940}
5941
5942/// `BREP_SWEEP_SPLIT_CROSSING` (default on; `=0` off): a lofted wall that
5943/// turns over near one end is split at its swallowtail's point whenever the
5944/// split segment to the far row crosses no trim curve, not only where the
5945/// trimmed row keeps to its side of the tip's u; otherwise the wall stays one
5946/// face carrying its double curve as a slot (one edge used twice), which
5947/// meshes poorly at the slot's tip.
5948fn split_crossing_on() -> bool {
5949    crate::switch!("BREP_SWEEP_SPLIT_CROSSING", true)
5950}
5951
5952fn restrict_u(surface: &NurbsSurface, a: f64, b: f64) -> Result<NurbsSurface, KernelRefusal> {
5953    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5954    if a <= u0 + 1e-12 && b >= u1 - 1e-12 {
5955        return Ok(surface.clone());
5956    }
5957    let columns = surface.control_points[0].len();
5958    let mut knots = Vec::new();
5959    let mut net: Vec<Vec<Vec4>> = Vec::new();
5960    for j in 0..columns {
5961        let line: Vec<Vec4> = surface.control_points.iter().map(|row| row[j]).collect();
5962        let mut curve = frag(NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), line), "restrict")?;
5963        if b < u1 - 1e-12 {
5964            curve = frag(curve.split(b), "restrict")?.0;
5965        }
5966        if a > u0 + 1e-12 {
5967            curve = frag(curve.split(a), "restrict")?.1;
5968        }
5969        if j == 0 {
5970            knots = curve.knots.clone();
5971            net = vec![Vec::with_capacity(columns); curve.control_points.len()];
5972        }
5973        for (i, point) in curve.control_points.iter().enumerate() {
5974            net[i].push(*point);
5975        }
5976    }
5977    frag(NurbsSurface::new(surface.degree_u, surface.degree_v, knots, surface.knots_v.clone(), net), "restrict")
5978}
5979
5980/// One place a wall is cut back where an end pose bulges past it: the wall
5981/// parameter range [λa, λb] along the grazing loop where the trim leaves and
5982/// rejoins it, the cut (from the point at λa to the point at λb, on both the
5983/// wall and the pose), the wall's side of the trim from λa to λb (`chain`),
5984/// the double curve and its swallowtail point if the trim follows one, and
5985/// the part of the wall's chart it takes away (`removed`, (u, v) points
5986/// around it).
5987struct TrimSpan {
5988    lambdas: [f64; 2],
5989    points: [Vec3; 2],
5990    /// None: no cut at all, only a break in the end's row at λa = λb (where
5991    /// a line splitting the wall lands on it).
5992    cut: Option<NurbsCurve>,
5993    chain: Vec<(TrimPiece, bool, NurbsCurve)>,
5994    slot: Option<(NurbsCurve, Vec3)>,
5995    /// The swallowtail's point in the wall's chart (u, v), where the trim
5996    /// follows a double curve.
5997    tip: Option<[f64; 2]>,
5998    removed: Vec<[f64; 2]>,
5999}
6000
6001/// Every place an end pose bulges past one wall, in order along the loop, and
6002/// the loop's pieces around them (one more than the spans).
6003struct EndTrim {
6004    spans: Vec<TrimSpan>,
6005    pieces: Vec<NurbsCurve>,
6006}
6007
6008/// Which edge a piece of a trimmed wall's end runs on: the cut it shares with
6009/// the cap, or the wall's own double curve (both of the slot's sides).
6010#[derive(Clone, Copy, PartialEq, Eq, Debug)]
6011enum TrimPiece {
6012    Cut,
6013    Slot,
6014}
6015
6016/// The cut of a lofted wall (u along the grazing loop, v the motion's time
6017/// fraction) by the pose at its end (`end` 0: v = 0, 1: v = 1), if the pose
6018/// bulges past it, else None.
6019///
6020/// The wall meets the pose along K and leaves it to second order (K grazes),
6021/// so with ε the time fraction from the end, f = d / ε² (d the pose's signed
6022/// distance) is smooth up to the end. The part of the wall inside the pose is
6023/// where f < 0; its boundary is traced as the curve f = 0 from the end and back
6024/// to it. It need not be a graph over u: a tongue of it may run on past where
6025/// it left the end.
6026///
6027/// `fit`: how near the wall keeps to the exact loop (a length).
6028fn end_trim(screw: &Screw, split: &Split, t: f64, wall: &NurbsSurface, end: usize, fit: f64) -> Result<Option<EndTrim>, KernelRefusal> {
6029    let v_of = |e: f64| if end == 1 { 1.0 - e } else { e };
6030    let at = |u: f64, e: f64| -> Result<Vec3, KernelRefusal> { frag(wall.evaluate(u.clamp(0.0, 1.0), v_of(e)), "wall") };
6031    let f = |u: f64, e: f64| -> Result<f64, KernelRefusal> { Ok(split.distance(screw.invert(t, at(u, e)?)) / (e * e)) };
6032    // Below `floor` the walls' fit swamps d / ε².
6033    let floor = 1e-3;
6034    // How far into the motion (as a fraction of it) a trim may reach (a fold
6035    // band can run most of a span); past that the end pose meets a distant
6036    // part of the sweep (`end_trim_deep`).
6037    let window = 0.6;
6038    let noise = 2.0 * fit / (floor * floor);
6039    // Where the wall dips into the pose just off the end.
6040    let n = 2000;
6041    let edge: Vec<f64> = (0..=n).map(|i| f(i as f64 / n as f64, floor)).collect::<Result<_, _>>()?;
6042    // Inside: the stretches where f is negative, those that dip below the
6043    // fit's noise somewhere (a stretch that never does is the fit's own).
6044    let mut inside: Vec<bool> = edge.iter().map(|&x| x < 0.0).collect();
6045    let mut i = 0;
6046    while i <= n {
6047        if !inside[i] {
6048            i += 1;
6049            continue;
6050        }
6051        let mut j = i;
6052        while j < n && inside[j + 1] {
6053            j += 1;
6054        }
6055        if edge[i..=j].iter().all(|&x| x >= -noise) {
6056            for flag in &mut inside[i..=j] {
6057                *flag = false;
6058            }
6059        }
6060        i = j + 1;
6061    }
6062    if !inside.iter().any(|&x| x) {
6063        // Nothing near the end; a pocket deeper in is caught below.
6064        return pierced(&f, floor, window, noise, &[]);
6065    }
6066    if inside[0] || inside[n] || inside[1] || inside[n - 1] {
6067        return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6068    }
6069    // Crossings of the floor line, by bisection between samples of either sign.
6070    let mut crossings: Vec<f64> = Vec::new();
6071    for i in 0..n {
6072        if inside[i] != inside[i + 1] {
6073            let (mut a, mut b) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
6074            let a_inside = inside[i];
6075            for _ in 0..60 {
6076                let mid = 0.5 * (a + b);
6077                if (f(mid, floor)? < 0.0) == a_inside { a = mid } else { b = mid }
6078            }
6079            crossings.push(0.5 * (a + b));
6080        }
6081    }
6082    if crossings.len() % 2 != 0 || crossings.is_empty() {
6083        return Err(refuse("end_trim", "an end pose's bulges past a wall do not pair up".into()));
6084    }
6085    // Trace f = 0 from the first crossing of each pair into the wall until it
6086    // returns to the floor; it must come back at the pair's other crossing.
6087    let gradient = |u: f64, e: f64| -> Result<[f64; 2], KernelRefusal> {
6088        let h = 1e-6;
6089        Ok([(f(u + h, e)? - f(u - h, e)?) / (2.0 * h), (f(u, e + h)? - f(u, e - h)?) / (2.0 * h)])
6090    };
6091    let settle = |mut p: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
6092        for _ in 0..30 {
6093            let value = f(p[0], p[1])?;
6094            let g = gradient(p[0], p[1])?;
6095            let norm = g[0] * g[0] + g[1] * g[1];
6096            if norm == 0.0 {
6097                return Err(refuse("end_trim", "the cut of an end pose has a flat point".into()));
6098            }
6099            p = [p[0] - value * g[0] / norm, p[1] - value * g[1] / norm];
6100            if value.abs() * p[1] * p[1] < 1e-14 * split.scale {
6101                break;
6102            }
6103        }
6104        Ok(p)
6105    };
6106    let step = 1e-3;
6107    let mut cuts: Vec<Vec<[f64; 2]>> = Vec::new();
6108    // Each cut starts at the lowest crossing not yet used and ends at the
6109    // unused one it comes back to.
6110    let mut unused: Vec<f64> = crossings.clone();
6111    while !unused.is_empty() {
6112        let start = unused.remove(0);
6113        let mut points: Vec<[f64; 2]> = vec![[start, floor]];
6114        let mut heading = [0.0, 1.0];
6115        loop {
6116            let last = *points.last().expect("points");
6117            let g = gradient(last[0], last[1])?;
6118            let length = g[0].hypot(g[1]);
6119            let mut tangent = [-g[1] / length, g[0] / length];
6120            if tangent[0] * heading[0] + tangent[1] * heading[1] < 0.0 {
6121                tangent = [-tangent[0], -tangent[1]];
6122            }
6123            let next = settle([last[0] + step * tangent[0], last[1] + step * tangent[1]])?;
6124            if next[1] < floor {
6125                break;
6126            }
6127            if next[0] <= 1e-3 || next[0] >= 1.0 - 1e-3 {
6128                return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6129            }
6130            if next[1] > window {
6131                return Err(refuse("end_trim_deep", "an end pose holds a deep part of a wall".into()));
6132            }
6133            if points.len() > 20_000 {
6134                return Err(refuse("end_trim", "the cut of an end pose does not close".into()));
6135            }
6136            heading = [next[0] - last[0], next[1] - last[1]];
6137            points.push(next);
6138        }
6139        let back = *points.last().expect("points");
6140        let Some(at_end) = unused.iter().position(|&c| (back[0] - c).abs() <= 2.0 * step) else {
6141            return Err(refuse("end_trim", "the cut of an end pose does not come back where it should".into()));
6142        };
6143        let back_at = unused.remove(at_end);
6144        // A dip that never rises off the floor and comes straight back is
6145        // the fit's noise at the end, not a bulge.
6146        if points.len() == 1 && (back_at - start).abs() <= step {
6147            continue;
6148        }
6149        points.push([back_at, floor]);
6150        // Down to the end itself along the cut's direction at the floor (taken
6151        // from the first point clearly above it).
6152        let to_end = |p: [f64; 2], rest: &[[f64; 2]], reversed: bool| -> Result<[f64; 2], KernelRefusal> {
6153            // Along the cut's own tangent there (across the gradient of f), so
6154            // the run to the end continues it smoothly.
6155            let g = gradient(p[0], p[1])?;
6156            if g[0].abs() > 1e-3 * g[1].abs() {
6157                return Ok([p[0] + g[1] / g[0] * p[1], 0.0]);
6158            }
6159            let clear = |q: &&[f64; 2]| q[1] - p[1] > 0.25 * step;
6160            let found = if reversed { rest.iter().rev().find(clear) } else { rest.iter().find(clear) };
6161            Ok(match found {
6162                Some(q) => [p[0] - (q[0] - p[0]) / (q[1] - p[1]) * p[1], 0.0],
6163                None => [p[0], 0.0],
6164            })
6165        };
6166        let count = points.len();
6167        let (first, last) = (to_end(points[0], &points[1..], false)?, to_end(points[count - 1], &points[..count - 1], true)?);
6168        if [first[0], last[0]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
6169            return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6170        }
6171        points.insert(0, first);
6172        points.push(last);
6173        if points[0][0] > points[points.len() - 1][0] {
6174            points.reverse();
6175        }
6176        cuts.push(points);
6177    }
6178    let rings: Vec<&[[f64; 2]]> = cuts.iter().map(|c| c.as_slice()).collect();
6179    pierced(&f, floor, window, noise, &rings)?;
6180    let chart = |p: [f64; 2]| [p[0], v_of(p[1])];
6181    // A curve on the wall through chart points and its pcurve, both on the
6182    // given parameters (normalized to [0, 1]); chart-length parameters by
6183    // default (the wall's own speed collapses near an edge of regression, so
6184    // 3D chord lengths would bunch them).
6185    let chart_lengths = |chart_points: &[[f64; 2]]| -> Vec<f64> {
6186        let mut params = vec![0.0];
6187        for k in 1..chart_points.len() {
6188            let gap = (chart_points[k][0] - chart_points[k - 1][0]).hypot(chart_points[k][1] - chart_points[k - 1][1]);
6189            params.push(params[k - 1] + gap.max(1e-15));
6190        }
6191        params
6192    };
6193    // Returns the curve, its pcurve, and how far the pcurve's image strays
6194    // from the curve between the points.
6195    let curve_through = |chart_points: &[[f64; 2]], params: &[f64], what: &'static str| -> Result<(NurbsCurve, NurbsCurve, f64), KernelRefusal> {
6196        let total = *params.last().expect("params");
6197        let params: Vec<f64> = params.iter().map(|x| x / total).collect();
6198        let world: Vec<Vec3> = chart_points.iter().map(|p| at(p[0], p[1])).collect::<Result<_, _>>()?;
6199        let uv: Vec<Vec3> = chart_points.iter().map(|p| Vec3::new(p[0], v_of(p[1]), 0.0)).collect();
6200        let (curve, pcurve) = (frag(crate::interpolate_curve(&world, 5, &params), what)?, frag(crate::interpolate_curve(&uv, 5, &params), what)?);
6201        // Between the points too: the pcurve's image stays on the curve.
6202        let mut worst = 0.0f64;
6203        for k in 0..params.len() - 1 {
6204            let s = 0.5 * (params[k] + params[k + 1]);
6205            let q = frag(pcurve.evaluate(s), "pcurve")?;
6206            let e = if end == 1 { 1.0 - q.y } else { q.y };
6207            worst = worst.max(at(q.x, e)?.sub(frag(curve.evaluate(s), "curve")?).length());
6208        }
6209        Ok((curve, pcurve, worst))
6210    };
6211    // A trim curve is refined until its pcurve's image is within `fine` of
6212    // it, and taken as near as it gets if within `loose` (a double curve has
6213    // a cusp at its swallowtail's point, where no finer trace helps; a
6214    // tighter bar costs a thin tool many rounds and buys no reader anything).
6215    let (fine, loose) = (1e-7 * split.scale, 1e-7 * split.scale);
6216    let missed = |what: &str| refuse("end_trim", format!("the {what}'s pcurve leaves it between its points however finely it is traced"));
6217    // The cut, refined where its fit misses: a settled point between each
6218    // pair of traced ones (on the stretches run straight to the end, their
6219    // middles).
6220    let cut_through = |mut chart_points: Vec<[f64; 2]>| -> Result<(NurbsCurve, NurbsCurve), KernelRefusal> {
6221        let mut best: Option<(NurbsCurve, NurbsCurve, f64)> = None;
6222        for _ in 0..7 {
6223            let fitted = curve_through(&chart_points, &chart_lengths(&chart_points), "cut")?;
6224            let done = fitted.2 <= fine;
6225            if best.as_ref().map_or(true, |b| fitted.2 < b.2) {
6226                best = Some(fitted);
6227            }
6228            if done {
6229                break;
6230            }
6231            let mut finer = Vec::with_capacity(2 * chart_points.len());
6232            for k in 0..chart_points.len() - 1 {
6233                finer.push(chart_points[k]);
6234                let (p, q) = (chart_points[k], chart_points[k + 1]);
6235                let middle = [0.5 * (p[0] + q[0]), 0.5 * (p[1] + q[1])];
6236                // Below the floor the cut runs straight to the end: split it there as a line.
6237                finer.push(if p[1] >= floor && q[1] >= floor { settle(middle)? } else { middle });
6238            }
6239            finer.push(chart_points[chart_points.len() - 1]);
6240            chart_points = finer;
6241        }
6242        match best {
6243            Some((curve, pcurve, worst)) if worst <= loose => Ok((curve, pcurve)),
6244            _ => Err(missed("cut")),
6245        }
6246    };
6247    let piece = |a: f64, b: f64| -> Result<NurbsCurve, KernelRefusal> {
6248        let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
6249        let along: Vec<Vec3> = ts.iter().map(|&s| at(a + (b - a) * s, 0.0)).collect::<Result<_, _>>()?;
6250        frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
6251    };
6252    // Where the wall turns over near the end (a swallowtail), the cut passes
6253    // through a point of the end's own loop K a second time, on the wall's far
6254    // sheet: there the wall's double curve starts, and the trim follows it to
6255    // the swallowtail's point and back instead of the cut's first stretch.
6256    let span_of = |points: &Vec<[f64; 2]>| -> Result<TrimSpan, KernelRefusal> {
6257        if let Some((k, ua, b)) = double_start(&at, points, floor)? {
6258            // The double curve, traced more finely while its fit misses.
6259            let mut traced: Option<(Vec<[f64; 2]>, Vec<[f64; 2]>, NurbsCurve, NurbsCurve, NurbsCurve, f64)> = None;
6260            for round in 0..5 {
6261                let (a_side, b_side) = double_curve(&at, [ua, 0.0], b, window, 2e-3 / f64::from(1u32 << round))?;
6262                // Both sides on the continuation's own arc length, so the double
6263                // curve and its two pcurves share one parameter.
6264                let mut sigma = vec![0.0];
6265                for k in 1..a_side.len() {
6266                    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]));
6267                    sigma.push(sigma[k - 1] + step.max(1e-15));
6268                }
6269                let ((slot, pa, miss_a), (_, pb, miss_b)) = (curve_through(&a_side, &sigma, "double_curve")?, curve_through(&b_side, &sigma, "double_curve")?);
6270                let worst = miss_a.max(miss_b);
6271                if traced.as_ref().map_or(true, |t| worst < t.5) {
6272                    traced = Some((a_side, b_side, slot, pa, pb, worst));
6273                }
6274                if worst <= fine {
6275                    break;
6276                }
6277            }
6278            let Some((a_side, b_side, slot, pa, pb, _)) = traced.filter(|t| t.5 <= loose) else { return Err(missed("double curve")) };
6279            // The cut keeps the stretch from the far sheet's point to its end away
6280            // from where the double curve leaves K.
6281            let low = ua < points[0][0];
6282            if !low && ua <= points[points.len() - 1][0] {
6283                return Err(refuse("end_trim", "the double curve of a wall leaves its end inside the cut".into()));
6284            }
6285            let mut kept: Vec<[f64; 2]> = if low { points[k..].to_vec() } else { points[..=k].to_vec() };
6286            if low { kept[0] = b } else { *kept.last_mut().expect("kept") = b }
6287            let (cut, cut_pcurve) = cut_through(kept.clone())?;
6288            let tip = at(a_side[a_side.len() - 1][0], a_side[a_side.len() - 1][1])?;
6289            // The wall's side of the trim from the low end to the high one.
6290            let chain = if low {
6291                vec![(TrimPiece::Slot, true, pa), (TrimPiece::Slot, false, frag(pb.reversed(), "reversed")?), (TrimPiece::Cut, true, cut_pcurve)]
6292            } else {
6293                vec![(TrimPiece::Cut, true, cut_pcurve), (TrimPiece::Slot, true, pb), (TrimPiece::Slot, false, frag(pa.reversed(), "reversed")?)]
6294            };
6295            let lambdas = if low { [ua, points[points.len() - 1][0]] } else { [points[0][0], ua] };
6296            let mut removed: Vec<[f64; 2]> = Vec::new();
6297            if low {
6298                removed.extend(a_side.iter().map(|&p| chart(p)));
6299                removed.extend(b_side.iter().rev().map(|&p| chart(p)));
6300                removed.extend(kept.iter().map(|&p| chart(p)));
6301            } else {
6302                removed.extend(kept.iter().map(|&p| chart(p)));
6303                removed.extend(b_side.iter().map(|&p| chart(p)));
6304                removed.extend(a_side.iter().rev().map(|&p| chart(p)));
6305            }
6306            // Everything the end pose holds must be in what goes.
6307            let dropped: Vec<[f64; 2]> = if low { points[..k].to_vec() } else { points[k + 1..].to_vec() };
6308            for p in dropped.iter().filter(|p| p[1] > 2.0 * floor && (p[0] - b[0]).hypot(p[1] - b[1]) > 5e-3) {
6309                if !inside_ring(&removed, chart(*p)) {
6310                    return Err(refuse("end_trim", "the cut of an end pose leaves the part of the wall its double curve takes away".into()));
6311                }
6312            }
6313            let points3 = [at(lambdas[0], 0.0)?, at(lambdas[1], 0.0)?];
6314            // The double curve's sides part about its end: one keeps to
6315            // each side of the swallowtail's point along the loop, so a
6316            // line through that point splits the wall between them.
6317            let tip_chart = chart(a_side[a_side.len() - 1]);
6318            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)));
6319            let ((a_lo, a_hi), (b_lo, b_hi)) = (side(&a_side), side(&b_side));
6320            let parted = (a_lo >= -1e-9 && b_hi <= 1e-9) || (a_hi <= 1e-9 && b_lo >= -1e-9);
6321            if !parted {
6322                return Err(refuse("end_trim", "the two sides of a wall's double curve do not keep to either side of its end".into()));
6323            }
6324            return Ok(TrimSpan { lambdas, points: points3, cut: Some(cut), chain, slot: Some((slot, tip)), tip: Some(tip_chart), removed });
6325        }
6326        let (cut, wall_pcurve) = cut_through(points.clone())?;
6327        let (la, lb) = (points[0][0], points[points.len() - 1][0]);
6328        let removed: Vec<[f64; 2]> = points.iter().map(|&p| chart(p)).collect();
6329        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 })
6330    };
6331    if cuts.is_empty() {
6332        return pierced(&f, floor, window, noise, &[]);
6333    }
6334    let mut spans = Vec::with_capacity(cuts.len());
6335    for points in &cuts {
6336        spans.push(span_of(points)?);
6337    }
6338    spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
6339    // A trim wholly inside what another takes away adds nothing (a bulge of
6340    // the end pose inside a swallowtail's slot).
6341    let edge_row = v_of(0.0);
6342    let within = |inner: &TrimSpan, outer: &TrimSpan| -> bool {
6343        inner.lambdas[0] >= outer.lambdas[0]
6344            && inner.lambdas[1] <= outer.lambdas[1]
6345            && 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))
6346    };
6347    let mut k = 0;
6348    while k < spans.len() {
6349        if (0..spans.len()).any(|j| j != k && within(&spans[k], &spans[j])) {
6350            spans.remove(k);
6351        } else {
6352            k += 1;
6353        }
6354    }
6355    for pair in spans.windows(2) {
6356        if pair[0].lambdas[1] >= pair[1].lambdas[0] {
6357            return Err(refuse("end_trim", "an end pose's trims of a wall overlap".into()));
6358        }
6359    }
6360    let mut pieces = Vec::with_capacity(spans.len() + 1);
6361    let mut from = 0.0;
6362    for span in &spans {
6363        pieces.push(piece(from, span.lambdas[0])?);
6364        from = span.lambdas[1];
6365    }
6366    pieces.push(piece(from, 1.0)?);
6367    Ok(Some(EndTrim { spans, pieces }))
6368}
6369
6370
6371
6372/// Is q within `reach` of the closed polygon `ring`'s sides?
6373fn near_ring(ring: &[[f64; 2]], q: [f64; 2], reach: f64) -> bool {
6374    (0..ring.len()).any(|k| {
6375        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6376        let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
6377        let length = dx * dx + dy * dy;
6378        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 };
6379        (q[0] - a[0] - s * dx).hypot(q[1] - a[1] - s * dy) < reach
6380    })
6381}
6382
6383/// Is q inside the closed polygon `ring` (its last point joins its first)?
6384fn inside_ring(ring: &[[f64; 2]], q: [f64; 2]) -> bool {
6385    let mut crossings = 0;
6386    for k in 0..ring.len() {
6387        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6388        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]) {
6389            crossings += 1;
6390        }
6391    }
6392    crossings % 2 == 1
6393}
6394
6395/// The point of an end pose's cut (chart points (u, ε), ε the time fraction
6396/// from the end) that lies on the end's own loop K a second time, away from
6397/// the cut's ends: (its index along the cut, the loop parameter u of the point
6398/// of K it meets, and the refined (u, ε) on the cut), if there is one.
6399fn double_start(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, points: &[[f64; 2]], floor: f64) -> Result<Option<(usize, f64, [f64; 2])>, KernelRefusal> {
6400    let n = 4000;
6401    let row: Vec<Vec3> = (0..=n).map(|i| at(i as f64 / n as f64, 0.0)).collect::<Result<_, _>>()?;
6402    let scale = row.iter().fold(0.0f64, |m, p| m.max(p.sub(row[0]).length())).max(1e-300);
6403    let mut best: Option<(f64, usize, usize)> = None;
6404    for (k, p) in points.iter().enumerate() {
6405        if p[1] < 4.0 * floor {
6406            continue;
6407        }
6408        let x = at(p[0], p[1])?;
6409        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 });
6410        // The cut nears K at its own ends in proportion to ε; the second
6411        // meeting is where that ratio drops to nothing.
6412        if best.map_or(true, |b| d / p[1] < b.0 / points[b.1][1]) {
6413            best = Some((d, k, i));
6414        }
6415    }
6416    let Some((distance, k, i)) = best else { return Ok(None) };
6417    // Coarse: the cut's points are a few thousandths of the chart apart.
6418    if distance > 5e-3 * scale {
6419        return Ok(None);
6420    }
6421    // Newton on at(b) = at(u, 0) for (b_u, b_ε, u).
6422    let mut x = [points[k][0], points[k][1], i as f64 / n as f64];
6423    let h = 1e-7;
6424    for _ in 0..40 {
6425        let g = at(x[0], x[1])?.sub(at(x[2], 0.0)?);
6426        if g.length() < 1e-13 * scale {
6427            // Not the trivial meeting of the end row with itself.
6428            if x[1] < 2.0 * floor || !(0.0..=1.0).contains(&x[0]) || !(0.0..=1.0).contains(&x[2]) {
6429                return Ok(None);
6430            }
6431            return Ok(Some((k, x[2], [x[0], x[1]])));
6432        }
6433        let c0 = at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h);
6434        let c1 = at(x[0], x[1] + h)?.sub(at(x[0], x[1] - h)?).scale(0.5 / h);
6435        let c2 = at(x[2] + h, 0.0)?.sub(at(x[2] - h, 0.0)?).scale(-0.5 / h);
6436        let det = c0.dot(c1.cross(c2));
6437        if det.abs() < 1e-300 {
6438            break;
6439        }
6440        // Cramer's rule for [c0 c1 c2] d = -g.
6441        let r = g.scale(-1.0);
6442        let d = [r.dot(c1.cross(c2)) / det, c0.dot(r.cross(c2)) / det, c0.dot(c1.cross(r)) / det];
6443        x = [x[0] + d[0], x[1] + d[1], x[2] + d[2]];
6444    }
6445    if distance < 1e-6 * scale {
6446        return Err(refuse("end_trim", "an end pose's cut meets its own loop, but not exactly enough to follow".into()));
6447    }
6448    Ok(None)
6449}
6450
6451/// The double curve of a wall from where it leaves the end (a, on the end's
6452/// loop) and its partner b on the far sheet, traced by continuation of
6453/// at(a) = at(b) in (u, ε) for both, to the swallowtail point where the two
6454/// sides meet. Returns both sides' chart points, ending at the same point.
6455fn 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> {
6456    let h = 1e-7;
6457    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);
6458    let jacobian = |x: [f64; 4]| -> Result<[Vec3; 4], KernelRefusal> {
6459        Ok([
6460            at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h),
6461            at(x[0], x[1] + h)?.sub(at(x[0], (x[1] - h).max(0.0))?).scale(1.0 / (h + x[1].min(h))),
6462            at(x[2] + h, x[3])?.sub(at(x[2] - h, x[3])?).scale(-0.5 / h),
6463            at(x[2], x[3] + h)?.sub(at(x[2], (x[3] - h).max(0.0))?).scale(-1.0 / (h + x[3].min(h))),
6464        ])
6465    };
6466    let residual = |x: [f64; 4]| -> Result<Vec3, KernelRefusal> { Ok(at(x[0], x[1])?.sub(at(x[2], x[3])?)) };
6467    // The null direction of the 3x4 Jacobian: its signed 3x3 minors.
6468    let null = |j: &[Vec3; 4]| -> [f64; 4] {
6469        let minor = |p: usize, q: usize, r: usize| j[p].dot(j[q].cross(j[r]));
6470        let n = [minor(1, 2, 3), -minor(0, 2, 3), minor(0, 1, 3), -minor(0, 1, 2)];
6471        let length = n.iter().map(|x| x * x).sum::<f64>().sqrt().max(1e-300);
6472        [n[0] / length, n[1] / length, n[2] / length, n[3] / length]
6473    };
6474    // Minimum-norm Newton back onto at(a) = at(b).
6475    let correct = |mut x: [f64; 4]| -> Result<Option<[f64; 4]>, KernelRefusal> {
6476        for _ in 0..30 {
6477            let g = residual(x)?;
6478            if g.length() < 1e-13 * scale {
6479                return Ok(Some(x));
6480            }
6481            let j = jacobian(x)?;
6482            // J Jᵀ y = -g, step = Jᵀ y.
6483            let mut m = [[0.0; 3]; 3];
6484            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]];
6485            for p in 0..3 {
6486                for q in 0..3 {
6487                    m[p][q] = (0..4).map(|c| rows[p][c] * rows[q][c]).sum();
6488                }
6489            }
6490            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]);
6491            if det.abs() < 1e-300 {
6492                return Ok(None);
6493            }
6494            let r = [-g.x, -g.y, -g.z];
6495            let solve = |col: usize| -> f64 {
6496                let mut a = m;
6497                for p in 0..3 {
6498                    a[p][col] = r[p];
6499                }
6500                (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
6501            };
6502            let y = [solve(0), solve(1), solve(2)];
6503            for c in 0..4 {
6504                x[c] += (0..3).map(|p| rows[p][c] * y[p]).sum::<f64>();
6505            }
6506        }
6507        Ok(None)
6508    };
6509    let mut x = [a[0], a[1], b[0], b[1]];
6510    let mut a_side = vec![a];
6511    let mut b_side = vec![b];
6512    let mut heading: Option<[f64; 4]> = None;
6513    loop {
6514        let separation = (x[0] - x[2]).hypot(x[1] - x[3]);
6515        if separation < 3.0 * step && a_side.len() > 2 {
6516            let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6517            a_side.push(tip);
6518            b_side.push(tip);
6519            return Ok((a_side, b_side));
6520        }
6521        let mut t = null(&jacobian(x)?);
6522        let reference = heading.unwrap_or([0.0, 1.0, 0.0, 0.0]);
6523        if (0..4).map(|c| t[c] * reference[c]).sum::<f64>() < 0.0 {
6524            t = [-t[0], -t[1], -t[2], -t[3]];
6525        }
6526        let mut next = None;
6527        let mut length = step;
6528        for _ in 0..6 {
6529            let guess = [x[0] + length * t[0], x[1] + length * t[1], x[2] + length * t[2], x[3] + length * t[3]];
6530            if let Some(y) = correct(guess)? {
6531                next = Some(y);
6532                break;
6533            }
6534            length *= 0.5;
6535        }
6536        let Some(y) = next else {
6537            // Near the swallowtail's point the two sheets turn tangent and
6538            // Newton gives out; close there if the sides are that near.
6539            if separation < 2e-2 && a_side.len() > 2 {
6540                let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6541                a_side.push(tip);
6542                b_side.push(tip);
6543                return Ok((a_side, b_side));
6544            }
6545            return Err(refuse("end_trim", format!("the double curve of a wall cannot be followed (sides {separation:e} apart)")));
6546        };
6547        if [y[0], y[2]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
6548            return Err(refuse("end_trim_corner", DOUBLE_CURVE_CORNER.into()));
6549        }
6550        if y[1] > window || y[3] > window || y[1] < 0.0 || y[3] < 0.0 {
6551            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())));
6552        }
6553        if a_side.len() > 20_000 {
6554            return Err(refuse("end_trim", "the double curve of a wall does not close".into()));
6555        }
6556        heading = Some([y[0] - x[0], y[1] - x[1], y[2] - x[2], y[3] - x[3]]);
6557        x = y;
6558        a_side.push([x[0], x[1]]);
6559        b_side.push([x[2], x[3]]);
6560    }
6561}
6562
6563/// Refuse a wall the end pose holds a part of that no cut encloses: a pocket
6564/// of the wall inside the pose away from the end.
6565fn pierced(
6566    f: &dyn Fn(f64, f64) -> Result<f64, KernelRefusal>,
6567    floor: f64,
6568    window: f64,
6569    noise: f64,
6570    cuts: &[&[[f64; 2]]],
6571) -> Result<Option<EndTrim>, KernelRefusal> {
6572    let enclosed = |q: [f64; 2]| -> bool { cuts.iter().any(|ring| inside_ring(ring, q)) };
6573    for i in 1..200 {
6574        for j in 1..=40 {
6575            let (u, e) = (i as f64 / 200.0, floor + (window - floor) * (j as f64 / 40.0).powi(2));
6576            // d itself against the fit's noise: f grows as 1 / ε² near the end.
6577            if f(u, e)? * e * e < -noise * floor * floor && !enclosed([u, e]) {
6578                return Err(refuse("end_trim_deep", "an end pose holds a part of a wall away from its end".into()));
6579            }
6580        }
6581    }
6582    Ok(None)
6583}
6584
6585#[allow(clippy::too_many_arguments)]
6586fn assemble_lofted(
6587    screw: &Screw,
6588    first: &Split,
6589    last: &Split,
6590    walls: &[(usize, bool, NurbsSurface, NurbsCurve, NurbsCurve)],
6591    times: &[f64],
6592    paths: &HashMap<usize, Vec<Vec3>>,
6593    fit: f64,
6594) -> Result<BrepSolid, KernelRefusal> {
6595    let mut shell = Shell::new();
6596    let ends = [(first, screw.t0), (last, screw.t1)];
6597    // Where an end pose bulges past a wall near its grazing loop (a saddle side
6598    // curving past the wall it touches), cut the wall back to where it
6599    // re-enters the pose and carry the end cap across the loop to there.
6600    let mut trims: HashMap<(usize, usize), EndTrim> = HashMap::new();
6601    // Walls split into strips along lines through their swallowtails' points.
6602    let mut split_walls: std::collections::HashSet<usize> = std::collections::HashSet::new();
6603    for (index, (_, _, surface, _, _)) in walls.iter().enumerate() {
6604        for end in 0..2 {
6605            if let Some(trim) = end_trim(screw, ends[end].0, ends[end].1, surface, end, fit)? {
6606                trims.insert((index, end), trim);
6607            }
6608        }
6609        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();
6610        wall_regular(surface, times, &removed, fit)?;
6611        // A trim along a double curve has that curve as one edge on both its
6612        // sides: on one face its two uses could not be told apart from its
6613        // 3D curve alone (the wall passes through it twice). The wall is split
6614        // along the parameter line from each swallowtail's point to the far
6615        // end's row, which that row is broken at.
6616        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() };
6617        let (tips0, tips1) = (tips_at(0), tips_at(1));
6618        if !tips0.is_empty() && !tips1.is_empty() {
6619            return Err(refuse("wall_split", "a wall turns over near both its ends".into()));
6620        }
6621        let (far, tips) = if tips0.is_empty() { (0usize, tips1) } else { (1usize, tips0) };
6622        // A straight split line serves only where the trimmed row keeps to
6623        // its own side of it: all that comes before the swallowtail's point
6624        // along the row at or below its u, all after at or above. (A cut
6625        // that bulges across it would be crossed by the line; such a wall
6626        // stays one face.)
6627        let straight = |trim: &EndTrim| -> Result<bool, KernelRefusal> {
6628            for (k, span) in trim.spans.iter().enumerate() {
6629                let Some(tip) = span.tip else { continue };
6630                let first_slot = span.chain.iter().position(|piece| piece.0 == TrimPiece::Slot).unwrap_or(0);
6631                for (j, other) in trim.spans.iter().enumerate() {
6632                    for (n, (_, _, pcurve)) in other.chain.iter().enumerate() {
6633                        let before = j < k || (j == k && n <= first_slot);
6634                        let [d0, d1] = frag(pcurve.domain(), "domain")?;
6635                        for i in 0..=32 {
6636                            let u = frag(pcurve.evaluate(d0 + (d1 - d0) * i as f64 / 32.0), "pcurve")?.x;
6637                            if (before && u > tip[0] + 1e-9) || (!before && u < tip[0] - 1e-9) {
6638                                return Ok(false);
6639                            }
6640                        }
6641                    }
6642                }
6643            }
6644            Ok(true)
6645        };
6646        // Or, where the trimmed row strays across the tip's u only beyond the
6647        // tip (near its own end), the split segment itself: from the tip to
6648        // the far row, crossed by none of either end's trim curves. Each strip
6649        // then lies on the wall over the u its own pcurves span.
6650        let crossing_free = |trim_near: &EndTrim| -> Result<bool, KernelRefusal> {
6651            let v_far = far as f64;
6652            for tip in &tips {
6653                let (v_lo, v_hi) = if v_far < tip[1] { (v_far, tip[1]) } else { (tip[1], v_far) };
6654                let ends = [Some(trim_near), trims.get(&(index, far))];
6655                for trim in ends.into_iter().flatten() {
6656                    for span in &trim.spans {
6657                        for (_, _, pcurve) in &span.chain {
6658                            if hull_meets_segment(pcurve, tip, v_lo, v_hi)? {
6659                                return Ok(false);
6660                            }
6661                        }
6662                    }
6663                }
6664            }
6665            Ok(true)
6666        };
6667        let split_here = !tips.is_empty()
6668            && match trims.get(&(index, 1 - far)) {
6669                Some(trim) => straight(trim)? || (split_crossing_on() && crossing_free(trim)?),
6670                None => false,
6671            };
6672        if split_here {
6673            split_walls.insert(index);
6674            let v_far = far as f64;
6675            let mut spans = trims.remove(&(index, far)).map(|trim| trim.spans).unwrap_or_default();
6676            for tip in &tips {
6677                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 {
6678                    return Err(refuse("wall_split", "a wall's split line lands in a trim of its far end".into()));
6679                }
6680                let point = frag(surface.evaluate(tip[0], v_far), "wall")?;
6681                spans.push(TrimSpan { lambdas: [tip[0], tip[0]], points: [point, point], cut: None, chain: Vec::new(), slot: None, tip: None, removed: Vec::new() });
6682            }
6683            spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
6684            let pieces = row_pieces(surface, v_far, &spans)?;
6685            trims.insert((index, far), EndTrim { spans, pieces });
6686        }
6687    }
6688    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
6689    let mut vertex = |shell: &mut Shell, end: usize, p: usize| -> u64 {
6690        *vertex_at.entry((end, p)).or_insert_with(|| shell.vertex(screw.apply(ends[end].1, ends[end].0.points[p])))
6691    };
6692    let grazing: HashMap<usize, usize> = walls.iter().enumerate().map(|(index, w)| (w.0, index)).collect();
6693    // Edges at each end: K curves from the walls' end rows (in the tool
6694    // curve's direction), the rest the end split's own curves moved.
6695    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
6696    let mut edge_curve: HashMap<(usize, usize), NurbsCurve> = HashMap::new();
6697    // Per trimmed wall end: the loop's piece edges, and each span's cut and
6698    // double-curve edges (u64::MAX where a span has none).
6699    let mut trim_edges: HashMap<(usize, usize), (Vec<u64>, Vec<[u64; 2]>)> = HashMap::new();
6700    // Per trimmed wall end and span: the vertex at its low end, and at the
6701    // swallowtail's point where it has one.
6702    let mut trim_vertices: HashMap<(usize, usize), Vec<(u64, Option<u64>)>> = HashMap::new();
6703    for end in 0..2 {
6704        let (split, t) = ends[end];
6705        for (c, tool_curve) in split.curves.iter().enumerate() {
6706            let used = split.caps.iter().any(|cap| cap.front == (end == 1) && cap.coedges.iter().any(|e| e.0 == c));
6707            if !used {
6708                continue;
6709            }
6710            if let Some(&index) = grazing.get(&c) {
6711                if let Some(trim) = trims.get(&(index, end)) {
6712                    // Pieces in the wall's direction: K up to the cut, the cut, K after it.
6713                    let back_forward = walls[index].1;
6714                    let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6715                    let (vf, vt) = (vertex(&mut shell, end, from), vertex(&mut shell, end, to));
6716                    let mut piece_edges = Vec::with_capacity(trim.pieces.len());
6717                    let mut span_edges = Vec::with_capacity(trim.spans.len());
6718                    let mut start = vf;
6719                    let mut span_vertices = Vec::with_capacity(trim.spans.len());
6720                    for (span, piece) in trim.spans.iter().zip(&trim.pieces) {
6721                        let va = shell.vertex(span.points[0]);
6722                        piece_edges.push(shell.edge(piece.clone(), start, va, false)?);
6723                        let Some(cut_curve) = &span.cut else {
6724                            // A break only: the row goes on from the same vertex.
6725                            span_edges.push([u64::MAX, u64::MAX]);
6726                            span_vertices.push((va, None));
6727                            start = va;
6728                            continue;
6729                        };
6730                        let vb = shell.vertex(span.points[1]);
6731                        let cut = shell.edge(cut_curve.clone(), va, vb, false)?;
6732                        // The double curve runs from where it leaves K (at
6733                        // the low end of the span if its chain starts with
6734                        // it) to the swallowtail's point.
6735                        let (slot, tip_vertex) = match &span.slot {
6736                            Some((curve, tip)) => {
6737                                let from = if span.chain[0].0 == TrimPiece::Slot { va } else { vb };
6738                                let tip = shell.vertex(*tip);
6739                                (shell.edge(curve.clone(), from, tip, false)?, Some(tip))
6740                            }
6741                            None => (u64::MAX, None),
6742                        };
6743                        span_edges.push([cut, slot]);
6744                        span_vertices.push((va, tip_vertex));
6745                        start = vb;
6746                    }
6747                    trim_vertices.insert((index, end), span_vertices);
6748                    piece_edges.push(shell.edge(trim.pieces[trim.pieces.len() - 1].clone(), start, vt, false)?);
6749                    trim_edges.insert((index, end), (piece_edges, span_edges));
6750                    continue;
6751                }
6752            }
6753            let curve = match grazing.get(&c) {
6754                Some(&index) => {
6755                    let (_, back_forward, _, row0, row1) = &walls[index];
6756                    let row = if end == 0 { row0 } else { row1 };
6757                    if *back_forward { frag(row.reversed(), "reversed")? } else { row.clone() }
6758                }
6759                None => screw.move_curve(t, &tool_curve.curve)?,
6760            };
6761            let (a, b) = (vertex(&mut shell, end, tool_curve.start), vertex(&mut shell, end, tool_curve.end));
6762            let edge = shell.edge(curve.clone(), a, b, tool_curve.degenerate)?;
6763            edge_at.insert((end, c), edge);
6764            edge_curve.insert((end, c), curve);
6765        }
6766    }
6767    for end in 0..2 {
6768        let (split, t) = ends[end];
6769        for cap in split.caps.iter().filter(|cap| cap.front == (end == 1)) {
6770            let surface = screw.move_surface(t, &cap.surface)?;
6771            let mut coedges = Vec::with_capacity(cap.coedges.len());
6772            for (c, forward, pcurve) in &cap.coedges {
6773                if let Some(&index) = grazing.get(c) {
6774                    if let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) {
6775                        let Some(chart) = cap.chart.as_ref() else {
6776                            return Err(refuse("end_trim", "an end pose bulges past a wall beside a cap without a chart".into()));
6777                        };
6778                        // The cap runs the tool's curve forward or back; the
6779                        // pieces run the wall's way: loop piece, cut, loop
6780                        // piece, ... loop piece.
6781                        let along = *forward != walls[index].1;
6782                        let mut pieces: Vec<(u64, &NurbsCurve)> = Vec::with_capacity(2 * trim.pieces.len());
6783                        for (k, piece) in trim.pieces.iter().enumerate() {
6784                            pieces.push((piece_edges[k], piece));
6785                            if let Some(cut) = trim.spans.get(k).and_then(|span| span.cut.as_ref()) {
6786                                pieces.push((span_edges[k][0], cut));
6787                            }
6788                        }
6789                        if !along {
6790                            pieces.reverse();
6791                        }
6792                        for (edge, curve) in pieces {
6793                            coedges.push((edge, along, charted_pcurve(chart, screw, t, curve, along)?));
6794                        }
6795                        continue;
6796                    }
6797                }
6798                let pcurve = if grazing.contains_key(c) && cap.chart.is_some() {
6799                    charted_pcurve(cap.chart.as_ref().expect("chart"), screw, t, &edge_curve[&(end, *c)], *forward)?
6800                } else if grazing.contains_key(c) {
6801                    match projected_pcurve(&surface, &edge_curve[&(end, *c)], *forward) {
6802                        Ok(p) => p,
6803                        Err(error) => {
6804                            // Which: the exact samples themselves, or the row between them?
6805                            let samples = split.curves[*c].samples.as_ref().map(|list| {
6806                                list.iter()
6807                                    .map(|&x| crate::project_point_to_surface(&surface, screw.apply(t, x)).map(|f| f.distance).unwrap_or(f64::NAN))
6808                                    .fold(0.0f64, f64::max)
6809                            });
6810                            let line = split.curves[*c].curve.degree;
6811                            return Err(KernelRefusal::unsupported(
6812                                KernelStage::Classify,
6813                                "loft_cap",
6814                                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),
6815                            ));
6816                        }
6817                    }
6818                } else {
6819                    pcurve.clone()
6820                };
6821                coedges.push((edge_at[&(end, *c)], *forward, pcurve));
6822            }
6823            shell.face(surface, coedges);
6824        }
6825    }
6826    // Orbits of K's corners: interpolated through the sample times as the
6827    // walls' end columns are.
6828    let mut orbits: HashMap<usize, u64> = HashMap::new();
6829    let mut keys: Vec<usize> = paths.keys().copied().collect();
6830    keys.sort_unstable();
6831    for r in keys {
6832        let curve = frag(crate::interpolate_curve(&paths[&r], 5, times), "orbit")?;
6833        let (a, b) = (vertex(&mut shell, 0, r), vertex(&mut shell, 1, r));
6834        orbits.insert(r, shell.edge(curve, a, b, false)?);
6835    }
6836    // One piece of a wall's end row in the direction of u: (edge, traversed
6837    // forward?, pcurve that way), and where a split line meets the row right
6838    // after it: (u, v, vertex).
6839    type RowPiece = (u64, bool, NurbsCurve, Option<(f64, f64, u64)>);
6840    for (index, (c, back_forward, surface, _, _)) in walls.iter().enumerate() {
6841        let tool_curve = &first.curves[*c];
6842        let (from, to) = if *back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6843        let row = |end: usize| -> Result<Vec<RowPiece>, KernelRefusal> {
6844            let v = end as f64;
6845            let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) else {
6846                return Ok(vec![(edge_at[&(end, *c)], !*back_forward, uv_line([0.0, v], [1.0, v])?, None)]);
6847            };
6848            let vertices = &trim_vertices[&(index, end)];
6849            let mut list: Vec<RowPiece> = Vec::new();
6850            let mut at = 0.0;
6851            for (k, span) in trim.spans.iter().enumerate() {
6852                let broken = if span.cut.is_none() { Some((span.lambdas[0], v, vertices[k].0)) } else { None };
6853                list.push((piece_edges[k], true, uv_line([at, v], [span.lambdas[0], v])?, broken));
6854                for (n, (piece, forward, pcurve)) in span.chain.iter().enumerate() {
6855                    let edge = if *piece == TrimPiece::Cut { span_edges[k][0] } else { span_edges[k][1] };
6856                    // The swallowtail's point lies between the double curve's two uses.
6857                    let between = *piece == TrimPiece::Slot && span.chain.get(n + 1).is_some_and(|next| next.0 == TrimPiece::Slot);
6858                    let tip = match (span.tip, vertices[k].1) {
6859                        (Some(tip), Some(vertex)) if between && split_walls.contains(&index) => Some((tip[0], tip[1], vertex)),
6860                        _ => None,
6861                    };
6862                    list.push((edge, *forward, pcurve.clone(), tip));
6863                }
6864                at = span.lambdas[1];
6865            }
6866            list.push((piece_edges[trim.spans.len()], true, uv_line([at, v], [1.0, v])?, None));
6867            Ok(list)
6868        };
6869        let (bottom, top) = (row(0)?, row(1)?);
6870        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());
6871        if low.len() != high.len() || low.iter().zip(&high).any(|(a, b)| (a.0 - b.0).abs() > 1e-9) {
6872            return Err(refuse("wall_split", "a wall's split lines do not run from one end's row to the other's".into()));
6873        }
6874        // The split lines, each from its lower point to its upper.
6875        let mut lines: Vec<(u64, f64, f64, f64)> = Vec::with_capacity(low.len());
6876        for (below, above) in low.iter().zip(&high) {
6877            let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
6878            let along: Vec<Vec3> = ts.iter().map(|&s| frag(surface.evaluate(below.0, below.1 + (above.1 - below.1) * s), "wall")).collect::<Result<_, _>>()?;
6879            let edge = shell.edge(frag(crate::interpolate_curve(&along, 5, &ts), "split_line")?, below.2, above.2, false)?;
6880            lines.push((edge, below.0, below.1, above.1));
6881        }
6882        // Each row in the stretches between the split lines.
6883        let stretches = |list: Vec<RowPiece>| -> Vec<Vec<(u64, bool, NurbsCurve)>> {
6884            let mut out = vec![Vec::new()];
6885            for (edge, forward, pcurve, cut) in list {
6886                out.last_mut().expect("stretch").push((edge, forward, pcurve));
6887                if cut.is_some() {
6888                    out.push(Vec::new());
6889                }
6890            }
6891            out
6892        };
6893        let (bottoms, tops) = (stretches(bottom), stretches(top));
6894        // A strip between two split lines (or the wall's sides): along the
6895        // start row, up its far side, back along the end row, down its near
6896        // side; on the wall over its own stretch of u only.
6897        for j in 0..=lines.len() {
6898            let mut coedges = bottoms[j].clone();
6899            match lines.get(j) {
6900                Some(&(edge, u, v0, v1)) => coedges.push((edge, true, uv_line([u, v0], [u, v1])?)),
6901                None => coedges.push((orbits[&to], true, uv_line([1.0, 0.0], [1.0, 1.0])?)),
6902            }
6903            for (edge, forward, pcurve) in tops[j].iter().rev() {
6904                coedges.push((*edge, !*forward, frag(pcurve.reversed(), "reversed")?));
6905            }
6906            match j.checked_sub(1).map(|k| lines[k]) {
6907                Some((edge, u, v0, v1)) => coedges.push((edge, false, uv_line([u, v1], [u, v0])?)),
6908                None => coedges.push((orbits[&from], false, uv_line([0.0, 1.0], [0.0, 0.0])?)),
6909            }
6910            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));
6911            // A strip whose trim strays past its split line (beyond the tip)
6912            // takes the wall over that u too: the parameters are the wall's.
6913            if lines.len() > 0 && split_crossing_on() {
6914                // Its control points bound each pcurve (positive weights).
6915                for (_, _, pcurve) in &coedges {
6916                    for point in &pcurve.control_points {
6917                        let u = point.x / point.w;
6918                        if u < ua - 1e-9 {
6919                            ua = u.max(0.0);
6920                        }
6921                        if u > ub + 1e-9 {
6922                            ub = u.min(1.0);
6923                        }
6924                    }
6925                }
6926            }
6927            shell.face(restrict_u(surface, ua, ub)?, coedges);
6928        }
6929    }
6930    let body = shell.solid();
6931    let issues = body.validate();
6932    if !issues.is_empty() {
6933        // Name the faces whose coedges stray: their pcurves' ends on the surface
6934        // against their edges' ends.
6935        let mut notes = Vec::new();
6936        for face in body.shells.iter().flat_map(|s| &s.faces) {
6937            for coedge in &face.loops[0].coedges {
6938                let edge = body.edges.iter().find(|e| e.id == coedge.edge_id).expect("edge");
6939                let [p0, p1] = frag(coedge.pcurve.domain(), "domain")?;
6940                let a = frag(coedge.pcurve.evaluate(p0), "uv")?;
6941                let on = frag(face.surface.evaluate_extended(a.x, a.y), "on")?;
6942                let at = frag(edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }), "at")?;
6943                if on.sub(at).length() > 1e-6 {
6944                    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));
6945                }
6946                let _ = p1;
6947            }
6948        }
6949        return Err(refuse("assembly", format!("the lofted sweep is not valid: {:?}; {}", issues.first(), notes.iter().take(4).cloned().collect::<Vec<_>>().join("; "))));
6950    }
6951    check_single_pass(screw, first, &body, &std::collections::HashSet::new())?;
6952    Ok(body)
6953}
6954
6955/// Is the world point y inside the moving tool at some time of the motion?
6956/// Steps t by the distance over a bound on the speed of any tool point near y.
6957fn covered(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6958    // A ball carried by a frame along a cubic: the question read off the cubic
6959    // (`BREP_SWEEP_BALL_COVER`, default on; its check mode walks as well).
6960    if crate::solid_sweep_one_pass::ball_cover_on() {
6961        if let (Some(frame), None, Shape::Revolved { origin, axis, meridian }) = (&screw.frame, &screw.turns, &split.shape) {
6962            if let Some((centre, r)) = crate::solid_sweep_one_pass::ball_of_revolved(*origin, *axis, meridian) {
6963                let offset = centre.sub(screw.a).length();
6964                if let Some(answer) = crate::solid_sweep_one_pass::ball_on_cubic_covered(frame.control, screw.t0, screw.t1, offset, r, y, margin) {
6965                    if !crate::solid_sweep_one_pass::ball_cover_check_on() {
6966                        return Ok(answer);
6967                    }
6968                    let walked = covered_walk(screw, split, reach, y, normal, margin)?;
6969                    crate::solid_sweep_one_pass::ball_cover_check_record(walked == answer);
6970                    return Ok(walked);
6971                }
6972            }
6973        }
6974    }
6975    covered_walk(screw, split, reach, y, normal, margin)
6976}
6977
6978/// [`covered`] by walking the motion.
6979fn covered_walk(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6980    if reach.is_some_and(|reach| reach.never_inside(screw, y, normal, margin)) {
6981        return Ok(false);
6982    }
6983    if let Some(found) = reach.and_then(|reach| reach.turn_about_parallel_axis(screw, y, margin)) {
6984        return found;
6985    }
6986    let speed = preimage_speed_bound(screw, split, y);
6987    let floor = (screw.t1 - screw.t0) * 1e-7;
6988    let glide = Glide::of(screw, y);
6989    let mut t = screw.t0;
6990    let mut steps = 0usize;
6991    loop {
6992        let p = screw.invert(t, y);
6993        let d = split.distance(p);
6994        if d < -margin {
6995            return Ok(true);
6996        }
6997        if t >= screw.t1 {
6998            return Ok(false);
6999        }
7000        if steps > 2_000_000 {
7001            return Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into()));
7002        }
7003        let first = (d.abs() + margin) / speed;
7004        let second = glide.as_ref().map_or(0.0, |glide| glide.step(split, p, t, d, margin, speed, screw.t1 - t));
7005        let second = if second.is_finite() { second } else { 0.0 };
7006        t = (t + first.max(second).max(floor)).min(screw.t1);
7007        steps += 1;
7008    }
7009}
7010
7011/// The preimage of a probe under a plain screw, as an explicit curve: with
7012/// `u` the probe's offset from the axis square to it and `v = e × u`,
7013/// `p(t) = a + (e·(y − a) − advance(t))·e + cos(ωt)·u − sin(ωt)·v`. Its
7014/// second derivative is no longer than `ω²·|u| + 2|c₂|` (`curve`).
7015///
7016/// The walk in time steps by the tool's distance over the preimage's speed:
7017/// beside a wall the tool grazes (a thread's flank, a ball's groove) the
7018/// distance stays the probe's tiny offset through the whole contact and the
7019/// walk crawls, some π·√(2R/δ) steps a probe. Where the path runs along the
7020/// tool rather than into it, its tangent line stays clear of the tool for
7021/// far longer, and the path leaves that line by no more than `curve·h²/2`:
7022/// the second-order step is the longest `h` the tool's distance from the
7023/// tangent segment, less that, keeps above −margin. It is never shorter than
7024/// the first-order step, and skips no time the probe is deeper than the margin.
7025struct Glide {
7026    e: Vec3,
7027    u: Vec3,
7028    v: Vec3,
7029    omega: f64,
7030    c: f64,
7031    c2: f64,
7032    curve: f64,
7033    /// Under `frame_glide_on`, a frame riding a curve: the probe's preimage
7034    /// `a + R(−θ(t))(y − P(t))` read through the frame (frame, y).
7035    riding: Option<(Frame, Vec3)>,
7036    /// Under `turns_glide_on`, two turns about fixed axes: the probe's preimage under them (turns, y).
7037    turning: Option<(Turns, Vec3)>,
7038    /// Under `frame_windows_on`, the bound on |p''| over each of equal windows
7039    /// of the motion (start, width, bounds), each no looser than `curve`.
7040    windows: Option<(f64, f64, Vec<f64>)>,
7041}
7042
7043/// The riding frame's |p''| bound read window by window (default on; `=0`
7044/// keeps one bound over the whole motion). Either is a bound; a window's is
7045/// read where the step stays within it, so steps lengthen where the curve
7046/// bends gently.
7047fn frame_windows_on() -> bool {
7048    crate::switch!("BREP_SWEEP_FRAME_WINDOWS", true)
7049}
7050
7051/// The second-order step for two turns about fixed axes (`BREP_SWEEP_TURNS_GLIDE`, default on;
7052/// `=0` restores the first-order walk).
7053fn turns_glide_on() -> bool {
7054    crate::switch!("BREP_SWEEP_TURNS_GLIDE", true)
7055}
7056
7057/// The second-order step for frames riding a curve (default on; `=0` restores the first-order walk).
7058fn frame_glide_on() -> bool {
7059    crate::switch!("BREP_SWEEP_FRAME_GLIDE", true)
7060}
7061
7062impl Glide {
7063    fn of(screw: &Screw, y: Vec3) -> Option<Glide> {
7064        if let (Some(frame), None, true) = (&screw.frame, &screw.turns, frame_glide_on()) {
7065            return Glide::riding(screw, frame, y);
7066        }
7067        if let (Some(turns), true) = (&screw.turns, turns_glide_on()) {
7068            return Glide::turning(turns, y);
7069        }
7070        if screw.frame.is_some() || screw.turns.is_some() {
7071            return None;
7072        }
7073        let r = y.sub(screw.a);
7074        let u = r.sub(screw.e.scale(r.dot(screw.e)));
7075        let curve = screw.omega * screw.omega * u.length() + 2.0 * screw.c2.abs();
7076        // A bound rounded to nothing, or below the normal range, is not one:
7077        // only a slide (no turn, no rise) is straight.
7078        let straight = screw.omega == 0.0 && screw.c2 == 0.0;
7079        if !straight && !(curve >= f64::MIN_POSITIVE && curve.is_finite()) {
7080            return None;
7081        }
7082        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 })
7083    }
7084
7085    /// A frame riding a planar cubic: the preimage `p = a + R(−θ) q`,
7086    /// `q = y − P(t)`, turns about `up`, and its second derivative is
7087    /// `R(−θ)(θ'² up×(up×q) − θ'' up×q + 2θ' up×P' − P'')`, so
7088    /// `|p''| ≤ (θ'² + |θ''|)·|q| + 2|θ'|·|P'| + |P''|`. Over the motion's
7089    /// span |P'| and |P''| are bounded by their control polygons and |P'''|
7090    /// is a constant; `θ' = up·(P'×P'')/|P'|²` and θ'' are bounded through a
7091    /// lower bound on |P'| (its samples less |P''| times half their spacing;
7092    /// no glide where that is not positive); `|q| ≤ |y − P(t₀)| + |P'|·span`.
7093    fn riding(screw: &Screw, frame: &Frame, y: Vec3) -> Option<Glide> {
7094        let [p0, p1, p2, p3] = frame.control;
7095        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);
7096        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);
7097        let third = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(6.0).length();
7098        let (t0, t1) = (screw.t0, screw.t1);
7099        let n = 256;
7100        let slowest = (0..=n).map(|k| frame.first(t0 + (t1 - t0) * k as f64 / n as f64).length()).fold(f64::INFINITY, f64::min);
7101        let floor = slowest - second * 0.5 * (t1 - t0) / n as f64;
7102        if !(floor > 0.0) {
7103            return None;
7104        }
7105        let w1 = first * second / (floor * floor);
7106        let w2 = third * first / (floor * floor) + 2.0 * first * first * second * second / floor.powi(4);
7107        let q = y.sub(frame.point(t0)).length() + first * (t1 - t0);
7108        let curve = (w1 * w1 + w2) * q + 2.0 * w1 * first + second;
7109        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
7110            return None;
7111        }
7112        // Window by window: |P'| by the hull of its quadratic over the window,
7113        // |P''| (linear) at the window's ends, the floor on |P'| from eight
7114        // samples less |P''| times half their spacing, |q| from the window's
7115        // start; each bound kept no looser than the whole motion's.
7116        let windows = frame_windows_on().then(|| {
7117            let count = 32usize;
7118            let width = (t1 - t0) / count as f64;
7119            let bounds = (0..count)
7120                .map(|i| {
7121                    let (a, b) = (t0 + width * i as f64, t0 + width * (i + 1) as f64);
7122                    let (da, db) = (frame.first(a), frame.first(b));
7123                    let middle = da.add(frame.second(a).scale(0.5 * (b - a)));
7124                    let first_w = da.length().max(db.length()).max(middle.length());
7125                    let second_w = frame.second(a).length().max(frame.second(b).length());
7126                    let m = 8;
7127                    let slow = (0..=m).map(|j| frame.first(a + (b - a) * j as f64 / m as f64).length()).fold(f64::INFINITY, f64::min);
7128                    let floor_w = slow - second_w * 0.5 * (b - a) / m as f64;
7129                    if !(floor_w > 0.0) {
7130                        return curve;
7131                    }
7132                    let w1 = first_w * second_w / (floor_w * floor_w);
7133                    let w2 = third * first_w / (floor_w * floor_w) + 2.0 * first_w * first_w * second_w * second_w / floor_w.powi(4);
7134                    let q_w = y.sub(frame.point(a)).length() + first_w * (b - a);
7135                    let c = (w1 * w1 + w2) * q_w + 2.0 * w1 * first_w + second_w;
7136                    if c.is_finite() && c >= f64::MIN_POSITIVE { c.min(curve) } else { curve }
7137                })
7138                .collect::<Vec<f64>>();
7139            (t0, width, bounds)
7140        });
7141        let zero = Vec3::new(0.0, 0.0, 0.0);
7142        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 })
7143    }
7144
7145    /// Two turns about fixed axes (unit `d₀`, `d₁` through `P₀`, `P₁` at rates `r₀`, `r₁`): the
7146    /// preimage `p = P₀ + R₀(−r₀t)(x − P₀)`, `x = P₁ + R₁(−r₁t)(y − P₁)`. With `x' = −r₁ d₁×(x − P₁)`
7147    /// and `x'' = −r₁ d₁×x'`, `p'' = R₀(x'') − 2r₀ d₀×R₀(x') + r₀² d₀×(d₀×(p − P₀))`, so
7148    /// `|p''| ≤ (r₁² + 2|r₀ r₁|)·|y − P₁| + r₀²·(|y − P₁| + |P₁ − P₀|)` (rotations keep lengths).
7149    fn turning(turns: &Turns, y: Vec3) -> Option<Glide> {
7150        let a = y.sub(turns.points[1]).length();
7151        let d = a + turns.points[1].sub(turns.points[0]).length();
7152        let (r0, r1) = (turns.rates[0].abs(), turns.rates[1].abs());
7153        let curve = (r1 * r1 + 2.0 * r0 * r1) * a + r0 * r0 * d;
7154        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
7155            return None;
7156        }
7157        let zero = Vec3::new(0.0, 0.0, 0.0);
7158        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 })
7159    }
7160
7161    /// The bound on |p''| over [t, t + h]: the most of the windows it meets,
7162    /// or the whole motion's.
7163    fn curve_over(&self, t: f64, h: f64) -> f64 {
7164        match &self.windows {
7165            Some((t0, width, bounds)) => {
7166                let last = bounds.len() - 1;
7167                let index = |x: f64| -> usize {
7168                    let k = ((x - t0) / width).floor();
7169                    if k.is_nan() || k <= 0.0 { 0 } else { (k as usize).min(last) }
7170                };
7171                bounds[index(t)..=index(t + h)].iter().fold(0.0f64, |a, &b| a.max(b))
7172            }
7173            None => self.curve,
7174        }
7175    }
7176
7177    /// `p'(t)`.
7178    fn velocity(&self, t: f64) -> Vec3 {
7179        if let Some((turns, y)) = &self.turning {
7180            let (p0, p1) = (turns.points[0], turns.points[1]);
7181            let (d0, d1) = (turns.directions[0], turns.directions[1]);
7182            let (r0, r1) = (turns.rates[0], turns.rates[1]);
7183            let arm1 = y.sub(p1).rotate_about(d1, -r1 * t);
7184            let x_rate = d1.cross(arm1).scale(-r1);
7185            let arm0 = p1.add(arm1).sub(p0).rotate_about(d0, -r0 * t);
7186            return x_rate.rotate_about(d0, -r0 * t).sub(d0.cross(arm0).scale(r0));
7187        }
7188        if let Some((frame, y)) = &self.riding {
7189            // p' = R(−θ)(−θ' up×q − P'), q = y − P(t).
7190            let q = y.sub(frame.point(t));
7191            let inner = frame.up.cross(q).scale(-frame.angle_rate(t)).sub(frame.first(t));
7192            return inner.rotate_about(frame.up, -frame.angle(t));
7193        }
7194        let (sin, cos) = (self.omega * t).sin_cos();
7195        self.e
7196            .scale(-(self.c + 2.0 * self.c2 * t))
7197            .sub(self.u.scale(self.omega * sin))
7198            .sub(self.v.scale(self.omega * cos))
7199    }
7200
7201    /// The second-order step from `t`, where the preimage is `p` at the
7202    /// tool's distance `d` (at most `left`; 0 when it finds none).
7203    #[allow(clippy::too_many_arguments)]
7204    fn step(&self, split: &Split, p: Vec3, t: f64, d: f64, margin: f64, speed: f64, left: f64) -> f64 {
7205        let velocity = self.velocity(t);
7206        // (the planes' root is read in closed form under one bound: the
7207        // windows' over the rest of the motion)
7208        let m = if self.windows.is_some() { self.curve_over(t, left) } else { self.curve };
7209        match &split.shape {
7210            // Each face's plane alone bounds the distance from below:
7211            // g(t + h) ≥ g + g'·h − m·h²/2, held above −margin up to the root.
7212            Shape::Planes(planes) => {
7213                let mut best = 0.0f64;
7214                for (n, offset) in planes {
7215                    let g = n.dot(p) - offset;
7216                    if g + margin <= 0.0 {
7217                        continue;
7218                    }
7219                    let slope = n.dot(velocity);
7220                    // The root, in the form that neither overflows nor cancels.
7221                    let h = if m > 0.0 {
7222                        let root = slope.hypot((2.0 * m * (g + margin)).sqrt());
7223                        if slope >= 0.0 { (slope + root) / m } else { 2.0 * (g + margin) / (root - slope) }
7224                    } else if slope >= 0.0 {
7225                        left
7226                    } else {
7227                        (g + margin) / -slope
7228                    };
7229                    if h.is_finite() {
7230                        best = best.max(h);
7231                    }
7232                }
7233                best.min(left)
7234            }
7235            // In the meridian plane: the path (ρ, z) about the tool's axis and
7236            // its tangent segment, whose distance from the outline is bounded
7237            // below piece by piece; the path leaves the segment by at most
7238            // m₂·h²/2, m₂ = 2m + speed²/ρ_min (the radius' bend), ρ_min > 0.
7239            Shape::Revolved { origin, axis, meridian } => {
7240                if d < 0.0 {
7241                    return 0.0;
7242                }
7243                let r = p.sub(*origin);
7244                let z = r.dot(*axis);
7245                let flat = r.sub(axis.scale(z));
7246                let rho = flat.length();
7247                if rho <= 0.0 {
7248                    return 0.0;
7249                }
7250                let dz = velocity.dot(*axis);
7251                let dflat = velocity.sub(axis.scale(dz));
7252                let drho = flat.dot(dflat) / rho;
7253                let q = [rho, z];
7254                let walk_sqrt = walk_sqrt_on();
7255                let mut best = 0.0f64;
7256                let mut h = (d + margin) / speed;
7257                for _ in 0..64 {
7258                    h *= 2.0;
7259                    if h > left {
7260                        h = left;
7261                    }
7262                    // Under the windows, the speed over [t, t + h] by the
7263                    // step's own: |p'| ≤ |p'(t)| + m·h, no more than `speed`.
7264                    let (m, speed) = if self.windows.is_some() {
7265                        let m = self.curve_over(t, h);
7266                        (m, (velocity.length() + m * h).min(speed))
7267                    } else {
7268                        (m, speed)
7269                    };
7270                    let low = rho - speed * h;
7271                    if low <= 0.0 {
7272                        break;
7273                    }
7274                    let bend = 2.0 * m + speed * speed / low;
7275                    let end = [rho + drho * h, z + dz * h];
7276                    let clear = if walk_sqrt {
7277                        meridian.iter().map(|piece| segment_clearance_sqrt(piece, q, end)).fold(f64::INFINITY, f64::min)
7278                    } else {
7279                        meridian.iter().map(|piece| segment_clearance(piece, q, end)).fold(f64::INFINITY, f64::min)
7280                    };
7281                    // A segment that touches the outline may enter the tool: no bound.
7282                    let held = clear - 0.5 * bend * h * h;
7283                    if !held.is_finite() || clear <= 0.0 || held < -margin {
7284                        break;
7285                    }
7286                    best = h;
7287                    if h >= left {
7288                        break;
7289                    }
7290                }
7291                best
7292            }
7293        }
7294    }
7295}
7296
7297/// A lower bound on the distance between the segment `a`–`b` and a meridian
7298/// piece: a line piece's exact distance (0 where they cross), an arc's from
7299/// its whole circle.
7300fn segment_clearance(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
7301    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
7302    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
7303    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
7304    let to_segment = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
7305        let d = sub(e, s);
7306        let len2 = dot(d, d);
7307        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
7308        let foot = [s[0] + d[0] * w, s[1] + d[1] * w];
7309        let gap = sub(x, foot);
7310        gap[0].hypot(gap[1])
7311    };
7312    match *piece {
7313        OutlinePiece::Line { from, to } => {
7314            let (d1, d2) = (sub(b, a), sub(to, from));
7315            let denom = cross(d1, d2);
7316            if denom != 0.0 {
7317                let w = sub(from, a);
7318                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
7319                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
7320                    return 0.0;
7321                }
7322            }
7323            to_segment(a, from, to).min(to_segment(b, from, to)).min(to_segment(from, a, b)).min(to_segment(to, a, b))
7324        }
7325        OutlinePiece::Arc { centre, radius, .. } => {
7326            let near = to_segment(centre, a, b);
7327            let far = { let (x, y) = (sub(a, centre), sub(b, centre)); x[0].hypot(x[1]).max(y[0].hypot(y[1])) };
7328            (near - radius).max(radius - far).max(0.0)
7329        }
7330        // no bound read for an ellipse: zero is one
7331        OutlinePiece::Ellipse { .. } => 0.0,
7332    }
7333}
7334
7335/// The switch for [`segment_clearance_sqrt`] in the walk's second-order step
7336/// (default on; `=0` reads `segment_clearance`).
7337fn walk_sqrt_on() -> bool {
7338    crate::switch!("BREP_SWEEP_WALK_SQRT", true)
7339}
7340
7341/// [`segment_clearance`] without `hypot`: a line piece's least squared gap,
7342/// one square root; an arc's lengths by `sqrt` (within a rounding of `hypot`).
7343/// A square outside the range where squaring is exact to a rounding (below
7344/// 1e-290, which takes in an underflow to zero, or above 1e290) reads the
7345/// piece by `segment_clearance` instead.
7346fn segment_clearance_sqrt(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
7347    let in_range = |x: f64| (1e-290..=1e290).contains(&x);
7348    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
7349    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
7350    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
7351    let to_segment_squared = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
7352        let d = sub(e, s);
7353        let len2 = dot(d, d);
7354        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
7355        let gap = sub(x, [s[0] + d[0] * w, s[1] + d[1] * w]);
7356        dot(gap, gap)
7357    };
7358    match *piece {
7359        OutlinePiece::Line { from, to } => {
7360            let (d1, d2) = (sub(b, a), sub(to, from));
7361            let denom = cross(d1, d2);
7362            if denom != 0.0 {
7363                let w = sub(from, a);
7364                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
7365                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
7366                    return 0.0;
7367                }
7368            }
7369            let least = to_segment_squared(a, from, to)
7370                .min(to_segment_squared(b, from, to))
7371                .min(to_segment_squared(from, a, b))
7372                .min(to_segment_squared(to, a, b));
7373            if !in_range(least) {
7374                return segment_clearance(piece, a, b);
7375            }
7376            least.sqrt()
7377        }
7378        OutlinePiece::Arc { centre, radius, .. } => {
7379            let near = to_segment_squared(centre, a, b);
7380            let (x, y) = (sub(a, centre), sub(b, centre));
7381            let far = dot(x, x).max(dot(y, y));
7382            if !(in_range(near) && in_range(far)) {
7383                return segment_clearance(piece, a, b);
7384            }
7385            (near.sqrt() - radius).max(radius - far.sqrt()).max(0.0)
7386        }
7387        OutlinePiece::Ellipse { .. } => 0.0,
7388    }
7389}
7390
7391/// A bound on how fast the tool-frame preimage `screw.invert(t, y)` of the
7392/// world point `y` moves per unit `t`; the tool's distance (1-Lipschitz)
7393/// changes no faster along it.
7394///
7395/// A plain screw about one fixed axis carries the preimage round that axis at
7396/// its distance from it, `ρ`, and along it at the advance's rate, two motions
7397/// square to each other: no faster than `hypot(|ω|·ρ, rate)`. A point near the axis barely moves, so a probe beside
7398/// a tool point on the axis (a coin turned about a line through its rim) walks
7399/// the motion in a few long steps, not millions of floor-sized ones. A riding
7400/// frame or two turns keep the coarser bound through `a`.
7401fn preimage_speed_bound(screw: &Screw, split: &Split, y: Vec3) -> f64 {
7402    let speed = if screw.frame.is_none() && screw.turns.is_none() {
7403        let r = y.sub(screw.a);
7404        let rho = r.sub(screw.e.scale(r.dot(screw.e))).length();
7405        (screw.omega.abs() * rho).hypot(screw.rate_bound())
7406    } else {
7407        let reach = y.sub(screw.a).length() + split.scale + screw.extent;
7408        screw.omega.abs() * reach + screw.rate_bound()
7409    };
7410    speed.max(1e-300)
7411}
7412
7413/// How far a revolved tool reaches about a plain screw's axis: its axial
7414/// coordinate `e·(x − a)` lies within `axial` and its distance from the axis
7415/// within `radial`, for every tool point `x` (bounds, not extremes: a meridian
7416/// line is bounded at its ends, an arc by its whole circle).
7417///
7418/// A plain screw keeps each point's distance from its axis and shifts its
7419/// axial coordinate only by the advance (a slide keeps every coordinate across
7420/// its direction), so a point `y` whose preimage stays outside these bounds
7421/// all through the motion is never inside the tool, and `covered` need not
7422/// walk the motion to say so. Without this a probe beside a face the tool runs
7423/// along all through the motion (the flat top of a coin turned about a line
7424/// through its rim, the floor of an end mill's pass) creeps through it in
7425/// steps of its own tiny distance from the tool.
7426struct ToolReach {
7427    /// The tool's revolution: its origin less the screw's point, its unit axis
7428    /// and its meridian (radius, height along the axis).
7429    base: Vec3,
7430    axis: Vec3,
7431    meridian: Vec<OutlinePiece>,
7432    axial: [f64; 2],
7433    radial: [f64; 2],
7434}
7435
7436/// The largest of |m₀|·p + m₁·q over a meridian (p ≥ 0): a line at its ends,
7437/// an arc by its circle (Cauchy–Schwarz on the offset from its centre).
7438fn meridian_most(meridian: &[OutlinePiece], p: f64, q: f64) -> f64 {
7439    meridian
7440        .iter()
7441        .map(|piece| match *piece {
7442            OutlinePiece::Line { from, to } => (from[0].abs() * p + from[1] * q).max(to[0].abs() * p + to[1] * q),
7443            OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() * p + centre[1] * q + radius * p.hypot(q),
7444            // within the circle of its larger semi-axis
7445            OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() * p + centre[1] * q + semi[0].max(semi[1]) * p.hypot(q),
7446        })
7447        .fold(f64::NEG_INFINITY, f64::max)
7448}
7449
7450impl ToolReach {
7451    fn of(screw: &Screw, split: &Split) -> Option<ToolReach> {
7452        if screw.frame.is_some() || screw.turns.is_some() {
7453            return None;
7454        }
7455        let Shape::Revolved { origin, axis, meridian } = &split.shape else { return None };
7456        let e = screw.e;
7457        // x − a = (origin − a) + m₁·axis + m₀·(unit vector ⊥ axis).
7458        let base = origin.sub(screw.a);
7459        let along = axis.dot(e);
7460        let across = axis.cross(e).length();
7461        let middle = base.dot(e);
7462        let top = middle + meridian_most(meridian, across, along);
7463        let bottom = middle - meridian_most(meridian, across, -along);
7464        // Off the axis: within |(origin − a)⊥| ± (|m₀| + |m₁|·|axis⊥e|).
7465        let off = base.sub(e.scale(middle)).length();
7466        let spread = meridian
7467            .iter()
7468            .map(|piece| match *piece {
7469                OutlinePiece::Line { from, to } => (from[0].abs() + from[1].abs() * across).max(to[0].abs() + to[1].abs() * across),
7470                OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() + centre[1].abs() * across + radius * (1.0 + across * across).sqrt(),
7471                OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() + centre[1].abs() * across + semi[0].max(semi[1]) * (1.0 + across * across).sqrt(),
7472            })
7473            .fold(f64::NEG_INFINITY, f64::max);
7474        let reach = ToolReach { base, axis: *axis, meridian: meridian.clone(), axial: [bottom, top], radial: [off - spread, off + spread] };
7475        (top.is_finite() && bottom.is_finite() && spread.is_finite()).then_some(reach)
7476    }
7477
7478    /// `covered` for a turn (no advance) about an axis along the tool's own,
7479    /// walked in the tool's radius instead of in time; `None` when the motion
7480    /// is not such a turn.
7481    ///
7482    /// The preimage keeps its height along the tool's axis, and its distance
7483    /// from that axis is `ρ_w² = ρ² + s² − 2·ρ·s·cos(θ − θ_W)`, `ρ` its own
7484    /// distance from the turn's axis, `s` the tool axis' and `θ − θ_W` the
7485    /// angle between them, which the turn sweeps through an interval. So the
7486    /// preimage takes every radius between the least and the most `ρ_w` over
7487    /// that interval, and no other: it is ever deeper than the margin inside
7488    /// the tool if and only if some radius in that range is, at that height.
7489    /// The meridian's distance is 1-Lipschitz in the radius, so the range is
7490    /// walked by it. Each radius is met once, where the walk in time crawls
7491    /// past a probe the tool grazes (by the probe's own tiny offset over the
7492    /// turn's speed at each step).
7493    fn turn_about_parallel_axis(&self, screw: &Screw, y: Vec3, margin: f64) -> Option<Result<bool, KernelRefusal>> {
7494        if screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 || self.axis.cross(screw.e).length() != 0.0 {
7495            return None;
7496        }
7497        let e = screw.e;
7498        let r = y.sub(screw.a);
7499        // From the tool's origin to the probe, and its height along the tool's
7500        // axis (the turn keeps it).
7501        let from_tool = r.sub(self.base);
7502        let height = from_tool.dot(self.axis);
7503        // In the plane square to the axis, from the turn's axis: the probe `P`
7504        // and the tool's axis `W`, and the probe from the tool's axis, `P − W`
7505        // (formed as one difference, not as two far points less each other).
7506        let flat = |x: Vec3| x.sub(e.scale(x.dot(e)));
7507        let (probe, tool, apart) = (flat(r), flat(self.base), flat(from_tool));
7508        let (rho, s) = (probe.length(), tool.length());
7509        // Rounding of the coordinates read here, a few ulps of the largest: past
7510        // a quarter of the margin, the walk in time decides instead.
7511        let slack = 64.0 * f64::EPSILON * (r.length() + self.base.length() + height.abs());
7512        if slack > 0.25 * margin {
7513            return None;
7514        }
7515        // The preimage at time t is R(−ω·t)·P: its distance from the tool's axis
7516        // is |R(φ)·(P − W) + (R(φ) − I)·W|, with R(φ) − I = −2 sin²(φ/2) + sin φ·(e ×).
7517        let radius = |phi: f64| -> f64 {
7518            let half = (0.5 * phi).sin();
7519            let turned = apart.rotate_about(e, phi).add(tool.scale(-2.0 * half * half)).add(e.cross(tool).scale(phi.sin()));
7520            turned.length()
7521        };
7522        let (phi0, phi1) = (-screw.omega * screw.t0, -screw.omega * screw.t1);
7523        // The angle from W to P; R(φ)·P lies along W at start + φ ≡ 0 and opposite it at ≡ π.
7524        let start = if rho == 0.0 || s == 0.0 { 0.0 } else { e.dot(tool.cross(probe)).atan2(tool.dot(probe)) };
7525        let (lo, hi) = ((start + phi0).min(start + phi1), (start + phi0).max(start + phi1));
7526        // Does [lo, hi] hold an angle ≡ `at` (mod 2π)?
7527        let holds = |at: f64| (lo - at).div_euclid(TAU) != (hi - at).div_euclid(TAU) || (lo - at).rem_euclid(TAU) == 0.0;
7528        let ends = [radius(phi0), radius(phi1)];
7529        // | |P| − |W| | as |(P − W)·(P + W)| / (|P| + |W|): no cancellation.
7530        let nearest = if rho + s > 0.0 { apart.dot(probe.add(tool)).abs() / (rho + s) } else { 0.0 };
7531        let mut least = if holds(0.0) { nearest } else { ends[0].min(ends[1]) };
7532        let mut most = if holds(PI) { rho + s } else { ends[0].max(ends[1]) };
7533        least = (least - slack).max(0.0);
7534        most += slack;
7535        let mut at = least;
7536        // No floor on the step (it is never less than the margin): a floor
7537        // could step over a wall thinner than itself.
7538        let mut steps = 0usize;
7539        loop {
7540            let d = outline_signed_distance(&self.meridian, [at, height]);
7541            if d < -margin {
7542                return Some(Ok(true));
7543            }
7544            if at >= most {
7545                return Some(Ok(false));
7546            }
7547            if steps > 2_000_000 {
7548                return Some(Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into())));
7549            }
7550            at = (at + d.abs() + margin).min(most);
7551            steps += 1;
7552        }
7553    }
7554
7555    /// A bound on `u·(x − a)` over the tool, `u` a unit direction.
7556    fn support(&self, u: Vec3) -> f64 {
7557        let along = u.dot(self.axis);
7558        let across = u.sub(self.axis.scale(along)).length();
7559        u.dot(self.base) + meridian_most(&self.meridian, across, along)
7560    }
7561
7562    /// Is `y`'s preimage outside the tool's reach, or within half the margin
7563    /// of its edge, at every time of the motion? Then the tool's boundary is
7564    /// within half the margin of every preimage inside (straight out of the
7565    /// bound), and none is deeper than the margin. `normal`: the probe's face
7566    /// normal, across which a slide is also tried.
7567    fn never_inside(&self, screw: &Screw, y: Vec3, normal: Vec3, margin: f64) -> bool {
7568        let r = y.sub(screw.a);
7569        let z = r.dot(screw.e);
7570        let rho = r.sub(screw.e.scale(z)).length();
7571        let mut advances = vec![screw.advance(screw.t0), screw.advance(screw.t1)];
7572        if screw.c2 != 0.0 {
7573            let vertex = -screw.c / (2.0 * screw.c2);
7574            if vertex > screw.t0 && vertex < screw.t1 {
7575                advances.push(screw.advance(vertex));
7576            }
7577        }
7578        let low = advances.iter().copied().fold(f64::INFINITY, f64::min);
7579        let high = advances.iter().copied().fold(f64::NEG_INFINITY, f64::max);
7580        // Half the margin, less what rounding may have cost the coordinates
7581        // and bounds compared (a few ulps of the largest of them).
7582        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());
7583        let half = 0.5 * margin - 1e-13 * size;
7584        if half <= 0.0 {
7585            return false;
7586        }
7587        if z - high >= self.axial[1] - half || z - low <= self.axial[0] + half {
7588            return true;
7589        }
7590        if rho >= self.radial[1] - half || (self.radial[0] > 0.0 && rho <= self.radial[0] + half) {
7591            return true;
7592        }
7593        // A slide carries the preimage along its direction only. `u` is meant
7594        // across it, but whatever of `e` rounding leaves in it moves `u·r`
7595        // with the advance: take the least `u·r` reaches over the motion.
7596        if screw.omega == 0.0 {
7597            if let Ok(u) = normal.sub(screw.e.scale(normal.dot(screw.e))).normalized() {
7598                let drift = u.dot(screw.e);
7599                let least = u.dot(r) - (drift * low).max(drift * high);
7600                if least >= self.support(u) - half {
7601                    return true;
7602                }
7603            }
7604        }
7605        false
7606    }
7607}
7608
7609/// Refuse a sweep that covers points just outside its own faces.
7610///
7611/// `sliding`: faces the tool slides within all through the motion. A probe
7612/// just off one stays that near the tool the whole way, and the walk's step
7613/// is that distance: it stands a thousand times further off them (whatever
7614/// of the tool rides higher than that over such a face is still found).
7615fn check_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7616    let (on, check) = (parallel_turn_one_pass_on(), parallel_turn_one_pass_check_on());
7617    if (on || check) && parallel_turn_one_pass(screw, split) {
7618        if !check {
7619            return Ok(());
7620        }
7621        let walked = walk_single_pass(screw, split, body, sliding);
7622        PARALLEL_TURN_CHECK.with(|cell| {
7623            let (n, bad) = cell.get();
7624            cell.set((n + 1, bad + u64::from(walked.is_err())));
7625        });
7626        return walked;
7627    }
7628    walk_single_pass(screw, split, body, sliding)
7629}
7630
7631/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS` (default on, `=0` walks): the one-pass check
7632/// answered in closed form for a solid of revolution turned (no advance)
7633/// about an axis parallel to its own, `D` from it, whose every section square
7634/// to the axes is one disc of radius `r(z) <= r_max < D`. A point's
7635/// distance from the turn's axis stays fixed; the disc at its height covers,
7636/// of the circle it runs on, one arc of half-angle at most `asin(r_max / D)`
7637/// centred on the tool's axis, and that arc moves round with the turn. The
7638/// point is inside over one interval of the turn unless the arc comes round
7639/// to it again: never while the turn is short of `2π − 2 asin(r_max / D)`.
7640/// The sampled walk is then not needed.
7641pub(crate) fn parallel_turn_one_pass_on() -> bool {
7642    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS", true)
7643}
7644
7645/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK` (default off): where the closed
7646/// form says one pass, the walk runs too and decides; the tally counts the
7647/// walks that refused ([`parallel_turn_one_pass_check_take`]).
7648fn parallel_turn_one_pass_check_on() -> bool {
7649    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK", false)
7650}
7651
7652thread_local! {
7653    static PARALLEL_TURN_CHECK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
7654}
7655
7656/// (closed-form one-pass answers walked, walks that refused) on this thread
7657/// since the last call.
7658pub fn parallel_turn_one_pass_check_take() -> (u64, u64) {
7659    PARALLEL_TURN_CHECK.with(|cell| cell.replace((0, 0)))
7660}
7661
7662/// Whether the closed form above proves the sweep one pass.
7663fn parallel_turn_one_pass(screw: &Screw, split: &Split) -> bool {
7664    if screw.frame.is_some() || screw.turns.is_some() || screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 {
7665        return false;
7666    }
7667    let Shape::Revolved { origin, axis, meridian } = &split.shape else { return false };
7668    if axis.cross(screw.e).length() > 1e-12 {
7669        return false;
7670    }
7671    let apart = origin.sub(screw.a);
7672    let d = apart.sub(screw.e.scale(apart.dot(screw.e))).length();
7673    // Every section one disc: the outline less its pieces on the axis is one
7674    // run whose axial coordinate never turns back (lines; arcs without a
7675    // turning point inside), and its largest radius.
7676    // On the axis exactly: a wall any way off it is a bore, however thin.
7677    let on_axis = |p: [f64; 2]| p[0] == 0.0;
7678    let axial: Vec<bool> = meridian.iter().map(|piece| matches!(*piece, OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to))).collect();
7679    let changes = (0..axial.len()).filter(|&k| axial[k] != axial[(k + 1) % axial.len()]).count();
7680    if changes != 2 {
7681        return false; // the pieces on the axis are not one run of them
7682    }
7683    let mut direction = 0i32;
7684    let mut r_max = 0.0f64;
7685    let mut agree = |sign: i32| -> bool {
7686        if sign == 0 {
7687            return true;
7688        }
7689        if direction == 0 {
7690            direction = sign;
7691        }
7692        direction == sign
7693    };
7694    for piece in meridian {
7695        match *piece {
7696            OutlinePiece::Line { from, to } => {
7697                if on_axis(from) && on_axis(to) {
7698                    continue;
7699                }
7700                if from[0] < -1e-12 || to[0] < -1e-12 {
7701                    return false;
7702                }
7703                r_max = r_max.max(from[0]).max(to[0]);
7704                let rise = to[1] - from[1];
7705                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7706                    return false;
7707                }
7708            }
7709            OutlinePiece::Arc { centre, radius, start, end } => {
7710                let (lo, hi) = (start.min(end), start.max(end));
7711                if !(hi > lo) || !(radius > 0.0) {
7712                    return false;
7713                }
7714                // Turning points of the axial coordinate (cos a = 0) strictly inside.
7715                let first = ((lo - FRAC_PI_2) / PI).floor() as i64 + 1;
7716                if FRAC_PI_2 + first as f64 * PI < hi - 1e-12 {
7717                    return false;
7718                }
7719                // Its radial reach: the ends, and a = 0 (mod 2π) inside.
7720                let reach = |a: f64| centre[0] + radius * a.cos();
7721                r_max = r_max.max(reach(start)).max(reach(end));
7722                if (lo / TAU).ceil() * TAU < hi {
7723                    r_max = r_max.max(centre[0] + radius);
7724                }
7725                if centre[0] - radius < -1e-12 && (lo..hi).contains(&PI) {
7726                    return false;
7727                }
7728                let mid = 0.5 * (start + end);
7729                let rise = radius * mid.cos() * (end - start).signum();
7730                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7731                    return false;
7732                }
7733            }
7734            _ => return false,
7735        }
7736    }
7737    if !(r_max > 0.0 && r_max < d * (1.0 - 1e-9)) {
7738        return false;
7739    }
7740    let turn = (screw.omega * (screw.t1 - screw.t0)).abs();
7741    turn + 2.0 * (r_max / d).asin() < TAU * (1.0 - 1e-9)
7742}
7743
7744fn walk_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7745    let margin = 1e-9 * split.scale;
7746    let reach = ToolReach::of(screw, split);
7747    for face in body.shells.iter().flat_map(|s| &s.faces) {
7748        let step = if sliding.contains(&face.id) { 1e-3 * split.scale } else { 1e-6 * split.scale };
7749        let surface = &face.surface;
7750        // Probe inside the face: towards each corner of its loop from the
7751        // average of its corners (caps are convex in their parameters), and on
7752        // a grid for the four-sided walls.
7753        let mut corners: Vec<[f64; 2]> = Vec::new();
7754        for coedge in &face.loops[0].coedges {
7755            let domain = frag(coedge.pcurve.domain(), "domain")?;
7756            for k in 0..4 {
7757                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 4.0), "pcurve")?;
7758                corners.push([p.x, p.y]);
7759            }
7760        }
7761        let middle = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
7762        let middle = [middle[0] / corners.len() as f64, middle[1] / corners.len() as f64];
7763        let mut probes: Vec<[f64; 2]> = vec![middle];
7764        for c in &corners {
7765            for w in [0.25, 0.5, 0.75, 0.9, 0.99] {
7766                probes.push([middle[0] + (c[0] - middle[0]) * w, middle[1] + (c[1] - middle[1]) * w]);
7767            }
7768        }
7769        if surface.degree_v == 5 {
7770            let [u0, u1] = frag(surface.domain_u(), "domain")?;
7771            for i in 1..8 {
7772                for j in 1..64 {
7773                    probes.push([u0 + (u1 - u0) * i as f64 / 8.0, j as f64 / 64.0]);
7774                }
7775            }
7776        }
7777        let ([u0, u1], [v0, v1]) = (frag(surface.domain_u(), "domain")?, frag(surface.domain_v(), "domain")?);
7778        // Keep the probes inside the face's own loop (a face under a grazing
7779        // curve that dips is not convex in its parameters).
7780        let mut ring: Vec<[f64; 2]> = Vec::new();
7781        for coedge in &face.loops[0].coedges {
7782            let domain = frag(coedge.pcurve.domain(), "domain")?;
7783            for k in 0..32 {
7784                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 32.0), "pcurve")?;
7785                ring.push([p.x, p.y]);
7786            }
7787        }
7788        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])]));
7789        for i in 1..12 {
7790            for j in 1..12 {
7791                probes.push([lo[0] + (hi[0] - lo[0]) * i as f64 / 12.0, lo[1] + (hi[1] - lo[1]) * j as f64 / 12.0]);
7792            }
7793        }
7794        let inside = |q: [f64; 2]| -> bool {
7795            let mut crossings = 0;
7796            for k in 0..ring.len() {
7797                let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
7798                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]) {
7799                    crossings += 1;
7800                }
7801            }
7802            crossings % 2 == 1
7803        };
7804        for [u, v] in probes.into_iter().filter(|&q| inside(q)) {
7805            let p = frag(surface.evaluate(u, v), "probe")?;
7806            let (hu, hv) = (1e-6 * (u1 - u0), 1e-6 * (v1 - v0));
7807            // Derivatives, not raw differences: their cross product is
7808            // measured against an absolute zero.
7809            let (ua, ub, va, vb) = ((u - hu).max(u0), (u + hu).min(u1), (v - hv).max(v0), (v + hv).min(v1));
7810            let du = frag(surface.evaluate(ub, v), "probe")?.sub(frag(surface.evaluate(ua, v), "probe")?).scale(1.0 / (ub - ua));
7811            let dv = frag(surface.evaluate(u, vb), "probe")?.sub(frag(surface.evaluate(u, va), "probe")?).scale(1.0 / (vb - va));
7812            let Ok(n) = du.cross(dv).normalized() else { continue };
7813            let n = if face.same_sense { n } else { n.scale(-1.0) };
7814            if covered(screw, split, reach.as_ref(), p.add(n.scale(step)), n, margin)? {
7815                return Err(refuse("folds", format!("the sweep passes over a point twice (just outside its own face at {p:?}); not one pass")));
7816            }
7817        }
7818    }
7819    Ok(())
7820}
7821
7822
7823#[path = "solid_sweep_ring_fold.rs"]
7824mod ring_fold;
7825
7826#[path = "solid_sweep_ball_screw.rs"]
7827mod ball_screw;
7828
7829#[path = "solid_sweep_cone_across.rs"]
7830mod cone_across;
7831
7832
7833