Skip to main content

brep_construction/construction/
solid_sweep.rs

1//! The sweep of a SOLID: everything a tool passes through as it moves, inside a
2//! region the caller names (the workpiece it is cut from).
3//!
4//! ## What is built, and why it reduces to a plane
5//!
6//! The boundary of a swept solid is an envelope: at each instant the tool's
7//! surface touches the sweep along its characteristic curve (where the motion's
8//! velocity is tangent to the surface), and the sweep's wall is the union of
9//! those curves. In general that wall has no simpler description. In the three
10//! classes built here it is invariant under a motion, so the region is a planar
11//! region carried by that motion:
12//!
13//! | class | tool | invariance | planar region | solid |
14//! |---|---|---|---|---|
15//! | SCREW | a solid of revolution | the screw | the section square to the screw axis | a loft through screwed copies |
16//! | TURN | a solid of revolution | the turn | the meridian section | a revolve |
17//! | PLANAR | a prism | the prism's direction | the union of the moving outline | an extrude |
18//!
19//! For a SCREW (axial advance `c` per radian) the reduced coordinates of a point
20//! are `(ℓ, o) = (ρ, α − z/c)`, both unchanged by the screw; for a TURN they are
21//! `(ρ, z)`; for a PLANAR motion `(ρ, α)` in the workpiece's frame. In each the
22//! region is described per LEVEL `ℓ` as a set of intervals of `o`.
23//!
24//! ## The region engine
25//!
26//! At a level the interval ends are local extrema of `o` over the images of the
27//! tool's boundary: on a face patch `S(u, v)` (a meridian piece revolved; an
28//! outline piece carried through time) Newton solves `ℓ(S) = ℓ₀`,
29//! `det(∇o, ∇ℓ) = 0` from seeds on a grid; on a sharp edge (a meridian corner
30//! revolved; an outline vertex carried through time; the outline at either end of
31//! the motion) the ends are the roots of `ℓ = ℓ₀`. These are CANDIDATES; a
32//! membership oracle (does the point's preimage under the motion meet the tool,
33//! for some time in the range, by the tool's signed distance) classifies the
34//! gaps between them, so the intervals are exact at every level. This is what
35//! survives where the characteristic degenerates: a grinding wheel set along its
36//! helix has a whole circle of characteristic points, which tracing the
37//! characteristic by parameter cannot follow, but the level extremes can.
38//!
39//! The levels are scanned for EVENTS — an interval born at a tip, two lobes
40//! merging, an interval end changing the boundary piece it lies on — solved by
41//! bisection. Between events each interval end is a smooth function of the
42//! level, sampled at levels clustered at both ends (`ℓ − ℓa ∝ σ²`, so a square
43//! root tip is smooth in `σ`) and interpolated as its own cubic edge. Along
44//! each event level the boundary runs along the level itself (an arc, or a
45//! straight line for the turn) where the intervals above and below differ.
46//!
47//! ## The contract
48//!
49//! Each returned body equals the sweep inside the clip region: levels in
50//! `clip.radius`, axial positions in `clip.axial`, angles in `clip.angle`. The
51//! caller cuts a workpiece that lies inside that region. A screw or turn whose
52//! first or last position reaches the clip region is refused, because there the
53//! sweep is not invariant; a planar sweep includes its end positions exactly.
54//!
55//! FOLDS. Two lobes of a space can merge where one face's envelope turns back
56//! (the plus-cut wheel's arm tip, ρ = 20). Where the face's fold Newton reaches
57//! the point it is a critical point like a tip; where it cannot (that envelope's
58//! level varies by 1e-4 along it, too flat for nested differences), the merge is
59//! located from the gap's own √ law: gap² fitted as a quadratic in the level at
60//! three levels just below, its root the merge level (4e-11 from ρ = 20).
61//!
62//! ## Not built yet (refused, never approximated)
63//!
64//! - A source whose level is constant along it (a vertex turning about the
65//!   clip's own axis) reads as roots everywhere; keep the clip's axis off such
66//!   a turn's axis.
67//! - Motions outside the three classes (two turns about skew axes: the
68//!   tumbling torus).
69use crate::{
70    extrude_profile_brep, interpolate_curve, loft_profile_brep, make_arc, make_line,
71    revolve_profile_brep, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, OrRefuse, Vec3,
72};
73use std::f64::consts::{PI, TAU};
74
75/// One piece of a planar outline, in the outline's own 2D coordinates.
76#[derive(Clone, Copy, Debug, PartialEq)]
77pub enum OutlinePiece {
78    /// The segment from `from` to `to`.
79    Line { from: [f64; 2], to: [f64; 2] },
80    /// The arc about `centre` of `radius`, from angle `start` to angle `end`
81    /// (radians; `end < start` runs clockwise). A full circle is `0 → 2π`.
82    Arc { centre: [f64; 2], radius: f64, start: f64, end: f64 },
83}
84
85impl OutlinePiece {
86    fn point(&self, s: f64) -> [f64; 2] {
87        match *self {
88            OutlinePiece::Line { from, to } => {
89                [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s]
90            }
91            OutlinePiece::Arc { centre, radius, start, end } => {
92                let angle = start + (end - start) * s;
93                [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
94            }
95        }
96    }
97
98    fn is_full_circle(&self) -> bool {
99        matches!(*self, OutlinePiece::Arc { start, end, .. } if ((end - start).abs() - TAU).abs() < 1e-12)
100    }
101
102    /// Unsigned distance from `p` to the piece.
103    fn distance(&self, p: [f64; 2]) -> f64 {
104        match *self {
105            OutlinePiece::Line { from, to } => {
106                let d = [to[0] - from[0], to[1] - from[1]];
107                let length2 = d[0] * d[0] + d[1] * d[1];
108                let t = if length2 > 0.0 {
109                    (((p[0] - from[0]) * d[0] + (p[1] - from[1]) * d[1]) / length2).clamp(0.0, 1.0)
110                } else {
111                    0.0
112                };
113                let q = [from[0] + d[0] * t - p[0], from[1] + d[1] * t - p[1]];
114                q[0].hypot(q[1])
115            }
116            OutlinePiece::Arc { centre, radius, start, end } => {
117                let v = [p[0] - centre[0], p[1] - centre[1]];
118                let angle = v[1].atan2(v[0]);
119                if self.is_full_circle() || angle_within(angle, start, end) {
120                    (v[0].hypot(v[1]) - radius).abs()
121                } else {
122                    let a = self.point(0.0);
123                    let b = self.point(1.0);
124                    (a[0] - p[0]).hypot(a[1] - p[1]).min((b[0] - p[0]).hypot(b[1] - p[1]))
125                }
126            }
127        }
128    }
129
130    /// Crossings of the ray from `p` towards +x with the piece (for the parity
131    /// inside test). Half-open in y so a vertex is counted once.
132    fn ray_crossings(&self, p: [f64; 2]) -> usize {
133        match *self {
134            OutlinePiece::Line { from, to } => {
135                let (a, b) = (from, to);
136                if (a[1] > p[1]) != (b[1] > p[1]) {
137                    let x = a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
138                    usize::from(x > p[0])
139                } else {
140                    0
141                }
142            }
143            OutlinePiece::Arc { centre, radius, start, end } => {
144                let dy = p[1] - centre[1];
145                if dy.abs() >= radius {
146                    return 0;
147                }
148                let dx = (radius * radius - dy * dy).sqrt();
149                let mut count = 0;
150                for x in [centre[0] - dx, centre[0] + dx] {
151                    if x <= p[0] {
152                        continue;
153                    }
154                    let angle = dy.atan2(x - centre[0]);
155                    if self.is_full_circle() || angle_within(angle, start, end) {
156                        // Half-open at the arc's own ends, like the segment rule:
157                        // count an end only where the arc leaves upwards.
158                        count += 1;
159                    }
160                }
161                count
162            }
163        }
164    }
165}
166
167/// Is `angle` on the arc that runs from `start` to `end` (either sense)?
168fn angle_within(angle: f64, start: f64, end: f64) -> bool {
169    let (low, high) = if end >= start { (start, end) } else { (end, start) };
170    let shifted = low + (angle - low).rem_euclid(TAU);
171    shifted <= high
172}
173
174fn scale_of(outline: &[OutlinePiece]) -> f64 {
175    outline
176        .iter()
177        .flat_map(|piece| [piece.point(0.0), piece.point(1.0)])
178        .map(|p| p[0].abs().max(p[1].abs()))
179        .fold(1.0f64, f64::max)
180}
181
182/// Signed distance to a closed outline (negative inside).
183pub fn outline_signed_distance(outline: &[OutlinePiece], p: [f64; 2]) -> f64 {
184    let distance = outline
185        .iter()
186        .map(|piece| piece.distance(p))
187        .fold(f64::INFINITY, f64::min);
188    let crossings: usize = outline.iter().map(|piece| piece.ray_crossings(p)).sum();
189    if crossings % 2 == 1 {
190        -distance
191    } else {
192        distance
193    }
194}
195
196fn validate_outline(outline: &[OutlinePiece], what: &str) -> Result<(), KernelRefusal> {
197    if outline.is_empty() {
198        return Err(KernelRefusal::input(
199            KernelStage::Collect,
200            "outline_empty",
201            format!("sweepSolidWithin: the {what} outline is empty"),
202        ));
203    }
204    let scale = outline
205        .iter()
206        .flat_map(|piece| [piece.point(0.0), piece.point(1.0)])
207        .map(|p| p[0].abs().max(p[1].abs()))
208        .fold(1.0f64, f64::max);
209    for (index, piece) in outline.iter().enumerate() {
210        let next = &outline[(index + 1) % outline.len()];
211        let a = piece.point(1.0);
212        let b = next.point(0.0);
213        if (a[0] - b[0]).hypot(a[1] - b[1]) > 1e-9 * scale {
214            return Err(KernelRefusal::input(
215                KernelStage::Collect,
216                "outline_open",
217                format!("sweepSolidWithin: the {what} outline is not closed after piece {index}"),
218            ));
219        }
220    }
221    Ok(())
222}
223
224/// The moving tool.
225#[derive(Clone, Debug)]
226pub enum SweptTool {
227    /// A solid of revolution: the region `meridian` bounds in the half-plane
228    /// spanned by `radial` (first coordinate, the distance from the axis, ≥ 0)
229    /// and `axis_direction` (second coordinate), turned about the axis through
230    /// `axis_origin`.
231    Revolved {
232        axis_origin: Vec3,
233        axis_direction: Vec3,
234        radial: Vec3,
235        meridian: Vec<OutlinePiece>,
236    },
237    /// A prism: the region `outline` bounds in the plane through `origin`
238    /// spanned by `x_axis` and `normal × x_axis`, extended along `normal` from
239    /// `from` to `to`.
240    Prism {
241        origin: Vec3,
242        normal: Vec3,
243        x_axis: Vec3,
244        outline: Vec<OutlinePiece>,
245        from: f64,
246        to: f64,
247    },
248    /// A bar: the region `section` bounds (curves end to end round a closed
249    /// loop, lying in the plane through `origin` square to `normal`), extended
250    /// along `normal` from height `from` to `to`. Its sides lean inward by
251    /// `draft` radians: at height `h` the section is the given one moved
252    /// inward by `h·tan(draft)` (outward where that is negative). Swept by a
253    /// screw about the clip's axis, whichever way the bar points.
254    Bar {
255        origin: Vec3,
256        normal: Vec3,
257        section: Vec<NurbsCurve>,
258        from: f64,
259        to: f64,
260        draft: f64,
261    },
262}
263
264/// One elementary motion, linear in the motion parameter `t`: a turn of
265/// `turn·t` radians, right-handed about the axis through `axis_origin` along
266/// `axis_direction`, together with an advance of `advance·t` along it. A turn
267/// alone is `advance = 0`, a slide alone is `turn = 0`.
268#[derive(Clone, Copy, Debug)]
269pub struct ScrewStep {
270    pub axis_origin: Vec3,
271    pub axis_direction: Vec3,
272    pub turn: f64,
273    pub advance: f64,
274}
275
276/// A rigid motion: the steps applied in order (the first to the tool first),
277/// for `t` from `from` to `to`.
278#[derive(Clone, Debug)]
279pub struct SolidMotion {
280    pub steps: Vec<ScrewStep>,
281    pub from: f64,
282    pub to: f64,
283}
284
285/// The region the result must agree with the sweep in, about an axis: levels
286/// (distance from the axis) in `radius`, axial positions in `axial` (measured
287/// from `axis_origin`), and polar angles in `angle` (from `reference`,
288/// right-handed about the axis), when given.
289#[derive(Clone, Copy, Debug)]
290pub struct SweepClip {
291    pub axis_origin: Vec3,
292    pub axis_direction: Vec3,
293    pub reference: Vec3,
294    pub radius: [f64; 2],
295    pub axial: [f64; 2],
296    pub angle: Option<[f64; 2]>,
297}
298
299/// The prefix of every refusal of this operation.
300pub const SOLID_SWEEP_REFUSAL: &str = "sweepSolidWithin";
301
302/// Words of the refusal for a level the sweep covers at every angle.
303const WHOLE_LEVEL: &str = "the sweep covers every angle at level";
304
305/// Turns of a thread each row of faces carries (measured: shorter rows cost more
306/// meshing, longer ones more edge reading).
307const TURNS_PER_ROW: f64 = 2.0;
308
309/// `BREP_SWEEP_THREAD_ROWS` (default on; `=0` one body-long face per wall and the
310/// boolean for the clip): a thread is built a few turns at a time, since readings
311/// over a face cost the square of its length.
312fn thread_rows_on() -> bool {
313    crate::switch!("BREP_SWEEP_THREAD_ROWS", true)
314}
315
316/// `BREP_SWEEP_WHOLE_LEVEL` (default on; `=0` restores the refusal): a screw's
317/// sweep whose turns meet at a crest, built as the clip less what stays.
318fn whole_level_on() -> bool {
319    crate::switch!("BREP_SWEEP_WHOLE_LEVEL", true)
320}
321
322/// `BREP_SWEEP_SCREW_CARRY` (default on; `=0` restores the cubic loft): every
323/// screw sweep's walls are carried along the screw to high order, as a bar's
324/// and a crest's always are, instead of lofted as a cubic through 64 sections a
325/// turn (which stands r·h⁴/384 off the screw: 1e-6 at a groove's floor).
326fn screw_carry_on() -> bool {
327    crate::switch!("BREP_SWEEP_SCREW_CARRY", true)
328}
329
330/// `BREP_SWEEP_APEX_TIP` (default on; `=0` off): a point of a solid of
331/// revolution on its own axis (a cone's apex) is a critical point of the faces
332/// that meet there. It revolves into nothing, so no edge carries it, and a
333/// groove whose tip it cuts would end where bisection first sees the level's
334/// contour (3.5e-7 short of a cone point's tip) instead of at the point itself.
335fn apex_tip_on() -> bool {
336    crate::switch!("BREP_SWEEP_APEX_TIP", true)
337}
338
339/// `BREP_SWEEP_LEAN_WALLS` (default on; `=0` restores the quintic through 48
340/// sections a turn and the cubic through every sample): a carried screw
341/// sweep's walls in few spans. Along the screw, the carry is of degree 2·`LEAN_CARRY_ORDER` + 1
342/// through that many derivatives, `LEAN_CARRY_PER_TURN` spans a turn, instead
343/// of the quintic through 48. Across it, each boundary piece is a quintic
344/// fitted to its exact envelope samples and checked against the exact envelope
345/// between them (`lean_fit_piece`), instead of the cubic through all of them.
346/// Off, a wall has some 100 by 84 spans: a reader that integrates over its
347/// spans pays their product.
348fn lean_walls_on() -> bool {
349    crate::switch!("BREP_SWEEP_LEAN_WALLS", true)
350}
351
352/// Derivatives the lean carry matches at each span's ends (degree 2m + 1, C^m
353/// at the joints). Its error is r·(h/2)^(2m+2)/(2m+2)!: at m = 4 and eight
354/// spans a turn, 2.4e-11·r.
355const LEAN_CARRY_ORDER: usize = 4;
356
357/// Spans of the lean carry a turn.
358const LEAN_CARRY_PER_TURN: f64 = 8.0;
359
360/// How near (of the scale) the exact envelope a lean boundary piece passes at
361/// the mid-points between its samples, where the cubic it replaces passes
362/// further from it: a tenth of what `sample_band` holds that cubic to.
363const LEAN_FIT_TOLERANCE: f64 = 1e-9;
364
365fn refuse(what: &'static str, message: String) -> KernelRefusal {
366    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_REFUSAL}: {message}"))
367}
368
369fn rotate(x: Vec3, origin: Vec3, axis: Vec3, angle: f64) -> Vec3 {
370    origin.add(x.sub(origin).rotate_about(axis, angle))
371}
372
373impl ScrewStep {
374    fn apply(&self, t: f64, x: Vec3, axis: Vec3) -> Vec3 {
375        rotate(x, self.axis_origin, axis, self.turn * t).add(axis.scale(self.advance * t))
376    }
377    fn invert(&self, t: f64, x: Vec3, axis: Vec3) -> Vec3 {
378        rotate(x.sub(axis.scale(self.advance * t)), self.axis_origin, axis, -self.turn * t)
379    }
380}
381
382/// Orthonormal frame of the clip: (ex, ey, ez).
383#[derive(Clone, Copy, Debug)]
384struct Frame {
385    origin: Vec3,
386    ex: Vec3,
387    ey: Vec3,
388    ez: Vec3,
389}
390
391impl Frame {
392    fn local(&self, x: Vec3) -> [f64; 3] {
393        let d = x.sub(self.origin);
394        [d.dot(self.ex), d.dot(self.ey), d.dot(self.ez)]
395    }
396    fn world(&self, p: [f64; 3]) -> Vec3 {
397        self.origin
398            .add(self.ex.scale(p[0]))
399            .add(self.ey.scale(p[1]))
400            .add(self.ez.scale(p[2]))
401    }
402}
403
404#[derive(Clone, Copy, Debug, PartialEq)]
405enum Class {
406    /// Axial advance per radian of the screw, in the clip frame (nonzero).
407    Screw(f64),
408    Turn,
409    Planar,
410}
411
412/// A tool-boundary source: a face patch over a 2D parameter box, or an edge
413/// over a 1D parameter interval. `periodic` marks a parameter that wraps.
414#[derive(Clone, Copy, Debug)]
415enum Source {
416    /// Revolved meridian piece `piece`, parameters (s ∈ [0,1], φ ∈ [0,2π)).
417    RevolvedFace { piece: usize },
418    /// Revolved meridian corner at the start of piece `piece`, parameter φ.
419    RevolvedCorner { piece: usize },
420    /// Prism outline piece `piece` carried through time: (s ∈ [0,1], t).
421    PrismFace { piece: usize },
422    /// Prism outline vertex at the start of piece `piece`, parameter t.
423    PrismVertex { piece: usize },
424    /// Prism outline piece `piece` at the motion's first (`end = false`) or last
425    /// position, parameter s.
426    PrismEnd { piece: usize, end: bool },
427    /// Under a screw, at the tool's own place (the screw's reduction is invariant
428    /// along it): side face of outline piece `piece`, (s ∈ [0,1], height).
429    ScrewPrismSide { piece: usize },
430    /// Under a screw: the upright edge at the start of piece `piece`, parameter height.
431    ScrewPrismEdge { piece: usize },
432    /// Under a screw: outline piece `piece` at the prism's low (`end = false`) or
433    /// high end, parameter s. An end cap itself maps one-to-one into the reduced
434    /// plane (polar coordinates at a fixed height), so only its rim can bound.
435    ScrewPrismRim { piece: usize, end: bool },
436    /// A bar's side on section curve `piece`, at its own place: (s ∈ [0,1], height).
437    BarSide { piece: usize },
438    /// A bar's upright edge at the start of section curve `piece`, parameter height.
439    BarEdge { piece: usize },
440    /// A bar's section curve `piece` at its low (`end = false`) or high end, parameter s.
441    BarRim { piece: usize, end: bool },
442}
443
444struct Engine<'a> {
445    tool: &'a SweptTool,
446    motion: &'a SolidMotion,
447    axes: Vec<Vec3>,
448    frame: Frame,
449    class: Class,
450    clip: &'a SweepClip,
451    /// The tool as a bar, where it is swept as one.
452    bar: Option<crate::solid_sweep_bar::Bar>,
453    /// The clip was narrowed to a crest level: below it some material is left.
454    crest_gap: bool,
455    sources: Vec<Source>,
456    /// Per face source: its parameter grid (nu × nv) of reduced coordinates.
457    grids: Vec<Option<Grid>>,
458    /// Per source: its critical points of the level, as (level, o).
459    critical: Vec<Vec<(f64, f64)>>,
460    /// Per face source: the parameters of its critical points (tips), which
461    /// seed the extremum Newton where the level's contour is smaller than a cell.
462    critical_params: Vec<Vec<(f64, f64)>>,
463    /// Angular `o` (wraps at 2π) or not.
464    angular: bool,
465    /// Prism height (along its normal) the planar sources are evaluated at.
466    prism_height: f64,
467    scale: f64,
468    /// `intervals_at` by level bits: the sampling revisits levels (a refined
469    /// band keeps every level of the coarser one).
470    cache: std::cell::RefCell<std::collections::HashMap<u64, Vec<Interval>>>,
471    /// The motion ends where it began as a set (the plus wheel: one turn of the
472    /// wheel, one and a half of the tool), so there are no end positions; piece
473    /// `k` at the end continues as piece `wrap[k]` at the start.
474    wrap: Option<Vec<usize>>,
475    /// Debug counters: (levels evaluated, oracle calls, oracle steps, seconds in
476    /// candidates, seconds in the oracle).
477    counters: std::cell::Cell<(usize, usize, usize, f64, f64)>,
478}
479
480struct Grid {
481    nu: usize,
482    nv: usize,
483    u: [f64; 2],
484    v: [f64; 2],
485    v_periodic: bool,
486    values: Vec<(f64, f64)>,
487}
488
489/// One interval of the region at a level, with the sources of its ends.
490#[derive(Clone, Copy, Debug)]
491struct Interval {
492    lo: f64,
493    hi: f64,
494    lo_source: usize,
495    hi_source: usize,
496}
497
498fn wrap_pi(angle: f64) -> f64 {
499    let wrapped = (angle + PI).rem_euclid(TAU) - PI;
500    wrapped
501}
502
503impl<'a> Engine<'a> {
504    fn motion_apply(&self, t: f64, x: Vec3) -> Vec3 {
505        self.motion
506            .steps
507            .iter()
508            .zip(&self.axes)
509            .fold(x, |x, (step, axis)| step.apply(t, x, *axis))
510    }
511
512    fn motion_invert(&self, t: f64, x: Vec3) -> Vec3 {
513        self.motion
514            .steps
515            .iter()
516            .zip(&self.axes)
517            .rev()
518            .fold(x, |x, (step, axis)| step.invert(t, x, *axis))
519    }
520
521    /// Reduced coordinates of a clip-frame point.
522    fn reduce(&self, p: [f64; 3]) -> (f64, f64) {
523        let level = p[0].hypot(p[1]);
524        match self.class {
525            Class::Screw(c) => (level, p[1].atan2(p[0]) - p[2] / c),
526            Class::Turn => (level, p[2]),
527            Class::Planar => (level, p[1].atan2(p[0])),
528        }
529    }
530
531    fn tool_signed_distance(&self, x: Vec3) -> f64 {
532        if let Some(bar) = &self.bar {
533            return bar.signed_distance(x);
534        }
535        match self.tool {
536            SweptTool::Bar { .. } => f64::INFINITY,
537            SweptTool::Revolved { axis_origin, axis_direction, meridian, .. } => {
538                let axis = axis_direction.normalized_or(*axis_direction);
539                let d = x.sub(*axis_origin);
540                let e = d.dot(axis);
541                let radial = d.sub(axis.scale(e)).length();
542                outline_signed_distance(meridian, [radial, e])
543            }
544            SweptTool::Prism { origin, normal, x_axis, outline, from, to } => {
545                let n = normal.normalized_or(*normal);
546                let xa = x_axis.normalized_or(*x_axis);
547                let ya = n.cross(xa);
548                let d = x.sub(*origin);
549                let h = d.dot(n);
550                let planar = outline_signed_distance(outline, [d.dot(xa), d.dot(ya)]);
551                planar.max(from - h).max(h - to)
552            }
553        }
554    }
555
556    /// The world point of a source at its parameters (at the tool's own place
557    /// for revolved tools; carried by the motion for prisms).
558    fn source_point(&self, source: Source, u: f64, v: f64) -> Vec3 {
559        if let Some(bar) = &self.bar {
560            match source {
561                Source::BarSide { piece } => return bar.side(piece, u, v),
562                Source::BarEdge { piece } => return bar.joint(piece, u),
563                Source::BarRim { piece, end } => return bar.side(piece, u, if end { bar.to } else { bar.from }),
564                _ => {}
565            }
566        }
567        match (self.tool, source) {
568            (SweptTool::Bar { origin, .. }, _) => *origin,
569            (SweptTool::Revolved { axis_origin, axis_direction, radial, meridian }, _) => {
570                let axis = axis_direction.normalized_or(*axis_direction);
571                let r0 = radial.sub(axis.scale(radial.dot(axis))).normalized_or(*radial);
572                let r1 = axis.cross(r0);
573                let (m, phi) = match source {
574                    Source::RevolvedFace { piece } => (meridian[piece].point(u), v),
575                    Source::RevolvedCorner { piece } => (meridian[piece].point(0.0), u),
576                    _ => unreachable!(),
577                };
578                axis_origin
579                    .add(r0.scale(m[0] * phi.cos()))
580                    .add(r1.scale(m[0] * phi.sin()))
581                    .add(axis.scale(m[1]))
582            }
583            (SweptTool::Prism { origin, normal, x_axis, outline, from, to }, _) => {
584                let n = normal.normalized_or(*normal);
585                let xa = x_axis.normalized_or(*x_axis);
586                let ya = n.cross(xa);
587                let at_own_place = match source {
588                    Source::ScrewPrismSide { piece } => Some((outline[piece].point(u), v)),
589                    Source::ScrewPrismEdge { piece } => Some((outline[piece].point(0.0), u)),
590                    Source::ScrewPrismRim { piece, end } => Some((outline[piece].point(u), if end { *to } else { *from })),
591                    _ => None,
592                };
593                if let Some((q, h)) = at_own_place {
594                    return origin.add(xa.scale(q[0])).add(ya.scale(q[1])).add(n.scale(h));
595                }
596                let (q, t) = match source {
597                    Source::PrismFace { piece } => (outline[piece].point(u), v),
598                    Source::PrismVertex { piece } => (outline[piece].point(0.0), u),
599                    Source::PrismEnd { piece, end } => (
600                        outline[piece].point(u),
601                        if end { self.motion.to } else { self.motion.from },
602                    ),
603                    _ => unreachable!(),
604                };
605                let x = origin
606                    .add(xa.scale(q[0]))
607                    .add(ya.scale(q[1]))
608                    .add(n.scale(self.prism_height));
609                self.motion_apply(t, x)
610            }
611        }
612    }
613
614    fn source_reduced(&self, source: Source, u: f64, v: f64) -> (f64, f64) {
615        self.reduce(self.frame.local(self.source_point(source, u, v)))
616    }
617
618    fn is_face(source: Source) -> bool {
619        matches!(source, Source::RevolvedFace { .. } | Source::PrismFace { .. } | Source::ScrewPrismSide { .. } | Source::BarSide { .. })
620    }
621
622    /// Parameter domain of a source: (u range, v range, v periodic).
623    fn domain(&self, source: Source) -> ([f64; 2], [f64; 2], bool) {
624        let time = [self.motion.from, self.motion.to];
625        match source {
626            Source::RevolvedFace { .. } => ([0.0, 1.0], [0.0, TAU], true),
627            Source::RevolvedCorner { .. } => ([0.0, TAU], [0.0, 0.0], false),
628            Source::PrismFace { .. } => ([0.0, 1.0], time, false),
629            Source::PrismVertex { .. } => (time, [0.0, 0.0], false),
630            Source::PrismEnd { .. } => ([0.0, 1.0], [0.0, 0.0], false),
631            Source::ScrewPrismSide { .. } => ([0.0, 1.0], self.prism_extent(), false),
632            Source::ScrewPrismEdge { .. } => (self.prism_extent(), [0.0, 0.0], false),
633            Source::ScrewPrismRim { .. } => ([0.0, 1.0], [0.0, 0.0], false),
634            Source::BarSide { .. } => ([0.0, 1.0], self.prism_extent(), false),
635            Source::BarEdge { .. } => (self.prism_extent(), [0.0, 0.0], false),
636            Source::BarRim { .. } => ([0.0, 1.0], [0.0, 0.0], false),
637        }
638    }
639
640    fn prism_extent(&self) -> [f64; 2] {
641        if let Some(bar) = &self.bar {
642            return [bar.from, bar.to];
643        }
644        match self.tool {
645            SweptTool::Bar { from, to, .. } => [*from, *to],
646            SweptTool::Prism { from, to, .. } => [*from, *to],
647            SweptTool::Revolved { .. } => [0.0, 0.0],
648        }
649    }
650
651    /// Is the face's first parameter periodic (a full circle in the meridian or
652    /// outline, which has no corner to bound it)?
653    fn u_periodic(&self, source: Source) -> bool {
654        match (self.tool, source) {
655            (_, Source::BarSide { .. }) => self.bar.as_ref().is_some_and(|bar| bar.periodic),
656            (SweptTool::Revolved { meridian, .. }, Source::RevolvedFace { piece }) => meridian[piece].is_full_circle(),
657            (SweptTool::Prism { outline, .. }, Source::PrismFace { piece } | Source::ScrewPrismSide { piece }) => outline[piece].is_full_circle(),
658            _ => false,
659        }
660    }
661
662    fn o_difference(&self, a: f64, b: f64) -> f64 {
663        if self.angular {
664            wrap_pi(a - b)
665        } else {
666            a - b
667        }
668    }
669
670    /// Newton on {ℓ = level, det(∇o, ∇ℓ) = 0} over a face source.
671    fn face_extremum(&self, source: Source, level: f64, mut u: f64, mut v: f64) -> Option<(f64, f64, f64)> {
672        let (ur, vr, periodic) = self.domain(source);
673        let hu = 1e-6 * (ur[1] - ur[0]).max(1e-3);
674        let hv = 1e-6 * (vr[1] - vr[0]).max(1e-3);
675        let residual = |u: f64, v: f64| -> [f64; 2] {
676            let (l, o) = self.source_reduced(source, u, v);
677            let (lu1, ou1) = self.source_reduced(source, u + hu, v);
678            let (lu0, ou0) = self.source_reduced(source, u - hu, v);
679            let (lv1, ov1) = self.source_reduced(source, u, v + hv);
680            let (lv0, ov0) = self.source_reduced(source, u, v - hv);
681            let (lu, lv) = ((lu1 - lu0) / (2.0 * hu), (lv1 - lv0) / (2.0 * hv));
682            let ou = self.o_difference(ou1, ou0) / (2.0 * hu);
683            let ov = self.o_difference(ov1, ov0) / (2.0 * hv);
684            // det scaled by the level's gradient so its size is that of ∇o.
685            let norm = lu.hypot(lv).max(1e-300);
686            let _ = o;
687            [l - level, (ou * lv - ov * lu) / norm]
688        };
689        let mut f = residual(u, v);
690        for _ in 0..60 {
691            let (du_step, dv_step) = (hu * 10.0, hv * 10.0);
692            let fu1 = residual(u + du_step, v);
693            let fu0 = residual(u - du_step, v);
694            let fv1 = residual(u, v + dv_step);
695            let fv0 = residual(u, v - dv_step);
696            let j = [
697                [(fu1[0] - fu0[0]) / (2.0 * du_step), (fv1[0] - fv0[0]) / (2.0 * dv_step)],
698                [(fu1[1] - fu0[1]) / (2.0 * du_step), (fv1[1] - fv0[1]) / (2.0 * dv_step)],
699            ];
700            let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
701            if !det.is_finite() || det.abs() < 1e-300 {
702                return None;
703            }
704            let du = -(f[0] * j[1][1] - f[1] * j[0][1]) / det;
705            let dv = -(j[0][0] * f[1] - j[1][0] * f[0]) / det;
706            let norm0 = f[0].hypot(f[1]);
707            let mut step = 1.0;
708            let mut accepted = false;
709            while step > 1e-4 {
710                let (nu, nv) = (u + step * du, v + step * dv);
711                let candidate = residual(nu, nv);
712                if candidate[0].hypot(candidate[1]) < norm0 || norm0 < 1e-14 * self.scale {
713                    u = nu;
714                    v = nv;
715                    f = candidate;
716                    accepted = true;
717                    break;
718                }
719                step *= 0.5;
720            }
721            if !accepted {
722                break;
723            }
724            if (du * step).abs() < 1e-15 * (ur[1] - ur[0]) && (dv * step).abs() < 1e-15 * (vr[1] - vr[0]).max(1.0) {
725                break;
726            }
727        }
728        if periodic {
729            v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
730        }
731        if self.u_periodic(source) {
732            u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
733        }
734        let tolerance = 1e-9;
735        if u < ur[0] - tolerance || u > ur[1] + tolerance || (!periodic && (v < vr[0] - tolerance || v > vr[1] + tolerance)) {
736            return None;
737        }
738        if f[0].abs() > 1e-10 * self.scale || f[1].abs() > 1e-6 {
739            return None;
740        }
741        let (l, o) = self.source_reduced(source, u.clamp(ur[0], ur[1]), v);
742        Some((l, o, u))
743    }
744
745    fn build_grid(&self, source: Source) -> Grid {
746        let (u, v, v_periodic) = self.domain(source);
747        let (nu, nv) = match source {
748            Source::RevolvedFace { .. } => (64, 256),
749            Source::ScrewPrismSide { .. } => (64, 64),
750            Source::BarSide { .. } => (128, 64),
751            _ => {
752                let turn = self
753                    .motion
754                    .steps
755                    .iter()
756                    .map(|step| step.turn.abs())
757                    .fold(0.0, f64::max)
758                    * (self.motion.to - self.motion.from).abs();
759                (48, ((turn * 128.0) as usize).clamp(256, 4096))
760            }
761        };
762        let mut values = Vec::with_capacity(nu * nv);
763        for i in 0..nu {
764            let uu = u[0] + (u[1] - u[0]) * i as f64 / (nu - 1) as f64;
765            for j in 0..nv {
766                let vv = if v_periodic {
767                    v[0] + (v[1] - v[0]) * j as f64 / nv as f64
768                } else {
769                    v[0] + (v[1] - v[0]) * j as f64 / (nv - 1) as f64
770                };
771                values.push(self.source_reduced(source, uu, vv));
772            }
773        }
774        Grid { nu, nv, u, v, v_periodic, values }
775    }
776
777    fn grid_param(grid: &Grid, i: usize, j: usize) -> (f64, f64) {
778        let u = grid.u[0] + (grid.u[1] - grid.u[0]) * i as f64 / (grid.nu - 1) as f64;
779        let v = if grid.v_periodic {
780            grid.v[0] + (grid.v[1] - grid.v[0]) * j as f64 / grid.nv as f64
781        } else {
782            grid.v[0] + (grid.v[1] - grid.v[0]) * j as f64 / (grid.nv - 1) as f64
783        };
784        (u, v)
785    }
786
787    /// Candidates of one source at a level: (o, source index).
788    fn source_candidates(&self, index: usize, level: f64, out: &mut Vec<(f64, usize)>) {
789        let source = self.sources[index];
790        if Self::is_face(source) {
791            let grid = self.grids[index].as_ref().expect("face grid");
792            // Crossings of the level along grid edges, then seeds where o is a
793            // local extremum among the crossings of neighbouring cells.
794            let at = |i: usize, j: usize| grid.values[i * grid.nv + j % grid.nv];
795            let jmax = if grid.v_periodic { grid.nv } else { grid.nv - 1 };
796            let mut crossings: Vec<(usize, usize, f64, f64, f64)> = Vec::new();
797            for i in 0..grid.nu {
798                for j in 0..jmax {
799                    let a = at(i, j);
800                    let b = at(i, j + 1);
801                    if (a.0 - level) * (b.0 - level) <= 0.0 && a.0 != b.0 {
802                        let w = (level - a.0) / (b.0 - a.0);
803                        let o = a.1 + self.o_difference(b.1, a.1) * w;
804                        let (u, v0) = Self::grid_param(grid, i, j);
805                        let (_, v1) = Self::grid_param(grid, i, j + 1);
806                        let v1 = if grid.v_periodic && j + 1 == grid.nv { grid.v[1] } else { v1 };
807                        crossings.push((i, j, o, u, v0 + (v1 - v0) * w));
808                    }
809                }
810            }
811            for i in 0..grid.nu.saturating_sub(1) {
812                for j in 0..grid.nv {
813                    let a = at(i, j);
814                    let b = at(i + 1, j);
815                    if (a.0 - level) * (b.0 - level) <= 0.0 && a.0 != b.0 {
816                        let w = (level - a.0) / (b.0 - a.0);
817                        let o = a.1 + self.o_difference(b.1, a.1) * w;
818                        let (u0, v) = Self::grid_param(grid, i, j);
819                        let (u1, _) = Self::grid_param(grid, i + 1, j);
820                        crossings.push((i, j, o, u0 + (u1 - u0) * w, v));
821                    }
822                }
823            }
824            let mut found: Vec<(f64, f64, f64)> = Vec::new();
825            let push = |found: &mut Vec<(f64, f64, f64)>, result: Option<(f64, f64, f64)>| {
826                if let Some((_, o_new, u_new)) = result {
827                    if !found
828                        .iter()
829                        .any(|&(o_old, u_old, _)| self.o_difference(o_old, o_new).abs() < 1e-11 && (u_old - u_new).abs() < 1e-6)
830                    {
831                        found.push((o_new, u_new, 0.0));
832                    }
833                }
834            };
835            // Near a tip the contour can be smaller than a cell: seed from the
836            // tip itself, pushed off it in four directions.
837            if let Some(params) = self.critical_params.get(index) {
838                let (ur, vr, _) = self.domain(source);
839                for &(u, v) in params {
840                    for (du, dv) in [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] {
841                        let (su, sv) = (u + du * 1e-3 * (ur[1] - ur[0]), v + dv * 1e-3 * (vr[1] - vr[0]));
842                        push(&mut found, self.face_extremum(source, level, su, sv));
843                    }
844                }
845            }
846            let mut buckets: std::collections::HashMap<(usize, usize), Vec<usize>> = std::collections::HashMap::new();
847            for (k, &(i, j, _, _, _)) in crossings.iter().enumerate() {
848                buckets.entry((i, j)).or_default().push(k);
849            }
850            for (k, &(i, j, o, u, v)) in crossings.iter().enumerate() {
851                let mut is_max = true;
852                let mut is_min = true;
853                let mut neighbours = Vec::new();
854                for di in [-1i64, 0, 1] {
855                    for dj in [-1i64, 0, 1] {
856                        let i2 = i as i64 + di;
857                        if i2 < 0 {
858                            continue;
859                        }
860                        let j2 = j as i64 + dj;
861                        let j2 = if grid.v_periodic { j2.rem_euclid(grid.nv as i64) } else { j2 };
862                        if j2 < 0 {
863                            continue;
864                        }
865                        if let Some(list) = buckets.get(&(i2 as usize, j2 as usize)) {
866                            neighbours.extend(list.iter().copied());
867                        }
868                    }
869                }
870                for m in neighbours {
871                    if m == k {
872                        continue;
873                    }
874                    let o2 = crossings[m].2;
875                    {
876                        let d = self.o_difference(o2, o);
877                        if d > 0.0 {
878                            is_max = false;
879                        }
880                        if d < 0.0 {
881                            is_min = false;
882                        }
883                    }
884                }
885                if !(is_max || is_min) {
886                    continue;
887                }
888                push(&mut found, self.face_extremum(source, level, u, v));
889            }
890            out.extend(found.into_iter().map(|(o, _, _)| (o, index)));
891        } else {
892            let (range, _, _) = self.domain(source);
893            let periodic = matches!(source, Source::RevolvedCorner { .. });
894            let n = match source {
895                Source::RevolvedCorner { .. }
896                | Source::PrismEnd { .. }
897                | Source::ScrewPrismEdge { .. }
898                | Source::ScrewPrismRim { .. }
899                | Source::BarEdge { .. }
900                | Source::BarRim { .. } => 1024,
901                _ => self.grids_len_for_time(),
902            };
903            let _ = periodic;
904            // The uniform samples, with the curve's own level extrema merged in:
905            // near a tip the two roots of `ℓ = ℓ₀` fall either side of the extremum,
906            // closer than any fixed step, and would be missed together.
907            let mut samples: Vec<f64> = (0..=n).map(|k| range[0] + (range[1] - range[0]) * k as f64 / n as f64).collect();
908            if let Some(extra) = self.critical_params.get(index) {
909                samples.extend(extra.iter().map(|p| p.0).filter(|t| *t > range[0] && *t < range[1]));
910                samples.sort_by(|a, b| a.total_cmp(b));
911            }
912            let mut previous = self.source_reduced(source, samples[0], 0.0).0 - level;
913            for k in 1..samples.len() {
914                let p = samples[k];
915                let value = self.source_reduced(source, p, 0.0).0 - level;
916                if previous == 0.0 {
917                    // A root exactly on the sample (a band's end level on the
918                    // curve's own end): bisecting from a zero walks to the far
919                    // end of the bracket, a whole sample step away.
920                    out.push((self.source_reduced(source, samples[k - 1], 0.0).1, index));
921                } else if previous * value < 0.0 {
922                    let (mut a, mut b) = (samples[k - 1], p);
923                    let fa0 = previous;
924                    for _ in 0..200 {
925                        let m = 0.5 * (a + b);
926                        let fm = self.source_reduced(source, m, 0.0).0 - level;
927                        if (fm < 0.0) == (fa0 < 0.0) && fm != 0.0 {
928                            a = m;
929                        } else {
930                            b = m;
931                        }
932                        if (b - a).abs() < 1e-15 * (range[1] - range[0]).abs().max(1.0) {
933                            break;
934                        }
935                    }
936                    let (_, o) = self.source_reduced(source, 0.5 * (a + b), 0.0);
937                    out.push((o, index));
938                }
939                previous = value;
940            }
941            if previous == 0.0 {
942                let last = *samples.last().expect("nonempty");
943                out.push((self.source_reduced(source, last, 0.0).1, index));
944            }
945        }
946    }
947
948    fn grids_len_for_time(&self) -> usize {
949        let turn = self
950            .motion
951            .steps
952            .iter()
953            .map(|step| step.turn.abs())
954            .fold(0.0, f64::max)
955            * (self.motion.to - self.motion.from).abs();
956        ((turn * 256.0) as usize).clamp(1024, 8192)
957    }
958
959    /// The clip-frame point a reduced coordinate is tested at.
960    fn lift(&self, level: f64, o: f64) -> [f64; 3] {
961        let axial = 0.5 * (self.clip.axial[0] + self.clip.axial[1]);
962        match self.class {
963            Class::Screw(c) => {
964                let alpha = o + axial / c;
965                [level * alpha.cos(), level * alpha.sin(), axial]
966            }
967            Class::Turn => {
968                let theta = self.clip.angle.map(|a| 0.5 * (a[0] + a[1])).unwrap_or(0.0);
969                [level * theta.cos(), level * theta.sin(), o]
970            }
971            Class::Planar => [level * o.cos(), level * o.sin(), axial],
972        }
973    }
974
975    /// Is the reduced point inside the sweep: does the point's preimage under
976    /// the motion meet the tool for some time in the range?
977    ///
978    /// Walked in time by the tool's signed distance: it bounds how far the
979    /// preimage is from the tool, and the preimage moves no faster than
980    /// `speed_bound`, so no time within `distance / speed` of the current one can
981    /// be inside. The walk is exact for the tool's own distance (a lower bound for
982    /// a prism, which is conservative), and the floor on the step only stops a
983    /// grazing walk from creeping.
984    fn removed(&self, level: f64, o: f64) -> bool {
985        let x = self.frame.world(self.lift(level, o));
986        let (t0, t1) = (self.motion.from, self.motion.to);
987        let speed = self.speed_bound(x);
988        // The floor only keeps a grazing walk from creeping; a coarse floor
989        // jumps over a shallow pass of the tool (1e-5 of the plus wheel's range
990        // is 0.02 mm of travel, and read a 4e-3 mm sliver of its tooth space as
991        // material). A walk still grazing after `cap` steps is on the boundary.
992        let floor = (t1 - t0) * 1e-8;
993        let cap = 200_000usize;
994        let touching = 1e-10 * self.scale;
995        let clock = web_time::Instant::now();
996        let mut t = t0;
997        let mut steps = 0usize;
998        let inside = loop {
999            steps += 1;
1000            let distance = self.tool_signed_distance(self.motion_invert(t, x));
1001            if distance <= touching || steps > cap {
1002                break true;
1003            }
1004            if t >= t1 {
1005                break false;
1006            }
1007            t = (t + (distance / speed).max(floor)).min(t1);
1008        };
1009        let mut c = self.counters.get();
1010        c.1 += 1;
1011        c.2 += steps;
1012        c.4 += clock.elapsed().as_secs_f64();
1013        self.counters.set(c);
1014        inside
1015    }
1016
1017    /// An upper bound on how fast the preimage `M(t)⁻¹ x` moves per unit `t`.
1018    fn speed_bound(&self, x: Vec3) -> f64 {
1019        let centre = self.frame.origin;
1020        let span = self.motion.from.abs().max(self.motion.to.abs());
1021        let mut reach = x.sub(centre).length();
1022        for step in &self.motion.steps {
1023            reach += 2.0 * step.axis_origin.sub(centre).length() + step.advance.abs() * span;
1024        }
1025        let speed: f64 = self
1026            .motion
1027            .steps
1028            .iter()
1029            .map(|step| step.turn.abs() * (reach + step.axis_origin.sub(centre).length()) + step.advance.abs())
1030            .sum();
1031        speed.max(1e-300)
1032    }
1033
1034    /// The region's intervals at a level, sorted by `lo` (angular: `lo` in
1035    /// [0, 2π), `hi` may exceed 2π).
1036    fn intervals_at(&self, level: f64) -> Result<Vec<Interval>, KernelRefusal> {
1037        if let Some(hit) = self.cache.borrow().get(&level.to_bits()) {
1038            return Ok(hit.clone());
1039        }
1040        let clock = web_time::Instant::now();
1041        let before = self.counters.get();
1042        let intervals = self.intervals_uncached(level)?;
1043        if clock.elapsed().as_secs_f64() > 0.5 && std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
1044            let after = self.counters.get();
1045            eprintln!(
1046                "  slow level {level:.12}: {:.2}s, candidates {:.2}s, oracle calls {} steps {} ({:.2}s), {} intervals",
1047                clock.elapsed().as_secs_f64(),
1048                after.3 - before.3,
1049                after.1 - before.1,
1050                after.2 - before.2,
1051                after.4 - before.4,
1052                intervals.len()
1053            );
1054        }
1055        self.cache.borrow_mut().insert(level.to_bits(), intervals.clone());
1056        Ok(intervals)
1057    }
1058
1059    fn intervals_uncached(&self, level: f64) -> Result<Vec<Interval>, KernelRefusal> {
1060        let clock = web_time::Instant::now();
1061        let mut candidates = Vec::new();
1062        for index in 0..self.sources.len() {
1063            self.source_candidates(index, level, &mut candidates);
1064        }
1065        let mut c = self.counters.get();
1066        c.0 += 1;
1067        c.3 += clock.elapsed().as_secs_f64();
1068        self.counters.set(c);
1069        if self.angular {
1070            for candidate in &mut candidates {
1071                candidate.0 = candidate.0.rem_euclid(TAU);
1072            }
1073        }
1074        candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
1075        candidates.dedup_by(|b, a| (b.0 - a.0).abs() < 1e-12);
1076        if candidates.is_empty() {
1077            let probes = 64;
1078            let (base, span) = if self.angular { (0.0, TAU) } else { (-self.scale * 4.0, self.scale * 8.0) };
1079            if (0..probes).all(|k| self.removed(level, base + span * (k as f64 + 0.5) / probes as f64)) {
1080                return Err(refuse(
1081                    "whole_level",
1082                    format!("{WHOLE_LEVEL} {level}, which this construction does not build"),
1083                ));
1084            }
1085            return Ok(Vec::new());
1086        }
1087        let n = candidates.len();
1088        let gaps = if self.angular { n } else { n - 1 };
1089        let mut removed = Vec::with_capacity(gaps);
1090        for k in 0..gaps {
1091            let a = candidates[k].0;
1092            let b = if k + 1 < n { candidates[k + 1].0 } else { candidates[0].0 + TAU };
1093            // A gap far below any feature is the two ends of one boundary
1094            // point; its middle is on the boundary, where the oracle can only
1095            // graze. It joins whatever is on either side.
1096            if (b - a) * level.max(1.0) < 1e-9 * self.scale {
1097                removed.push(true);
1098                continue;
1099            }
1100            removed.push(self.removed(level, 0.5 * (a + b)));
1101        }
1102        let mut intervals = Vec::new();
1103        // Below a crest some material is left, however narrow: the widest gap,
1104        // which the oracle can no longer see inside.
1105        if self.crest_gap && self.angular && removed.iter().all(|r| *r) {
1106            let width = |k: usize| if k + 1 < n { candidates[k + 1].0 - candidates[k].0 } else { candidates[0].0 + TAU - candidates[k].0 };
1107            if let Some(widest) = (0..gaps).max_by(|&a, &b| width(a).total_cmp(&width(b))) {
1108                removed[widest] = false;
1109            }
1110        }
1111        if self.angular && removed.iter().all(|r| *r) {
1112            return Err(refuse(
1113                "whole_level",
1114                format!("{WHOLE_LEVEL} {level}, which this construction does not build"),
1115            ));
1116        }
1117        // Start the walk after a material gap so a run never straddles the start.
1118        let start = if self.angular {
1119            removed.iter().position(|r| !r).map(|k| (k + 1) % n).unwrap_or(0)
1120        } else {
1121            0
1122        };
1123        let mut k = 0;
1124        while k < gaps {
1125            let g = (start + k) % n.max(1);
1126            if !removed[g] {
1127                k += 1;
1128                continue;
1129            }
1130            let first = g;
1131            let mut last = g;
1132            while k + 1 < gaps && removed[(start + k + 1) % n] {
1133                k += 1;
1134                last = (start + k) % n;
1135            }
1136            let lo = candidates[first];
1137            let hi_index = (last + 1) % n;
1138            let hi = candidates[hi_index];
1139            let mut hi_value = hi.0;
1140            if self.angular && hi_value <= lo.0 {
1141                hi_value += TAU;
1142            }
1143            intervals.push(Interval {
1144                lo: lo.0,
1145                hi: hi_value,
1146                lo_source: lo.1,
1147                hi_source: hi.1,
1148            });
1149            k += 1;
1150        }
1151        intervals.sort_by(|a, b| a.lo.total_cmp(&b.lo));
1152        Ok(intervals)
1153    }
1154
1155    /// Critical points of the level over a source (tips and plateaus).
1156    /// The face's characteristic function: `det(∇o, ∇ℓ) / |∇ℓ|`, zero where
1157    /// the face's image turns back (its envelope), and the level there.
1158    fn characteristic(&self, source: Source, u: f64, v: f64) -> (f64, f64) {
1159        let (ur, vr, _) = self.domain(source);
1160        let hu = 1e-6 * (ur[1] - ur[0]).max(1e-3);
1161        let hv = 1e-6 * (vr[1] - vr[0]).max(1e-3);
1162        let (l, _) = self.source_reduced(source, u, v);
1163        let (lu1, ou1) = self.source_reduced(source, u + hu, v);
1164        let (lu0, ou0) = self.source_reduced(source, u - hu, v);
1165        let (lv1, ov1) = self.source_reduced(source, u, v + hv);
1166        let (lv0, ov0) = self.source_reduced(source, u, v - hv);
1167        let (lu, lv) = ((lu1 - lu0) / (2.0 * hu), (lv1 - lv0) / (2.0 * hv));
1168        let ou = self.o_difference(ou1, ou0) / (2.0 * hu);
1169        let ov = self.o_difference(ov1, ov0) / (2.0 * hv);
1170        ((ou * lv - ov * lu) / lu.hypot(lv).max(1e-300), l)
1171    }
1172
1173    /// FOLDS and KINKS of a face, recorded as its critical points so events snap
1174    /// to them and band ends read them exactly:
1175    /// - a FOLD is where the level is extremal along the face's own envelope
1176    ///   (`D = 0`): two extrema of `o` on one level contour annihilate there
1177    ///   (the plus wheel's lobes merging at ρ = 20, the tip of its arm's flat
1178    ///   end). Newton on {D = 0, ℓ_u·D_v − ℓ_v·D_u = 0}, seeded where the level
1179    ///   is locally extremal among the grid's crossings of D = 0.
1180    /// - a KINK is where the envelope runs into the face's own boundary and the
1181    ///   boundary's edge takes over: roots of D along each non-periodic side.
1182    fn folds_and_kinks(&self, source: Source, grid: &Grid, out: &mut Vec<(f64, f64)>, params: &mut Vec<(f64, f64)>) {
1183        let (ur, vr, v_periodic) = self.domain(source);
1184        let u_periodic = self.u_periodic(source);
1185        let (nu, nv) = (grid.nu, grid.nv);
1186        let mut d = vec![0.0; nu * nv];
1187        for i in 0..nu {
1188            for j in 0..nv {
1189                let (u, v) = Self::grid_param(grid, i, j);
1190                d[i * nv + j] = self.characteristic(source, u, v).0;
1191            }
1192        }
1193        // Crossings of D = 0 along grid edges: (i, j, u, v, level).
1194        let mut crossings: Vec<(usize, usize, f64, f64, f64)> = Vec::new();
1195        let jmax = if v_periodic { nv } else { nv - 1 };
1196        for i in 0..nu {
1197            for j in 0..jmax {
1198                let (a, b) = (d[i * nv + j], d[i * nv + (j + 1) % nv]);
1199                if a * b < 0.0 {
1200                    let w = a / (a - b);
1201                    let (u, v0) = Self::grid_param(grid, i, j);
1202                    let (_, v1) = Self::grid_param(grid, i, j + 1);
1203                    let v1 = if v_periodic && j + 1 == nv { vr[1] } else { v1 };
1204                    let v = v0 + (v1 - v0) * w;
1205                    crossings.push((i, j, u, v, self.source_reduced(source, u, v).0));
1206                }
1207            }
1208        }
1209        for i in 0..nu - 1 {
1210            for j in 0..nv {
1211                let (a, b) = (d[i * nv + j], d[(i + 1) * nv + j]);
1212                if a * b < 0.0 {
1213                    let w = a / (a - b);
1214                    let (u0, v) = Self::grid_param(grid, i, j);
1215                    let (u1, _) = Self::grid_param(grid, i + 1, j);
1216                    let u = u0 + (u1 - u0) * w;
1217                    crossings.push((i, j, u, v, self.source_reduced(source, u, v).0));
1218                }
1219            }
1220        }
1221        let mut buckets: std::collections::HashMap<(usize, usize), Vec<usize>> = std::collections::HashMap::new();
1222        for (k, c) in crossings.iter().enumerate() {
1223            buckets.entry((c.0, c.1)).or_default().push(k);
1224        }
1225        let ku = 1e-4 * (ur[1] - ur[0]);
1226        let kv = 1e-4 * (vr[1] - vr[0]);
1227        let fold = |u: f64, v: f64| -> [f64; 2] {
1228            let (dd, _) = self.characteristic(source, u, v);
1229            let du = (self.characteristic(source, u + ku, v).0 - self.characteristic(source, u - ku, v).0) / (2.0 * ku);
1230            let dv = (self.characteristic(source, u, v + kv).0 - self.characteristic(source, u, v - kv).0) / (2.0 * kv);
1231            let lu = (self.source_reduced(source, u + ku, v).0 - self.source_reduced(source, u - ku, v).0) / (2.0 * ku);
1232            let lv = (self.source_reduced(source, u, v + kv).0 - self.source_reduced(source, u, v - kv).0) / (2.0 * kv);
1233            let norm = (lu.hypot(lv) * du.hypot(dv)).max(1e-300);
1234            [dd, (lu * dv - lv * du) / norm]
1235        };
1236        for (k, &(i, j, u0, v0, level)) in crossings.iter().enumerate() {
1237            let mut is_min = true;
1238            let mut is_max = true;
1239            for di in [-1i64, 0, 1] {
1240                for dj in [-1i64, 0, 1] {
1241                    let i2 = i as i64 + di;
1242                    let j2 = if v_periodic { (j as i64 + dj).rem_euclid(nv as i64) } else { j as i64 + dj };
1243                    if i2 < 0 || j2 < 0 {
1244                        continue;
1245                    }
1246                    if let Some(list) = buckets.get(&(i2 as usize, j2 as usize)) {
1247                        for &m in list {
1248                            if m == k {
1249                                continue;
1250                            }
1251                            if crossings[m].4 < level {
1252                                is_min = false;
1253                            }
1254                            if crossings[m].4 > level {
1255                                is_max = false;
1256                            }
1257                        }
1258                    }
1259                }
1260            }
1261            if !(is_min || is_max) {
1262                continue;
1263            }
1264            let (mut u, mut v) = (u0, v0);
1265            let mut converged = false;
1266            for _ in 0..40 {
1267                let f = fold(u, v);
1268                let (su, sv) = (ku * 10.0, kv * 10.0);
1269                let fu1 = fold(u + su, v);
1270                let fu0 = fold(u - su, v);
1271                let fv1 = fold(u, v + sv);
1272                let fv0 = fold(u, v - sv);
1273                let j00 = (fu1[0] - fu0[0]) / (2.0 * su);
1274                let j01 = (fv1[0] - fv0[0]) / (2.0 * sv);
1275                let j10 = (fu1[1] - fu0[1]) / (2.0 * su);
1276                let j11 = (fv1[1] - fv0[1]) / (2.0 * sv);
1277                let det = j00 * j11 - j01 * j10;
1278                if !det.is_finite() || det.abs() < 1e-300 {
1279                    break;
1280                }
1281                let du = -(f[0] * j11 - f[1] * j01) / det;
1282                let dv = -(j00 * f[1] - j10 * f[0]) / det;
1283                // Stay near the seed: a fold is local to its crossing.
1284                let cap = 4.0 * ((ur[1] - ur[0]) / (nu as f64)).max((vr[1] - vr[0]) / (nv as f64));
1285                let scale = (du.hypot(dv) / cap).max(1.0);
1286                u += du / scale;
1287                v += dv / scale;
1288                if du.hypot(dv) < 1e-12 * (ur[1] - ur[0]).max(vr[1] - vr[0]) {
1289                    converged = true;
1290                    break;
1291                }
1292            }
1293            let f = fold(u, v);
1294            if !(converged || (f[0].abs() < 1e-9 && f[1].abs() < 1e-5)) {
1295                continue;
1296            }
1297            if u_periodic {
1298                u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
1299            }
1300            if v_periodic {
1301                v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
1302            }
1303            if u > ur[0] && u < ur[1] && (v_periodic || (v > vr[0] && v < vr[1])) {
1304                out.push(self.source_reduced(source, u, v));
1305                params.push((u, v));
1306            }
1307        }
1308        // Kinks: roots of D along each non-periodic side of the face.
1309        let mut sides: Vec<(bool, f64)> = Vec::new(); // (along v at fixed u, the fixed value)
1310        if !u_periodic {
1311            sides.push((true, ur[0]));
1312            sides.push((true, ur[1]));
1313        }
1314        if !v_periodic {
1315            sides.push((false, vr[0]));
1316            sides.push((false, vr[1]));
1317        }
1318        for (along_v, fixed) in sides {
1319            let (range, n) = if along_v { (vr, nv * 4) } else { (ur, nu * 4) };
1320            let at = |t: f64| if along_v { (fixed, t) } else { (t, fixed) };
1321            let value = |t: f64| {
1322                let (u, v) = at(t);
1323                self.characteristic(source, u, v).0
1324            };
1325            let mut previous = value(range[0]);
1326            for k in 1..=n {
1327                let t = range[0] + (range[1] - range[0]) * k as f64 / n as f64;
1328                let current = value(t);
1329                if previous * current < 0.0 {
1330                    let (mut a, mut b) = (t - (range[1] - range[0]) / n as f64, t);
1331                    let fa = previous;
1332                    for _ in 0..100 {
1333                        let m = 0.5 * (a + b);
1334                        if (value(m) < 0.0) == (fa < 0.0) {
1335                            a = m;
1336                        } else {
1337                            b = m;
1338                        }
1339                    }
1340                    let (u, v) = at(0.5 * (a + b));
1341                    out.push(self.source_reduced(source, u, v));
1342                    params.push((u, v));
1343                }
1344                previous = current;
1345            }
1346        }
1347    }
1348
1349    fn source_critical(&self, index: usize) -> (Vec<(f64, f64)>, Vec<(f64, f64)>) {
1350        let source = self.sources[index];
1351        let mut out = Vec::new();
1352        let mut params = Vec::new();
1353        if Self::is_face(source) {
1354            let grid = self.grids[index].as_ref().expect("face grid");
1355            let (ur, vr, periodic) = self.domain(source);
1356            let at = |i: usize, j: usize| grid.values[i * grid.nv + j].0;
1357            let u_periodic = self.u_periodic(source);
1358            // A periodic first parameter has its last row equal to its first.
1359            let rows = if u_periodic { grid.nu - 1 } else { grid.nu };
1360            for i in 0..rows {
1361                if !u_periodic && (i == 0 || i + 1 == grid.nu) {
1362                    continue;
1363                }
1364                for j in 0..grid.nv {
1365                    if !periodic && (j == 0 || j + 1 == grid.nv) {
1366                        continue;
1367                    }
1368                    let here = at(i, j);
1369                    let mut is_min = true;
1370                    let mut is_max = true;
1371                    for di in [-1i64, 0, 1] {
1372                        for dj in [-1i64, 0, 1] {
1373                            if di == 0 && dj == 0 {
1374                                continue;
1375                            }
1376                            let i2 = ((i as i64 + di).rem_euclid(rows as i64)) as usize;
1377                            let j2 = ((j as i64 + dj).rem_euclid(grid.nv as i64)) as usize;
1378                            let there = at(i2, j2);
1379                            if there < here {
1380                                is_min = false;
1381                            }
1382                            if there > here {
1383                                is_max = false;
1384                            }
1385                        }
1386                    }
1387                    if !(is_min || is_max) {
1388                        continue;
1389                    }
1390                    // Newton on ∇ℓ = 0.
1391                    let (mut u, mut v) = Self::grid_param(grid, i, j);
1392                    let hu = 1e-5 * (ur[1] - ur[0]);
1393                    let hv = 1e-5 * (vr[1] - vr[0]);
1394                    let level = |u: f64, v: f64| self.source_reduced(source, u, v).0;
1395                    for _ in 0..50 {
1396                        let f = level(u, v);
1397                        let fu = (level(u + hu, v) - level(u - hu, v)) / (2.0 * hu);
1398                        let fv = (level(u, v + hv) - level(u, v - hv)) / (2.0 * hv);
1399                        let fuu = (level(u + hu, v) - 2.0 * f + level(u - hu, v)) / (hu * hu);
1400                        let fvv = (level(u, v + hv) - 2.0 * f + level(u, v - hv)) / (hv * hv);
1401                        let fuv = (level(u + hu, v + hv) - level(u + hu, v - hv) - level(u - hu, v + hv)
1402                            + level(u - hu, v - hv))
1403                            / (4.0 * hu * hv);
1404                        let det = fuu * fvv - fuv * fuv;
1405                        if det.abs() < 1e-300 {
1406                            break;
1407                        }
1408                        let du = -(fu * fvv - fv * fuv) / det;
1409                        let dv = -(fuu * fv - fuv * fu) / det;
1410                        u += du;
1411                        v += dv;
1412                        if du.abs() < 1e-14 && dv.abs() < 1e-14 {
1413                            break;
1414                        }
1415                    }
1416                    if u_periodic {
1417                        u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
1418                    }
1419                    if periodic {
1420                        v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
1421                    }
1422                    if u >= ur[0] && u <= ur[1] && (periodic || (v >= vr[0] && v <= vr[1])) {
1423                        out.push(self.source_reduced(source, u, v));
1424                        params.push((u, v));
1425                    }
1426                }
1427            }
1428            self.folds_and_kinks(source, grid, &mut out, &mut params);
1429        } else {
1430            let (range, _, _) = self.domain(source);
1431            let n = 2048;
1432            let param = |k: usize| range[0] + (range[1] - range[0]) * k as f64 / n as f64;
1433            let values: Vec<f64> = (0..=n).map(|k| self.source_reduced(source, param(k), 0.0).0).collect();
1434            for k in 1..n {
1435                let (a, b, c) = (values[k - 1], values[k], values[k + 1]);
1436                if (b <= a && b <= c) || (b >= a && b >= c) {
1437                    let sign = if b <= a && b <= c { 1.0 } else { -1.0 };
1438                    let (mut lo, mut hi) = (param(k - 1), param(k + 1));
1439                    let ratio = 0.618_033_988_749_894_9;
1440                    for _ in 0..100 {
1441                        let c1 = hi - ratio * (hi - lo);
1442                        let d1 = lo + ratio * (hi - lo);
1443                        if sign * self.source_reduced(source, c1, 0.0).0 < sign * self.source_reduced(source, d1, 0.0).0 {
1444                            hi = d1;
1445                        } else {
1446                            lo = c1;
1447                        }
1448                    }
1449                    out.push(self.source_reduced(source, 0.5 * (lo + hi), 0.0));
1450                    params.push((0.5 * (lo + hi), 0.0));
1451                }
1452            }
1453        }
1454        (out, params)
1455    }
1456}
1457
1458/// Are two sources the same boundary piece of the sweep: the same source, or
1459/// a piece and the one that continues it across a set-periodic motion's wrap?
1460/// A face handing over to the edge that bounds it is NOT the same: the V
1461/// wheel's flank meets its tip circle's image at a kink, and fitting one curve
1462/// through it read the groove 1.5e-6 off (split: 1.1e-8).
1463fn same_or_bounding(engine: &Engine, a: usize, b: usize) -> bool {
1464    if a == b {
1465        return true;
1466    }
1467    let pieces = match (&engine.bar, engine.tool) {
1468        (Some(bar), _) => bar.piece_count(),
1469        (None, SweptTool::Revolved { meridian, .. }) => meridian.len(),
1470        (None, SweptTool::Prism { outline, .. }) => outline.len(),
1471        (None, SweptTool::Bar { section, .. }) => section.len(),
1472    };
1473    // (piece of the face, piece whose start the edge is)
1474    let face = |s: Source| match s {
1475        Source::RevolvedFace { piece } | Source::PrismFace { piece } | Source::ScrewPrismSide { piece } | Source::BarSide { piece } => Some(piece),
1476        _ => None,
1477    };
1478    let edge = |s: Source| match s {
1479        Source::RevolvedCorner { piece } | Source::PrismVertex { piece } | Source::ScrewPrismEdge { piece } | Source::BarEdge { piece } => Some(piece),
1480        _ => None,
1481    };
1482    let (sa, sb) = (engine.sources[a], engine.sources[b]);
1483    // Across the wrap, piece `k` continues as `wrap[k]`.
1484    let same_piece = |x: usize, y: usize| {
1485        x == y || engine.wrap.as_ref().is_some_and(|map| map[x] == y || map[y] == x)
1486    };
1487    let bounds = |f: usize, e: usize| {
1488        same_piece(e, f) || same_piece(e, (f + 1) % pieces)
1489    };
1490    let _ = bounds;
1491    match (face(sa), edge(sa), face(sb), edge(sb)) {
1492        (Some(f), _, Some(g), _) => same_piece(f, g),
1493        (_, Some(e), _, Some(g)) => same_piece(e, g),
1494        _ => false,
1495    }
1496}
1497
1498/// Do two interval lists describe the same structure (same count, each end on
1499/// the same source or one that hands over to it smoothly, matched in order)?
1500fn compatible(engine: &Engine, a: &[Interval], b: &[Interval]) -> bool {
1501    let angular = engine.angular;
1502    if a.len() != b.len() {
1503        return false;
1504    }
1505    // Match each interval of `a` to the one of `b` nearest its middle.
1506    let mut used = vec![false; b.len()];
1507    for x in a {
1508        let mid = 0.5 * (x.lo + x.hi);
1509        let mut best = None;
1510        let mut best_distance = f64::INFINITY;
1511        for (k, y) in b.iter().enumerate() {
1512            let other = 0.5 * (y.lo + y.hi);
1513            let d = if angular { wrap_pi(mid - other).abs() } else { (mid - other).abs() };
1514            if d < best_distance {
1515                best_distance = d;
1516                best = Some(k);
1517            }
1518        }
1519        let Some(k) = best else { return false };
1520        let y = &b[k];
1521        let overlap = if angular {
1522            let shift = (wrap_pi(y.lo - x.lo)) - (y.lo - x.lo);
1523            let (ylo, yhi) = (y.lo + shift, y.hi + shift);
1524            x.hi.min(yhi) - x.lo.max(ylo)
1525        } else {
1526            x.hi.min(y.hi) - x.lo.max(y.lo)
1527        };
1528        if used[k]
1529            || overlap < 0.0
1530            || !same_or_bounding(engine, x.lo_source, y.lo_source)
1531            || !same_or_bounding(engine, x.hi_source, y.hi_source)
1532        {
1533            return false;
1534        }
1535        used[k] = true;
1536    }
1537    true
1538}
1539
1540/// A boundary piece in reduced coordinates, as a polyline of exact samples
1541/// (the first and last are the piece's ends) with their `σ`.
1542struct Piece {
1543    points: Vec<(f64, f64)>,
1544    sigma: Vec<f64>,
1545    /// A straight level segment (built exactly, not fitted).
1546    level_segment: bool,
1547}
1548
1549/// Build the sweep of `tool` along `motion` inside `clip`, as one body per
1550/// connected region of the reduced section.
1551pub fn sweep_solid_within(
1552    tool: &SweptTool,
1553    motion: &SolidMotion,
1554    clip: &SweepClip,
1555) -> Result<Vec<BrepSolid>, KernelRefusal> {
1556    // A convex polygon's prism carried round a closed planar motion (turns
1557    // about axes along its own, ending where it starts: a planet on its
1558    // carrier): the plane region its section covers, found exactly and
1559    // extruded. It is the whole sweep, so it holds whatever lies in the clip.
1560    if let SweptTool::Prism { origin, normal, x_axis, outline, from, to } = tool {
1561        if motion.steps.len() >= 2 {
1562            let steps: Vec<(Vec3, Vec3, f64, f64)> = motion.steps.iter().map(|step| (step.axis_origin, step.axis_direction, step.turn, step.advance)).collect();
1563            if let Some(body) = crate::solid_sweep_caps::closed_planar_prism(*origin, *normal, *x_axis, outline, *from, *to, &steps, motion.from, motion.to)? {
1564                return Ok(vec![body]);
1565            }
1566        }
1567    }
1568    let narrowed: SweepClip;
1569    // --- Frame and classification.
1570    let ez = clip
1571        .axis_direction
1572        .normalized()
1573        .or_refuse(KernelStage::Collect, "clip_axis")?;
1574    let ex = clip
1575        .reference
1576        .sub(ez.scale(clip.reference.dot(ez)))
1577        .normalized()
1578        .or_refuse(KernelStage::Collect, "clip_reference")?;
1579    let frame = Frame { origin: clip.axis_origin, ex, ey: ez.cross(ex), ez };
1580    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
1581        return Err(KernelRefusal::input(
1582            KernelStage::Collect,
1583            "motion_range",
1584            format!("{SOLID_SWEEP_REFUSAL}: the motion's range must run forwards"),
1585        ));
1586    }
1587    if motion.steps.is_empty() {
1588        return Err(KernelRefusal::input(KernelStage::Collect, "motion_empty", format!("{SOLID_SWEEP_REFUSAL}: no motion")));
1589    }
1590    let mut axes = Vec::with_capacity(motion.steps.len());
1591    for step in &motion.steps {
1592        axes.push(step.axis_direction.normalized().or_refuse(KernelStage::Collect, "step_axis")?);
1593    }
1594    if !(clip.radius[0] >= 0.0 && clip.radius[1] > clip.radius[0] && clip.axial[1] > clip.axial[0]) {
1595        return Err(KernelRefusal::input(
1596            KernelStage::Collect,
1597            "clip_range",
1598            format!("{SOLID_SWEEP_REFUSAL}: the clip's ranges must be increasing"),
1599        ));
1600    }
1601    let on_axis = |origin: Vec3, axis: Vec3| -> bool {
1602        let parallel = axis.cross(ez).length() < 1e-12;
1603        let offset = origin.sub(clip.axis_origin);
1604        parallel && offset.sub(ez.scale(offset.dot(ez))).length() < 1e-9 * (1.0 + clip.radius[1])
1605    };
1606    // One screw about the clip's axis, as its axial advance per radian about +ez.
1607    let screw_about_clip = || -> Option<f64> {
1608        let step = motion.steps.first()?;
1609        (motion.steps.len() == 1 && step.turn != 0.0 && step.advance != 0.0 && on_axis(step.axis_origin, axes[0])).then(|| {
1610            let sense = axes[0].dot(ez).signum();
1611            (step.advance * sense) / (step.turn * sense)
1612        })
1613    };
1614    let mut bar: Option<crate::solid_sweep_bar::Bar> = None;
1615    let class = 'class: { match tool {
1616        SweptTool::Bar { origin, normal, section, from, to, draft } => {
1617            let Some(c) = screw_about_clip() else {
1618                return Err(refuse("motion_class", "a bar is swept here only by one screw about the clip's axis".into()));
1619            };
1620            bar = Some(crate::solid_sweep_bar::Bar::new(*origin, *normal, section, *from, *to, *draft)?);
1621            Class::Screw(c)
1622        }
1623        SweptTool::Revolved { meridian, .. } => {
1624            validate_outline(meridian, "meridian")?;
1625            if motion.steps.len() != 1 || !on_axis(motion.steps[0].axis_origin, axes[0]) {
1626                return Err(refuse(
1627                    "motion_class",
1628                    "a solid of revolution is swept here only by one screw or turn about the clip's axis".into(),
1629                ));
1630            }
1631            let step = motion.steps[0];
1632            let sense = axes[0].dot(ez).signum();
1633            if step.turn == 0.0 {
1634                return Err(refuse("motion_class", "a slide of a solid of revolution is not built here".into()));
1635            }
1636            if step.advance == 0.0 {
1637                Class::Turn
1638            } else {
1639                // axial advance per radian about +ez
1640                Class::Screw((step.advance * sense) / (step.turn * sense))
1641            }
1642        }
1643        SweptTool::Prism { normal, outline, from, to, origin, x_axis } => {
1644            validate_outline(outline, "prism")?;
1645            let n = normal.normalized().or_refuse(KernelStage::Collect, "prism_normal")?;
1646            let screw = motion.steps.len() == 1
1647                && motion.steps[0].turn != 0.0
1648                && motion.steps[0].advance != 0.0
1649                && on_axis(motion.steps[0].axis_origin, axes[0])
1650                && n.cross(ez).length() <= 1e-12;
1651            if screw {
1652                // A screw carries the prism's ends along, so the clip may run past them.
1653                let step = motion.steps[0];
1654                let sense = axes[0].dot(ez).signum();
1655                break 'class Class::Screw((step.advance * sense) / (step.turn * sense));
1656            }
1657            if n.cross(ez).length() > 1e-12 {
1658                // Across the screw's axis the prism is a bar with no draft.
1659                if let Some(c) = screw_about_clip() {
1660                    let xa = x_axis.sub(n.scale(x_axis.dot(n))).normalized().or_refuse(KernelStage::Collect, "prism_x_axis")?;
1661                    let ya = n.cross(xa);
1662                    let at = |q: [f64; 2]| origin.add(xa.scale(q[0])).add(ya.scale(q[1]));
1663                    let mut section = Vec::with_capacity(outline.len());
1664                    for piece in outline {
1665                        section.push(match *piece {
1666                            OutlinePiece::Line { from, to } => make_line(at(from), at(to)),
1667                            // an arc run clockwise is one run the other way about the mirrored axis
1668                            OutlinePiece::Arc { centre, radius, start, end } if end >= start => make_arc(at(centre), xa, ya, radius, start, end),
1669                            OutlinePiece::Arc { centre, radius, start, end } => make_arc(at(centre), xa, ya.scale(-1.0), radius, -start, -end),
1670                        }
1671                        .or_refuse(KernelStage::Collect, "prism_outline")?);
1672                    }
1673                    bar = Some(crate::solid_sweep_bar::Bar::new(*origin, n, &section, *from, *to, 0.0)?);
1674                    break 'class Class::Screw(c);
1675                }
1676                return Err(refuse("motion_class", "a prism is swept here only along its own direction's clip axis".into()));
1677            }
1678            for (step, axis) in motion.steps.iter().zip(&axes) {
1679                let turn_ok = step.turn == 0.0 || axis.cross(n).length() < 1e-12;
1680                let advance_ok = step.advance == 0.0 || (step.turn == 0.0 && axis.dot(n).abs() < 1e-12);
1681                if !(turn_ok && advance_ok) {
1682                    return Err(refuse(
1683                        "motion_class",
1684                        "a prism is swept here only by turns about axes along it and slides across it".into(),
1685                    ));
1686                }
1687            }
1688            // The clip's axial range must lie within the prism's extent.
1689            let base = clip.axis_origin.sub(*origin).dot(n);
1690            let sense = ez.dot(n);
1691            let h0 = base + sense * clip.axial[0];
1692            let h1 = base + sense * clip.axial[1];
1693            if h0.min(h1) < *from || h0.max(h1) > *to {
1694                return Err(refuse(
1695                    "clip_past_prism",
1696                    "the clip reaches past the prism's ends, where the sweep is not a prism".into(),
1697                ));
1698            }
1699            Class::Planar
1700        }
1701    } };
1702    // A leaning end face folds into a wall of its own, which is not built.
1703    if let (Some(bar), Class::Screw(c)) = (&bar, class) {
1704        if bar.end_folds(clip.axis_origin, ez, c, clip.radius) {
1705            return Err(refuse(
1706                "bar_end_fold",
1707                "an end face of the bar leans to the screw's axis and folds inside the clip region, a wall this construction does not build".into(),
1708            ));
1709        }
1710    }
1711    let prism_height = match tool {
1712        SweptTool::Prism { from, to, .. } => 0.5 * (from + to),
1713        _ => 0.0,
1714    };
1715
1716    // Does the motion end where it began, as a set? For a prism, every outline
1717    // vertex at the last position must sit on some vertex at the first (the plus
1718    // turns 540°, which its half-turn symmetry makes a whole period). The
1719    // permutation says which piece continues which across the wrap.
1720    let wrap: Option<Vec<usize>> = match tool {
1721        SweptTool::Bar { .. } => None,
1722        SweptTool::Prism { .. } if matches!(class, Class::Screw(_)) => None,
1723        SweptTool::Prism { origin, normal, x_axis, outline, .. } => {
1724            let probe = Engine {
1725                tool,
1726                motion,
1727                axes: axes.clone(),
1728                frame,
1729                class,
1730                clip,
1731                bar: None,
1732                crest_gap: false,
1733                sources: Vec::new(),
1734                grids: Vec::new(),
1735                critical: Vec::new(),
1736                critical_params: Vec::new(),
1737                angular: true,
1738                prism_height,
1739                scale: 1.0,
1740                cache: std::cell::RefCell::new(std::collections::HashMap::new()),
1741                wrap: None,
1742                counters: std::cell::Cell::new((0, 0, 0, 0.0, 0.0)),
1743            };
1744            let n = normal.normalized_or(*normal);
1745            let xa = x_axis.normalized_or(*x_axis);
1746            let ya = n.cross(xa);
1747            let vertex = |k: usize, t: f64| {
1748                let q = outline[k].point(0.0);
1749                probe.motion_apply(t, origin.add(xa.scale(q[0])).add(ya.scale(q[1])).add(n.scale(prism_height)))
1750            };
1751            let size = scale_of(outline);
1752            let mut map = Vec::with_capacity(outline.len());
1753            for k in 0..outline.len() {
1754                let end = vertex(k, motion.to);
1755                match (0..outline.len()).find(|&j| vertex(j, motion.from).sub(end).length() < 1e-9 * size) {
1756                    Some(j) => map.push(j),
1757                    None => break,
1758                }
1759            }
1760            let consistent = map.len() == outline.len()
1761                && (0..outline.len()).all(|k| map[(k + 1) % outline.len()] == (map[k] + 1) % outline.len());
1762            consistent.then_some(map)
1763        }
1764        SweptTool::Revolved { .. } => None,
1765    };
1766    let periodic_motion = wrap.is_some();
1767    let mut sources = Vec::new();
1768    match tool {
1769        _ if bar.is_some() => {
1770            let bar = bar.as_ref().expect("bar");
1771            for piece in 0..bar.piece_count() {
1772                sources.push(Source::BarSide { piece });
1773                if !bar.periodic {
1774                    sources.push(Source::BarEdge { piece });
1775                }
1776                sources.push(Source::BarRim { piece, end: false });
1777                sources.push(Source::BarRim { piece, end: true });
1778            }
1779        }
1780        SweptTool::Bar { .. } => {}
1781        SweptTool::Revolved { meridian, .. } => {
1782            // A piece lying on the axis revolves into nothing, and a corner on the
1783            // axis into a point: neither bounds the tool.
1784            let on_axis = |p: [f64; 2]| p[0].abs() <= 1e-12 * scale_of(meridian);
1785            for piece in 0..meridian.len() {
1786                let lies_on_axis = matches!(meridian[piece], OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to));
1787                if !lies_on_axis {
1788                    sources.push(Source::RevolvedFace { piece });
1789                }
1790                if !meridian[piece].is_full_circle() && !on_axis(meridian[piece].point(0.0)) {
1791                    sources.push(Source::RevolvedCorner { piece });
1792                }
1793            }
1794        }
1795        SweptTool::Prism { outline, .. } if matches!(class, Class::Screw(_)) => {
1796            for piece in 0..outline.len() {
1797                sources.push(Source::ScrewPrismSide { piece });
1798                if !outline[piece].is_full_circle() {
1799                    sources.push(Source::ScrewPrismEdge { piece });
1800                }
1801                sources.push(Source::ScrewPrismRim { piece, end: false });
1802                sources.push(Source::ScrewPrismRim { piece, end: true });
1803            }
1804        }
1805        SweptTool::Prism { outline, .. } => {
1806            for piece in 0..outline.len() {
1807                sources.push(Source::PrismFace { piece });
1808                if !outline[piece].is_full_circle() {
1809                    sources.push(Source::PrismVertex { piece });
1810                }
1811                if !periodic_motion {
1812                    sources.push(Source::PrismEnd { piece, end: false });
1813                    sources.push(Source::PrismEnd { piece, end: true });
1814                }
1815            }
1816        }
1817    }
1818    let scale = clip.radius[1].max(1.0);
1819    let mut engine = Engine {
1820        tool,
1821        motion,
1822        axes,
1823        frame,
1824        class,
1825        clip,
1826        bar,
1827        crest_gap: false,
1828        sources,
1829        grids: Vec::new(),
1830        critical: Vec::new(),
1831        critical_params: Vec::new(),
1832        angular: class != Class::Turn,
1833        prism_height,
1834        scale,
1835        cache: std::cell::RefCell::new(std::collections::HashMap::new()),
1836        wrap,
1837        counters: std::cell::Cell::new((0, 0, 0, 0.0, 0.0)),
1838    };
1839    engine.grids = engine
1840        .sources
1841        .iter()
1842        .map(|source| if Engine::is_face(*source) { Some(engine.build_grid(*source)) } else { None })
1843        .collect();
1844    let critical: Vec<_> = (0..engine.sources.len()).map(|k| engine.source_critical(k)).collect();
1845    engine.critical_params = critical.iter().map(|c| c.1.clone()).collect();
1846    engine.critical = critical.into_iter().map(|c| c.0).collect();
1847    if let (SweptTool::Revolved { axis_origin, axis_direction, meridian, .. }, true) = (tool, apex_tip_on()) {
1848        let axis = axis_direction.normalized_or(*axis_direction);
1849        let count = meridian.len();
1850        for piece in 0..count {
1851            let corner = meridian[piece].point(0.0);
1852            if corner[0].abs() > 1e-12 * scale_of(meridian) {
1853                continue;
1854            }
1855            let apex = engine.reduce(engine.frame.local(axis_origin.add(axis.scale(corner[1]))));
1856            // the faces on either side of the corner
1857            for neighbour in [piece, (piece + count - 1) % count] {
1858                if let Some(index) = engine.sources.iter().position(|source| matches!(source, Source::RevolvedFace { piece } if *piece == neighbour)) {
1859                    engine.critical[index].push(apex);
1860                }
1861            }
1862        }
1863    }
1864
1865    // --- Ends: a screw or turn must not reach the clip at either end.
1866    if matches!(class, Class::Screw(_) | Class::Turn) {
1867        check_ends_clear(&engine)?;
1868    }
1869
1870    // --- A screw whose grooves meet: above a crest level nothing stays. Build
1871    //     what stays below it, and take that from the clip at the end.
1872    let mut crest = None;
1873    if matches!(class, Class::Screw(_)) && clip.radius[0] == 0.0 && clip.angle.is_none() && whole_level_on() {
1874        crest = crest_level(&engine)?;
1875        if let Some(level) = crest {
1876            narrowed = SweepClip { radius: [0.0, level], ..clip.clone() };
1877            engine.clip = &narrowed;
1878            engine.crest_gap = true;
1879        }
1880    }
1881
1882    // --- Scan the levels for events.
1883    let (l0, l1) = (engine.clip.radius[0], engine.clip.radius[1]);
1884    let scan = 192;
1885    let mut levels: Vec<f64> = (0..=scan).map(|k| l0 + (l1 - l0) * k as f64 / scan as f64).collect();
1886    // Never sample exactly on a critical level: nudge the scan off them.
1887    for level in &mut levels {
1888        for critical in engine.critical.iter().flatten() {
1889            if (critical.0 - *level).abs() < 1e-9 * scale {
1890                *level += 1e-7 * (l1 - l0);
1891            }
1892        }
1893    }
1894    let mut structure = Vec::with_capacity(levels.len());
1895    for &level in &levels {
1896        structure.push(engine.intervals_at(level)?);
1897    }
1898    let debug = std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok();
1899    let mut breaks = vec![l0];
1900    for k in 0..scan {
1901        find_events(&engine, levels[k], &structure[k], levels[k + 1], &structure[k + 1], &mut breaks, 0)?;
1902    }
1903    breaks.push(l1);
1904    // Snap each event to a critical level of a source when one is that close.
1905    // A birth or death is found by bisection only to where the seeding first
1906    // sees the level's contour, which near a tip is a √ away from it: the
1907    // critical level is the exact one.
1908    let last = breaks.len() - 1;
1909    for level in breaks[1..last].iter_mut() {
1910        let mut nearest = *level;
1911        let mut distance = 1e-5 * scale;
1912        for critical in engine.critical.iter().flatten() {
1913            if (critical.0 - *level).abs() < distance {
1914                distance = (critical.0 - *level).abs();
1915                nearest = critical.0;
1916            }
1917        }
1918        *level = nearest;
1919    }
1920    breaks.sort_by(|a, b| a.total_cmp(b));
1921    // A source handing over to the next one at an edge can flicker over a few
1922    // bisection steps (the face's extremum sits a hair inside its domain); the
1923    // bands that leaves are far below any feature. Keep the first break of each
1924    // cluster, and the clip's own ends.
1925    let mut kept: Vec<f64> = Vec::with_capacity(breaks.len());
1926    for (index, &level) in breaks.iter().enumerate() {
1927        let is_end = index == 0 || index + 1 == breaks.len();
1928        match kept.last() {
1929            Some(&previous) if level - previous < 1e-5 * scale => {
1930                if is_end {
1931                    kept.pop();
1932                    kept.push(level);
1933                }
1934            }
1935            _ => kept.push(level),
1936        }
1937    }
1938    let mut breaks = kept;
1939
1940    // --- Merges no critical point explains: a FOLD the face's own Newton cannot
1941    //     reach (the plus wheel's arm tip: its level varies by 1e-4 along the
1942    //     envelope there). The gap between the two merging ends closes as
1943    //     √(ℓf − ℓ), so gap² is smooth in ℓ: fit it as a quadratic through three
1944    //     levels below the event, outside the band where the extremum Newton
1945    //     flickers, and take its root as the merge level; the gap's middle,
1946    //     extrapolated the same way, is the merge point. Both ends' sources
1947    //     record it as a critical point, and the bands keep their samples away
1948    //     from it (`fold_ends`).
1949    let mut fold_ends: Vec<f64> = Vec::new();
1950    for index in 1..breaks.len().saturating_sub(1) {
1951        let level = breaks[index];
1952        let snapped = engine.critical.iter().flatten().any(|c| (c.0 - level).abs() < 1e-9 * scale);
1953        if snapped {
1954            continue;
1955        }
1956        let room = (level - breaks[index - 1]).min(breaks[index + 1] - level);
1957        // Close enough that the √ law holds to the fit's order, far enough to be
1958        // clear of the flicker (the plus wheel: 2e-4 out, flicker inside 1e-5).
1959        let delta = (5e-6 * scale).min(room / 8.0);
1960        let below = engine.intervals_at(level - delta)?;
1961        let above = engine.intervals_at(level + delta)?;
1962        if below.len() <= above.len() {
1963            continue;
1964        }
1965        // Adjacent intervals below whose facing ends close into one above.
1966        let mut refined: Vec<(f64, f64, usize, usize)> = Vec::new();
1967        for k in 0..below.len() {
1968            let (x, y) = (below[k], below[(k + 1) % below.len()]);
1969            if !engine.angular && k + 1 == below.len() {
1970                break;
1971            }
1972            let gap_at = |intervals: &[Interval]| -> Option<(f64, f64)> {
1973                // the pair nearest (x.hi, y.lo) at this level
1974                let mut best: Option<(f64, f64, f64)> = None;
1975                for i in 0..intervals.len() {
1976                    let (p, q) = (intervals[i], intervals[(i + 1) % intervals.len()]);
1977                    let d = engine.o_difference(p.hi, x.hi).abs() + engine.o_difference(q.lo, y.lo).abs();
1978                    if best.map_or(true, |b| d < b.2) {
1979                        let gap = engine.o_difference(q.lo, p.hi);
1980                        best = Some((gap, p.hi + 0.5 * gap, d));
1981                    }
1982                }
1983                best.map(|b| (b.0, b.1))
1984            };
1985            let mut samples = Vec::new();
1986            for factor in [1.0, 2.0, 4.0] {
1987                let l = level - delta * factor;
1988                let intervals = engine.intervals_at(l)?;
1989                if intervals.len() != below.len() {
1990                    break;
1991                }
1992                if let Some((gap, middle)) = gap_at(&intervals) {
1993                    samples.push((l, gap, middle));
1994                }
1995            }
1996            if samples.len() < 3 || samples.iter().any(|s| s.1 <= 0.0 || s.1 > 0.5) {
1997                continue;
1998            }
1999            // Quadratic through (l, gap²); its root above the samples.
2000            let quad = |values: [f64; 3]| -> (f64, f64, f64) {
2001                let (x0, x1, x2) = (samples[0].0, samples[1].0, samples[2].0);
2002                let (y0, y1, y2) = (values[0], values[1], values[2]);
2003                let d01 = (y0 - y1) / (x0 - x1);
2004                let d12 = (y1 - y2) / (x1 - x2);
2005                let a2 = (d01 - d12) / (x0 - x2);
2006                let a1 = d01 - a2 * (x0 + x1);
2007                let a0 = y0 - a1 * x0 - a2 * x0 * x0;
2008                (a0, a1, a2)
2009            };
2010            let (c0, c1, c2) = quad([samples[0].1.powi(2), samples[1].1.powi(2), samples[2].1.powi(2)]);
2011            let root = if c2.abs() < 1e-300 {
2012                -c0 / c1
2013            } else {
2014                let disc = c1 * c1 - 4.0 * c2 * c0;
2015                if disc < 0.0 {
2016                    continue;
2017                }
2018                let r1 = (-c1 + disc.sqrt()) / (2.0 * c2);
2019                let r2 = (-c1 - disc.sqrt()) / (2.0 * c2);
2020                if (r1 - level).abs() < (r2 - level).abs() { r1 } else { r2 }
2021            };
2022            if !(root > samples[0].0 && (root - level).abs() < delta) {
2023                continue;
2024            }
2025            let (m0, m1, m2) = quad([samples[0].2, samples[1].2, samples[2].2]);
2026            let middle = m0 + m1 * root + m2 * root * root;
2027            refined.push((root, middle, x.hi_source, y.lo_source));
2028        }
2029        if !refined.is_empty() {
2030            // Every merging pair records its own point; the break is their mean
2031            // level (equal to round-off where the spaces are copies of one).
2032            let root = refined.iter().map(|r| r.0).sum::<f64>() / refined.len() as f64;
2033            for &(own, middle, a_source, b_source) in &refined {
2034                if debug {
2035                    eprintln!("  fold: break {level:.12} -> {own:.12} at o {middle:.12}");
2036                }
2037                engine.critical[a_source].push((root, middle));
2038                engine.critical[b_source].push((root, middle));
2039            }
2040            breaks[index] = root;
2041            fold_ends.push(root);
2042        }
2043    }
2044
2045    if debug {
2046        eprintln!("solid sweep: after events {:?} breaks {}", engine.counters.get(), breaks.len());
2047    }
2048    // --- Sample each band's interval ends.
2049    let mut pieces: Vec<Piece> = Vec::new();
2050    // Per band: the intervals at its bottom and top (for the level segments).
2051    let mut band_ends: Vec<(f64, f64, Vec<(usize, usize)>)> = Vec::new();
2052    for window in breaks.windows(2) {
2053        let (a, b) = (window[0], window[1]);
2054        if b - a < 1e-12 * scale {
2055            continue;
2056        }
2057        let mid = engine.intervals_at(0.5 * (a + b))?;
2058        if mid.is_empty() {
2059            continue;
2060        }
2061        let (band_pieces, _, _) = sample_band(&engine, a, b, &mid, &fold_ends)?;
2062        let first = pieces.len();
2063        let pairs = (0..band_pieces.len() / 2).map(|i| (first + 2 * i, first + 2 * i + 1)).collect();
2064        pieces.extend(band_pieces);
2065        band_ends.push((a, b, pairs));
2066    }
2067    if pieces.is_empty() {
2068        return Ok(Vec::new());
2069    }
2070    if debug {
2071        eprintln!("solid sweep: after bands {:?}", engine.counters.get());
2072        for (k, critical) in engine.critical.iter().enumerate() {
2073            eprintln!("  source {k} {:?}: critical {:?}", engine.sources[k], critical);
2074        }
2075    }
2076
2077    // --- One value per interval end at each break. The band below and the band
2078    //     above read an end that continues across a break from their own
2079    //     sources, at a level found only to the flicker cluster; the two agree to
2080    //     far below any feature but not to the bit, and a sliver of level segment
2081    //     between them is an edge no solid should carry. Snap every end at a level
2082    //     to its cluster's first value (ends of one interval meeting at a tip
2083    //     included).
2084    let snap_length = 1e-5 * scale;
2085    let mut break_levels: Vec<f64> = band_ends.iter().flat_map(|e| [e.0, e.1]).collect();
2086    break_levels.sort_by(|a, b| a.total_cmp(b));
2087    break_levels.dedup_by(|b, a| (*b - *a).abs() < 1e-12 * scale);
2088    for &level in &break_levels {
2089        let tolerance = if engine.angular { snap_length / level.max(1e-12) } else { snap_length };
2090        let mut ends: Vec<(usize, bool)> = Vec::new();
2091        for (index, piece) in pieces.iter().enumerate() {
2092            if (piece.points[0].0 - level).abs() < 1e-12 * scale {
2093                ends.push((index, false));
2094            }
2095            if (piece.points.last().expect("nonempty").0 - level).abs() < 1e-12 * scale {
2096                ends.push((index, true));
2097            }
2098        }
2099        let value = |pieces: &Vec<Piece>, (index, last): (usize, bool)| {
2100            if last { pieces[index].points.last().expect("nonempty").1 } else { pieces[index].points[0].1 }
2101        };
2102        for i in 0..ends.len() {
2103            let anchor = value(&pieces, ends[i]);
2104            for j in i + 1..ends.len() {
2105                let other = value(&pieces, ends[j]);
2106                let d = engine.o_difference(other, anchor);
2107                if d.abs() < tolerance && d != 0.0 {
2108                    let (index, last) = ends[j];
2109                    let target = other - d;
2110                    let points = &mut pieces[index].points;
2111                    if last {
2112                        points.last_mut().expect("nonempty").1 = target;
2113                    } else {
2114                        points[0].1 = target;
2115                    }
2116                }
2117            }
2118        }
2119    }
2120
2121    // --- Level segments: where the intervals above and below a level differ.
2122    let mut all_levels: Vec<f64> = band_ends.iter().flat_map(|e| [e.0, e.1]).collect();
2123    all_levels.sort_by(|a, b| a.total_cmp(b));
2124    all_levels.dedup_by(|b, a| (*b - *a).abs() < 1e-12 * scale);
2125    for &level in &all_levels {
2126        let mut below: Vec<(f64, f64)> = Vec::new();
2127        let mut above: Vec<(f64, f64)> = Vec::new();
2128        for (a, b, pairs) in &band_ends {
2129            for &(lo, hi) in pairs {
2130                let (lo, hi) = (&pieces[lo].points, &pieces[hi].points);
2131                if (b - level).abs() < 1e-12 * scale {
2132                    below.push((lo.last().expect("nonempty").1, hi.last().expect("nonempty").1));
2133                }
2134                if (a - level).abs() < 1e-12 * scale {
2135                    above.push((lo[0].1, hi[0].1));
2136                }
2137            }
2138        }
2139        let tolerance = if engine.angular { 1e-9 * scale / level.max(1e-12) } else { 1e-9 * scale };
2140        for (lo, hi) in symmetric_difference(&below, &above, engine.angular, tolerance) {
2141            let steps = 2;
2142            pieces.push(Piece {
2143                points: (0..=steps)
2144                    .map(|k| (level, lo + (hi - lo) * k as f64 / steps as f64))
2145                    .collect(),
2146                sigma: (0..=steps).map(|k| k as f64 / steps as f64).collect(),
2147                level_segment: true,
2148            });
2149        }
2150    }
2151
2152    if std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
2153        eprintln!("solid sweep: breaks {breaks:?}");
2154        for piece in &pieces {
2155            let a = piece.points[0];
2156            let b = *piece.points.last().expect("nonempty");
2157            eprintln!(
2158                "  piece {} ({:.9}, {:.9}) -> ({:.9}, {:.9}) n={}",
2159                if piece.level_segment { "LEVEL" } else { "edge " },
2160                a.0, a.1, b.0, b.1, piece.points.len()
2161            );
2162            if std::env::var("BREP_DEBUG_SOLID_SWEEP").as_deref() == Ok("2") {
2163                for p in piece.points.iter().take(6) {
2164                    eprintln!("      {:.12} {:.12}", p.0, p.1);
2165                }
2166            }
2167        }
2168    }
2169    // --- At a crest the walls have met: the top arc is no boundary of what stays.
2170    if let Some(level) = crest {
2171        pieces.retain(|piece| !(piece.level_segment && (piece.points[0].0 - level).abs() < 1e-9 * scale));
2172    }
2173    // --- Assemble loops and build the bodies.
2174    let loops = assemble_loops(&engine, pieces)?;
2175    let mut bodies = Vec::new();
2176    for pieces in loops {
2177        bodies.push(build_body(&engine, &pieces)?);
2178    }
2179    if crest.is_some() {
2180        let [kept] = bodies.as_slice() else {
2181            return Err(refuse("whole_level", "what stays below the crest is not one body".into()));
2182        };
2183        return clip_less(clip, frame_base(&engine), kept);
2184    }
2185    Ok(bodies)
2186}
2187
2188/// Replace a screw loft's side surfaces and helical edges by quintic splines
2189/// through the exact screw and its first two derivatives. A cubic interpolant
2190/// through `segments + 1` sections misses a turn by h⁴; these by h⁶, which is
2191/// what lets a long fine thread be built with few spans. Sections, caps and
2192/// parameters are the loft's, so the trims stay as they are.
2193fn carry_along_screw(body: &mut BrepSolid, engine: &Engine, c: f64, span: f64, segments: usize) -> Result<(), KernelRefusal> {
2194    if lean_walls_on() {
2195        return carry_along_screw_to_order(body, engine, c, span, segments, LEAN_CARRY_ORDER);
2196    }
2197    let origin = engine.clip.axis_origin;
2198    let ez = engine.frame.ez;
2199    // The six Bézier points of each span collapse to three a span, C² at the joints.
2200    let carry = |start: Vec3| -> Vec<Vec3> {
2201        let h = span / segments as f64;
2202        let axial = ez.scale(start.sub(origin).dot(ez));
2203        let radial = start.sub(origin).sub(axial);
2204        let at = |k: usize| {
2205            let angle = h * k as f64;
2206            let r = radial.rotate_about(ez, angle);
2207            let value = origin.add(axial).add(r).add(ez.scale(c * angle));
2208            (value, ez.cross(r).add(ez.scale(c)), r.scale(-1.0))
2209        };
2210        let piece = |k: usize| {
2211            let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
2212            [
2213                f0,
2214                f0.add(d0.scale(h / 5.0)),
2215                f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
2216                f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
2217                f1.sub(d1.scale(h / 5.0)),
2218                f1,
2219            ]
2220        };
2221        let mut points = Vec::with_capacity(3 * segments + 3);
2222        let first = piece(0);
2223        points.extend_from_slice(&first[..3]);
2224        for k in 0..segments - 1 {
2225            let (here, next) = (piece(k), piece(k + 1));
2226            points.push(here[3]);
2227            points.push(here[4].scale(2.0).sub(here[3]));
2228            points.push(next[2]);
2229        }
2230        let last = piece(segments - 1);
2231        points.extend_from_slice(&last[3..]);
2232        points
2233    };
2234    let knots = |lo: f64, hi: f64| -> Vec<f64> {
2235        let mut knots = vec![lo; 6];
2236        for k in 1..segments {
2237            knots.extend([lo + (hi - lo) * k as f64 / segments as f64; 3]);
2238        }
2239        knots.extend([hi; 6]);
2240        knots
2241    };
2242    let point = |p: &crate::Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
2243    let moved = |p: &crate::Vec4, angle: f64| -> Vec3 {
2244        rotate(point(p), origin, ez, angle).add(ez.scale(c * angle))
2245    };
2246    let tolerance = 1e-7 * engine.scale;
2247    for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
2248        let rows = &face.surface.control_points;
2249        if rows[0].len() != segments + 1 {
2250            continue; // a cap
2251        }
2252        // The loft's columns must already be this screw, from section to section.
2253        if rows.iter().any(|row| moved(&row[0], span).sub(point(&row[segments])).length() > tolerance) {
2254            return Err(refuse("screw_loft", "a lofted wall does not follow the screw".into()));
2255        }
2256        let lifted: Vec<Vec<crate::Vec4>> = rows
2257            .iter()
2258            .map(|row| {
2259                let w = row[0].w;
2260                carry(point(&row[0])).into_iter().map(|q| crate::Vec4::from_point(q, w)).collect()
2261            })
2262            .collect();
2263        let v = &face.surface.knots_v;
2264        let (lo, hi) = (v[0], *v.last().expect("knots"));
2265        face.surface = crate::NurbsSurface::new(face.surface.degree_u, 5, face.surface.knots_u.clone(), knots(lo, hi), lifted)
2266            .or_refuse(KernelStage::Fragment, "screw_surface")?;
2267    }
2268    let height = c * span;
2269    let points: rustc_hash::FxHashMap<u64, Vec3> = body.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
2270    for edge in &mut body.edges {
2271        let (from, to) = (points[&edge.start_vertex_id], points[&edge.end_vertex_id]);
2272        let rise = to.sub(from).dot(ez);
2273        // An edge in a cap rises nothing, a carried one the whole height: told apart
2274        // well inside the height itself, however short the clip against its radius.
2275        if (rise.abs() - height.abs()).abs() > tolerance.min(0.25 * height.abs()) {
2276            continue; // lies in a cap
2277        }
2278        let domain = edge.curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
2279        let forward = rise * height > 0.0;
2280        let mut path = carry(if forward { from } else { to });
2281        if !forward {
2282            path.reverse();
2283        }
2284        edge.curve = NurbsCurve::new(5, knots(domain[0], domain[1]), path.into_iter().map(|q| crate::Vec4::from_point(q, 1.0)).collect())
2285            .or_refuse(KernelStage::Fragment, "screw_edge")?;
2286    }
2287    Ok(())
2288}
2289
2290/// `rows` copies of `row` along the screw, each the image of the last, sharing
2291/// the section edges and vertices between neighbours; only the first bottom cap
2292/// and the last top cap stay.
2293/// Knots of the carry of order `m` (degree 2m + 1, C^m) over [lo, hi] in
2294/// `segments` even spans.
2295fn carry_knots_of_order(lo: f64, hi: f64, segments: usize, m: usize) -> Vec<f64> {
2296    let degree = 2 * m + 1;
2297    let mut knots = vec![lo; degree + 1];
2298    for k in 1..segments {
2299        knots.extend(std::iter::repeat_n(lo + (hi - lo) * k as f64 / segments as f64, m + 1));
2300    }
2301    knots.extend(std::iter::repeat_n(hi, degree + 1));
2302    knots
2303}
2304
2305/// The polar form of the Bézier curve `b` at `ts` (de Casteljau with a
2306/// parameter of its own at each level).
2307fn bezier_blossom(b: &[Vec3], ts: &[f64]) -> Vec3 {
2308    let mut p = b.to_vec();
2309    for (level, &t) in ts.iter().enumerate() {
2310        for i in 0..p.len() - 1 - level {
2311            p[i] = p[i].scale(1.0 - t).add(p[i + 1].scale(t));
2312        }
2313    }
2314    p[0]
2315}
2316
2317/// Control points of the C^m spline of degree 2m + 1 that matches a path and
2318/// its first m derivatives at `segments + 1` even steps of [0, h·segments]:
2319/// `jet(k)` is the path's derivatives 0..=m at step k (per unit parameter).
2320/// Each span is the Hermite interpolant of its two ends' jets; the spline's
2321/// points are the spans' polar forms at its knots (`carry_knots_of_order`), which
2322/// adjacent spans share where they meet to order m.
2323fn carry_points_of_order(jet: impl Fn(usize) -> Vec<Vec3>, h: f64, segments: usize, m: usize) -> Vec<Vec3> {
2324    let degree = 2 * m + 1;
2325    let binomial = |n: usize, k: usize| -> f64 { (0..k).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64) };
2326    // (n - k)!/n!, the factor from a k-th derivative to a k-th difference.
2327    let falling = |k: usize| -> f64 { (0..k).fold(1.0, |acc, i| acc / (degree - i) as f64) };
2328    let bezier = |k: usize| -> Vec<Vec3> {
2329        let (start, end) = (jet(k), jet(k + 1));
2330        let mut b = vec![Vec3::new(0.0, 0.0, 0.0); degree + 1];
2331        for j in 0..=m {
2332            let scale = h.powi(j as i32) * falling(j);
2333            // Δ^j b_0 = start_j·scale, so b_j = Σ_i C(j, i) Δ^i b_0.
2334            let mut front = start[j].scale(scale);
2335            for i in 0..j {
2336                // Δ^j b_0 = Σ_i (-1)^(j-i) C(j, i) b_i
2337                let sign = if (j - i) % 2 == 0 { 1.0 } else { -1.0 };
2338                front = front.sub(b[i].scale(sign * binomial(j, i)));
2339            }
2340            b[j] = front;
2341            // ∇^j b_n = Σ_i (-1)^i C(j, i) b_(n-i) = end_j·scale.
2342            let mut back = end[j].scale(scale);
2343            for i in 0..j {
2344                let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
2345                back = back.sub(b[degree - i].scale(sign * binomial(j, i)));
2346            }
2347            b[degree - j] = back.scale(if j % 2 == 0 { 1.0 } else { -1.0 });
2348        }
2349        b
2350    };
2351    let spans: Vec<Vec<Vec3>> = (0..segments).map(bezier).collect();
2352    // Knots in units of a span.
2353    let knots = carry_knots_of_order(0.0, segments as f64, segments, m);
2354    let count = knots.len() - degree - 1;
2355    (0..count)
2356        .map(|i| {
2357            let args = &knots[i + 1..=i + degree];
2358            let k = (args[0].floor() as usize).min(segments - 1);
2359            let local: Vec<f64> = args.iter().map(|t| t - k as f64).collect();
2360            bezier_blossom(&spans[k], &local)
2361        })
2362        .collect()
2363}
2364
2365/// `carry_along_screw` to order `m`: each wall's columns and each carried edge
2366/// as the C^m spline of degree 2m + 1 through the exact screw and m of its
2367/// derivatives at `segments + 1` turns.
2368fn carry_along_screw_to_order(body: &mut BrepSolid, engine: &Engine, c: f64, span: f64, segments: usize, m: usize) -> Result<(), KernelRefusal> {
2369    let origin = engine.clip.axis_origin;
2370    let ez = engine.frame.ez;
2371    let degree = 2 * m + 1;
2372    let h = span / segments as f64;
2373    let carry = |start: Vec3| -> Vec<Vec3> {
2374        let axial = ez.scale(start.sub(origin).dot(ez));
2375        let radial = start.sub(origin).sub(axial);
2376        let jet = |k: usize| -> Vec<Vec3> {
2377            let angle = h * k as f64;
2378            let mut out = Vec::with_capacity(m + 1);
2379            out.push(origin.add(axial).add(radial.rotate_about(ez, angle)).add(ez.scale(c * angle)));
2380            for j in 1..=m {
2381                // The j-th derivative of the turned radius is the radius turned a further j quarter turns.
2382                let turned = radial.rotate_about(ez, angle + j as f64 * std::f64::consts::FRAC_PI_2);
2383                out.push(if j == 1 { turned.add(ez.scale(c)) } else { turned });
2384            }
2385            out
2386        };
2387        carry_points_of_order(jet, h, segments, m)
2388    };
2389    let point = |p: &crate::Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
2390    let moved = |p: &crate::Vec4, angle: f64| -> Vec3 { rotate(point(p), origin, ez, angle).add(ez.scale(c * angle)) };
2391    let tolerance = 1e-7 * engine.scale;
2392    for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
2393        let rows = &face.surface.control_points;
2394        if rows[0].len() != segments + 1 {
2395            continue; // a cap
2396        }
2397        if rows.iter().any(|row| moved(&row[0], span).sub(point(&row[segments])).length() > tolerance) {
2398            return Err(refuse("screw_loft", "a lofted wall does not follow the screw".into()));
2399        }
2400        let lifted: Vec<Vec<crate::Vec4>> = rows
2401            .iter()
2402            .map(|row| {
2403                let w = row[0].w;
2404                carry(point(&row[0])).into_iter().map(|q| crate::Vec4::from_point(q, w)).collect()
2405            })
2406            .collect();
2407        let v = &face.surface.knots_v;
2408        let (lo, hi) = (v[0], *v.last().expect("knots"));
2409        face.surface = crate::NurbsSurface::new(face.surface.degree_u, degree, face.surface.knots_u.clone(), carry_knots_of_order(lo, hi, segments, m), lifted)
2410            .or_refuse(KernelStage::Fragment, "screw_surface")?;
2411    }
2412    let height = c * span;
2413    let points: rustc_hash::FxHashMap<u64, Vec3> = body.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
2414    for edge in &mut body.edges {
2415        let (from, to) = (points[&edge.start_vertex_id], points[&edge.end_vertex_id]);
2416        let rise = to.sub(from).dot(ez);
2417        if (rise.abs() - height.abs()).abs() > tolerance.min(0.25 * height.abs()) {
2418            continue; // lies in a cap
2419        }
2420        let domain = edge.curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
2421        let forward = rise * height > 0.0;
2422        let mut path = carry(if forward { from } else { to });
2423        if !forward {
2424            path.reverse();
2425        }
2426        edge.curve = NurbsCurve::new(
2427            degree,
2428            carry_knots_of_order(domain[0], domain[1], segments, m),
2429            path.into_iter().map(|q| crate::Vec4::from_point(q, 1.0)).collect(),
2430        )
2431        .or_refuse(KernelStage::Fragment, "screw_edge")?;
2432    }
2433    Ok(())
2434}
2435
2436/// Control points a carried wall has along the screw, in `segments` spans.
2437fn carried_columns(segments: usize) -> usize {
2438    if lean_walls_on() {
2439        (LEAN_CARRY_ORDER + 1) * (segments + 1)
2440    } else {
2441        3 * segments + 3
2442    }
2443}
2444
2445fn stack_screw_rows(
2446    row: &BrepSolid,
2447    engine: &Engine,
2448    c: f64,
2449    span: f64,
2450    segments: usize,
2451    rows: usize,
2452) -> Result<BrepSolid, KernelRefusal> {
2453    let origin = engine.clip.axis_origin;
2454    let ez = engine.frame.ez;
2455    let moved = |x: Vec3, copy: usize| -> Vec3 {
2456        let angle = span * copy as f64;
2457        rotate(x, origin, ez, angle).add(ez.scale(c * angle))
2458    };
2459    let tolerance = 1e-7 * engine.scale;
2460    let height = |x: Vec3| x.sub(origin).dot(ez);
2461    let points: rustc_hash::FxHashMap<u64, Vec3> = row.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
2462    let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
2463    for vertex in &row.vertices {
2464        low = low.min(height(vertex.point));
2465        high = high.max(height(vertex.point));
2466    }
2467    let at = |id: u64, level: f64| (height(points[&id]) - level).abs() <= tolerance;
2468    let in_level = |edge: &crate::topology::EdgeRecord, level: f64| at(edge.start_vertex_id, level) && at(edge.end_vertex_id, level);
2469    let (bottom, top) = if c * span > 0.0 { (low, high) } else { (high, low) };
2470    // Each bottom vertex and edge of a copy is a top one of the copy before.
2471    let mut vertex_below: rustc_hash::FxHashMap<u64, u64> = Default::default();
2472    for vertex in row.vertices.iter().filter(|vertex| at(vertex.id, bottom)) {
2473        let up = moved(vertex.point, 1);
2474        let below = row.vertices.iter().find(|other| at(other.id, top) && other.point.sub(up).length() <= tolerance);
2475        let Some(below) = below else { return Err(refuse("screw_rows", "a row's section does not meet the next".into())) };
2476        vertex_below.insert(vertex.id, below.id);
2477    }
2478    let mut edge_below: rustc_hash::FxHashMap<u64, u64> = Default::default();
2479    for edge in row.edges.iter().filter(|edge| in_level(edge, bottom)) {
2480        let ends = (vertex_below[&edge.start_vertex_id], vertex_below[&edge.end_vertex_id]);
2481        let below = row.edges.iter().find(|other| in_level(other, top) && (other.start_vertex_id, other.end_vertex_id) == ends);
2482        let Some(below) = below else { return Err(refuse("screw_rows", "a row's section edge does not meet the next".into())) };
2483        edge_below.insert(edge.id, below.id);
2484    }
2485    let face_ids = row.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| {
2486        std::iter::once(face.id).chain(face.loops.iter().flat_map(|l| std::iter::once(l.id).chain(l.coedges.iter().map(|c| c.id))))
2487    });
2488    let stride = row
2489        .vertices
2490        .iter()
2491        .map(|v| v.id)
2492        .chain(row.edges.iter().map(|e| e.id))
2493        .chain(face_ids)
2494        .max()
2495        .unwrap_or(0)
2496        + 1;
2497    let vertex_id = |id: u64, copy: usize| match vertex_below.get(&id) {
2498        Some(&below) if copy > 0 => below + stride * (copy as u64 - 1),
2499        _ => id + stride * copy as u64,
2500    };
2501    let edge_id = |id: u64, copy: usize| match edge_below.get(&id) {
2502        Some(&below) if copy > 0 => below + stride * (copy as u64 - 1),
2503        _ => id + stride * copy as u64,
2504    };
2505    let is_cap = |face: &crate::FaceRecord| face.surface.control_points[0].len() != carried_columns(segments);
2506    let cap_level = |face: &crate::FaceRecord, level: f64| {
2507        face.loops.iter().flat_map(|l| &l.coedges).all(|coedge| {
2508            row.edges.iter().find(|edge| edge.id == coedge.edge_id).is_some_and(|edge| in_level(edge, level))
2509        })
2510    };
2511    let mut stacked = row.clone();
2512    stacked.mass_properties_cache = Default::default();
2513    stacked.vertices.clear();
2514    stacked.edges.clear();
2515    for shell in &mut stacked.shells {
2516        shell.faces.clear();
2517    }
2518    for copy in 0..rows {
2519        for vertex in &row.vertices {
2520            if copy == 0 || !vertex_below.contains_key(&vertex.id) {
2521                stacked.vertices.push(crate::topology::VertexRecord { id: vertex_id(vertex.id, copy), point: moved(vertex.point, copy) });
2522            }
2523        }
2524        for edge in &row.edges {
2525            if copy == 0 || !edge_below.contains_key(&edge.id) {
2526                stacked.edges.push(crate::topology::EdgeRecord {
2527                    id: edge_id(edge.id, copy),
2528                    curve: transform_curve(&edge.curve, |x| moved(x, copy))?,
2529                    t0: edge.t0,
2530                    t1: edge.t1,
2531                    start_vertex_id: vertex_id(edge.start_vertex_id, copy),
2532                    end_vertex_id: vertex_id(edge.end_vertex_id, copy),
2533                    degenerate: edge.degenerate,
2534                    name: edge.name.clone(),
2535                });
2536            }
2537        }
2538        for (target, shell) in stacked.shells.iter_mut().zip(&row.shells) {
2539            for face in &shell.faces {
2540                if is_cap(face) && !((copy == 0 && cap_level(face, bottom)) || (copy + 1 == rows && cap_level(face, top))) {
2541                    continue;
2542                }
2543                let control_points = face
2544                    .surface
2545                    .control_points
2546                    .iter()
2547                    .map(|line| {
2548                        line.iter()
2549                            .map(|p| {
2550                                let w = p.w;
2551                                crate::Vec4::from_point(moved(Vec3::new(p.x / w, p.y / w, p.z / w), copy), w)
2552                            })
2553                            .collect()
2554                    })
2555                    .collect();
2556                let surface = crate::NurbsSurface::new(
2557                    face.surface.degree_u,
2558                    face.surface.degree_v,
2559                    face.surface.knots_u.clone(),
2560                    face.surface.knots_v.clone(),
2561                    control_points,
2562                )
2563                .or_refuse(KernelStage::Fragment, "screw_rows")?;
2564                let mut copied = face.clone();
2565                copied.surface = surface;
2566                copied.id += stride * copy as u64;
2567                for loop_record in &mut copied.loops {
2568                    loop_record.id += stride * copy as u64;
2569                    for coedge in &mut loop_record.coedges {
2570                        coedge.id += stride * copy as u64;
2571                        coedge.edge_id = edge_id(coedge.edge_id, copy);
2572                    }
2573                }
2574                target.faces.push(copied);
2575            }
2576        }
2577    }
2578    let issues = stacked.validate();
2579    if issues.iter().any(|issue| issue.severity == "error") {
2580        return Err(refuse("screw_rows", format!("the stacked thread is invalid: {issues:?}")));
2581    }
2582    Ok(stacked)
2583}
2584
2585/// Where the clip's solid starts, on its axis.
2586fn frame_base(engine: &Engine) -> Vec3 {
2587    engine.frame.world([0.0, 0.0, engine.clip.axial[0]])
2588}
2589
2590/// The whole clip cylinder with `kept` taken out of it.
2591fn clip_less(clip: &SweepClip, base: Vec3, kept: &BrepSolid) -> Result<Vec<BrepSolid>, KernelRefusal> {
2592    let direction = clip.axis_direction.normalized().or_refuse(KernelStage::Collect, "clip_axis")?;
2593    let cylinder = crate::make_cylinder_brep(base, direction, clip.radius[1], clip.axial[1] - clip.axial[0])
2594        .or_refuse(KernelStage::Fragment, "clip_cylinder")?;
2595    if thread_rows_on() {
2596        if let Some(direct) = clip_less_direct(&cylinder, base, direction, kept)? {
2597            return Ok(vec![direct]);
2598        }
2599    }
2600    let r = crate::boolean_operation(&cylinder, kept, crate::BooleanOperation::Subtract, &Default::default())?;
2601    Ok(vec![r])
2602}
2603
2604/// `cylinder` with `kept` taken out, where `kept` runs from cap to cap inside
2605/// the wall: nothing crosses, so the result is written down: `kept`'s end loops
2606/// become holes in the caps and its sides turn inside out. `None` when the
2607/// bodies are not that shape; the caller takes the boolean then.
2608fn clip_less_direct(
2609    cylinder: &BrepSolid,
2610    base: Vec3,
2611    direction: Vec3,
2612    kept: &BrepSolid,
2613) -> Result<Option<BrepSolid>, KernelRefusal> {
2614    if kept.shells.len() != 1 || cylinder.shells.len() != 1 {
2615        return Ok(None);
2616    }
2617    let mut stride = 0;
2618    for shell in &cylinder.shells {
2619        for face in &shell.faces {
2620            stride = stride.max(face.id);
2621            for loop_record in &face.loops {
2622                stride = stride.max(loop_record.id);
2623                stride = loop_record.coedges.iter().fold(stride, |m, c| m.max(c.id));
2624            }
2625        }
2626    }
2627    stride = cylinder.vertices.iter().fold(stride, |m, v| m.max(v.id));
2628    stride = cylinder.edges.iter().fold(stride, |m, e| m.max(e.id)) + 1;
2629    let corners = |surface: &crate::NurbsSurface| -> Result<([f64; 4], [Vec3; 3]), String> {
2630        let (u0, u1) = (surface.knots_u[0], *surface.knots_u.last().ok_or("knots")?);
2631        let (v0, v1) = (surface.knots_v[0], *surface.knots_v.last().ok_or("knots")?);
2632        Ok(([u0, u1, v0, v1], [surface.evaluate(u0, v0)?, surface.evaluate(u1, v0)?, surface.evaluate(u0, v1)?]))
2633    };
2634    let mut result = cylinder.clone();
2635    result.mass_properties_cache = Default::default();
2636    result.genus = 1;
2637    result.vertices.extend(kept.vertices.iter().map(|v| crate::topology::VertexRecord { id: v.id + stride, point: v.point }));
2638    for edge in &kept.edges {
2639        let mut edge = edge.clone();
2640        edge.id += stride;
2641        edge.start_vertex_id += stride;
2642        edge.end_vertex_id += stride;
2643        result.edges.push(edge);
2644    }
2645    let mut holes = 0;
2646    let turned = |loop_record: &crate::topology::LoopRecord| -> Result<crate::topology::LoopRecord, KernelRefusal> {
2647        let mut coedges = Vec::with_capacity(loop_record.coedges.len());
2648        for coedge in loop_record.coedges.iter().rev() {
2649            coedges.push(crate::topology::CoedgeRecord {
2650                id: coedge.id + stride,
2651                edge_id: coedge.edge_id + stride,
2652                forward: !coedge.forward,
2653                pcurve: coedge.pcurve.reversed().or_refuse(KernelStage::Fragment, "clip_less_pcurve")?,
2654            });
2655        }
2656        Ok(crate::topology::LoopRecord { id: loop_record.id + stride, coedges })
2657    };
2658    for face in &kept.shells[0].faces {
2659        let mut loops = Vec::with_capacity(face.loops.len());
2660        for loop_record in &face.loops {
2661            loops.push(turned(loop_record)?);
2662        }
2663        if !face.surface.is_affine().unwrap_or(false) {
2664            result.shells[0].faces.push(crate::FaceRecord {
2665                id: face.id + stride,
2666                surface: face.surface.clone(),
2667                same_sense: !face.same_sense,
2668                loops,
2669                name: face.name.clone(),
2670            });
2671            continue;
2672        }
2673        // An end: its loops are holes in the cap at its height, read in that cap's chart.
2674        let (from_box, from) = corners(&face.surface).or_refuse(KernelStage::Fragment, "clip_less_chart")?;
2675        let height = from[0].sub(base).dot(direction);
2676        let mut caps = result.shells[0].faces.iter_mut().filter(|cap| {
2677            cap.surface.is_affine().unwrap_or(false)
2678                && cap.surface.evaluate(cap.surface.knots_u[0], cap.surface.knots_v[0]).is_ok_and(|p| (p.sub(base).dot(direction) - height).abs() < 1e-9 * (1.0 + height.abs()))
2679        });
2680        let (Some(cap), None) = (caps.next(), caps.next()) else { return Ok(None) };
2681        let (to_box, to) = corners(&cap.surface).or_refuse(KernelStage::Fragment, "clip_less_chart")?;
2682        let (eu, ev) = (to[1].sub(to[0]), to[2].sub(to[0]));
2683        if eu.dot(ev).abs() > 1e-9 * eu.length() * ev.length() {
2684            return Ok(None);
2685        }
2686        let chart = |p: Vec3| {
2687            let d = p.sub(to[0]);
2688            [
2689                to_box[0] + (to_box[1] - to_box[0]) * d.dot(eu) / eu.dot(eu),
2690                to_box[2] + (to_box[3] - to_box[2]) * d.dot(ev) / ev.dot(ev),
2691            ]
2692        };
2693        let source = |a: f64, b: f64| from[0].add(from[1].sub(from[0]).scale(a)).add(from[2].sub(from[0]).scale(b));
2694        let (origin, across, up) = (chart(source(0.0, 0.0)), chart(source(1.0, 0.0)), chart(source(0.0, 1.0)));
2695        for loop_record in &mut loops {
2696            for coedge in &mut loop_record.coedges {
2697                let curve = &coedge.pcurve;
2698                let control_points = curve
2699                    .control_points
2700                    .iter()
2701                    .map(|p| {
2702                        let a = (p.x / p.w - from_box[0]) / (from_box[1] - from_box[0]);
2703                        let b = (p.y / p.w - from_box[2]) / (from_box[3] - from_box[2]);
2704                        let x = origin[0] + a * (across[0] - origin[0]) + b * (up[0] - origin[0]);
2705                        let y = origin[1] + a * (across[1] - origin[1]) + b * (up[1] - origin[1]);
2706                        crate::Vec4 { x: x * p.w, y: y * p.w, z: p.z, w: p.w }
2707                    })
2708                    .collect();
2709                coedge.pcurve = NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
2710                    .or_refuse(KernelStage::Fragment, "clip_less_pcurve")?;
2711            }
2712        }
2713        cap.loops.extend(loops);
2714        holes += 1;
2715    }
2716    if holes != 2 || result.validate().iter().any(|issue| issue.severity == "error") {
2717        return Ok(None);
2718    }
2719    Ok(Some(result))
2720}
2721
2722/// The level above which a screw's sweep covers every angle, up to the clip,
2723/// when the material between its turns narrows to nothing there; `None` when
2724/// the sweep leaves something at the clip's edge.
2725fn crest_level(engine: &Engine) -> Result<Option<f64>, KernelRefusal> {
2726    let whole = |level: f64| -> Result<bool, KernelRefusal> {
2727        match engine.intervals_at(level) {
2728            Ok(_) => Ok(false),
2729            Err(error) if error.message.contains(WHOLE_LEVEL) => Ok(true),
2730            Err(error) => Err(error),
2731        }
2732    };
2733    let [l0, l1] = engine.clip.radius;
2734    let scan = 64;
2735    let level_at = |k: usize| l0 + (l1 - l0) * k as f64 / scan as f64;
2736    if !whole(l1)? {
2737        return Ok(None);
2738    }
2739    let mut first = scan;
2740    while first > 0 && whole(level_at(first - 1))? {
2741        first -= 1;
2742    }
2743    if first == 0 {
2744        return Ok(None);
2745    }
2746    let (mut below, mut above) = (level_at(first - 1), level_at(first));
2747    for _ in 0..60 {
2748        let middle = 0.5 * (below + above);
2749        if whole(middle)? {
2750            above = middle;
2751        } else {
2752            below = middle;
2753        }
2754    }
2755    // The material must narrow to nothing there, not stop at some width. Near
2756    // the end the walls have already crossed unseen (the oracle stops seeing the
2757    // gap a little past the crest), so the crest is where the gap, measured
2758    // well below, extrapolates to zero.
2759    let gap = |level: f64| -> Result<f64, KernelRefusal> {
2760        Ok(TAU - engine.intervals_at(level)?.iter().map(|interval| interval.hi - interval.lo).sum::<f64>())
2761    };
2762    let step = 4e-5 * (l1 - l0);
2763    let (x0, x1, x2) = (below - 3.0 * step, below - 2.0 * step, below - step);
2764    let (g0, g1, g2) = (gap(x0)?, gap(x1)?, gap(x2)?);
2765    if !(g2 > 0.0 && g1 > g2 && g0 > g1) || g2 > 16.0 * (g1 - g2) {
2766        return Ok(None);
2767    }
2768    let curve = |x: f64| {
2769        g0 * (x - x1) * (x - x2) / ((x0 - x1) * (x0 - x2))
2770            + g1 * (x - x0) * (x - x2) / ((x1 - x0) * (x1 - x2))
2771            + g2 * (x - x0) * (x - x1) / ((x2 - x0) * (x2 - x1))
2772    };
2773    let (mut lo, mut hi) = (x2, below + step);
2774    if curve(hi) > 0.0 {
2775        return Ok(None);
2776    }
2777    for _ in 0..80 {
2778        let middle = 0.5 * (lo + hi);
2779        if curve(middle) > 0.0 {
2780            lo = middle;
2781        } else {
2782            hi = middle;
2783        }
2784    }
2785    Ok(Some(0.5 * (lo + hi)))
2786}
2787
2788fn find_events(
2789    engine: &Engine,
2790    a: f64,
2791    sa: &[Interval],
2792    b: f64,
2793    sb: &[Interval],
2794    breaks: &mut Vec<f64>,
2795    depth: usize,
2796) -> Result<(), KernelRefusal> {
2797    if compatible(engine, sa, sb) {
2798        return Ok(());
2799    }
2800    if depth <= 2 && std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
2801        let summary = |s: &[Interval]| -> Vec<(usize, usize, f64, f64)> {
2802            s.iter().map(|x| (x.lo_source, x.hi_source, (x.lo * 1e4).round() / 1e4, (x.hi * 1e4).round() / 1e4)).collect()
2803        };
2804        eprintln!("  find_events depth {depth} [{a:.9}, {b:.9}] {:?}\n      -> {:?} counters {:?}", summary(sa), summary(sb), engine.counters.get());
2805    }
2806    if b - a < 1e-13 * engine.scale || depth > 60 {
2807        breaks.push(0.5 * (a + b));
2808        return Ok(());
2809    }
2810    let m = 0.5 * (a + b);
2811    let sm = engine.intervals_at(m)?;
2812    // Both halves stay incompatible only where the reading flickers; follow the
2813    // half that changes first and let the other be found from the scan above.
2814    if !compatible(engine, sa, &sm) && !compatible(engine, &sm, sb) && depth > 8 {
2815        breaks.push(m);
2816        return Ok(());
2817    }
2818    find_events(engine, a, sa, m, &sm, breaks, depth + 1)?;
2819    find_events(engine, m, &sm, b, sb, breaks, depth + 1)
2820}
2821
2822/// The candidate of `source` at `level` nearest `guess` (or its critical point
2823/// at that level); `fallback` when the source has none there.
2824fn end_value(engine: &Engine, source: usize, level: f64, guess: f64, fallback: f64) -> f64 {
2825    let mut candidates = Vec::new();
2826    engine.source_candidates(source, level, &mut candidates);
2827    let mut options: Vec<f64> = candidates.iter().map(|c| c.0).collect();
2828    for critical in &engine.critical[source] {
2829        if (critical.0 - level).abs() < 1e-7 * engine.scale {
2830            options.push(critical.1);
2831        }
2832    }
2833    let mut best = fallback;
2834    let mut distance = f64::INFINITY;
2835    for option in options {
2836        let d = engine.o_difference(option, guess).abs();
2837        if d < distance {
2838            distance = d;
2839            best = guess + engine.o_difference(option, guess);
2840        }
2841    }
2842    best
2843}
2844
2845/// Sample a band (a, b) of constant structure; return its end pieces and the
2846/// intervals at its bottom and top.
2847#[allow(clippy::type_complexity)]
2848fn sample_band(
2849    engine: &Engine,
2850    a: f64,
2851    b: f64,
2852    mid: &[Interval],
2853    fold_ends: &[f64],
2854) -> Result<(Vec<Piece>, Vec<(f64, f64)>, Vec<(f64, f64)>), KernelRefusal> {
2855    let count = mid.len();
2856    let n = 24usize;
2857    // Next to a fold the extremum Newton flickers; keep every sample at least
2858    // this far from a fold end (the end itself reads the fold's critical point).
2859    let near_fold = fold_ends.iter().any(|f| (f - a).abs() < 1e-12 * engine.scale || (f - b).abs() < 1e-12 * engine.scale);
2860    let n_cap = if near_fold {
2861        let keep = (1e-4 * engine.scale).min((b - a) / 50.0);
2862        // smallest σ step: (b − a)(1 − cos(π/n))/2 ≥ keep
2863        let ratio = (1.0 - 2.0 * keep / (b - a)).clamp(-1.0, 1.0);
2864        ((PI / ratio.acos()).floor() as usize).max(8)
2865    } else {
2866        192
2867    };
2868    let mut n = n.min(n_cap);
2869    loop {
2870        let sigma: Vec<f64> = (0..=n).map(|k| k as f64 / n as f64).collect();
2871        let level_at = |s: f64| a + (b - a) * (1.0 - (PI * s).cos()) / 2.0;
2872        // Track every interval from the middle sample outward.
2873        let mut lo = vec![vec![f64::NAN; n + 1]; count];
2874        let mut hi = vec![vec![f64::NAN; n + 1]; count];
2875        let mut lo_src = vec![vec![0usize; n + 1]; count];
2876        let mut hi_src = vec![vec![0usize; n + 1]; count];
2877        let mid_index = n / 2;
2878        let mid_intervals = engine.intervals_at(level_at(sigma[mid_index]))?;
2879        if mid_intervals.len() != count {
2880            return Err(refuse("band_structure", format!("the structure changes inside the band {a}..{b}")));
2881        }
2882        for (i, interval) in mid_intervals.iter().enumerate() {
2883            lo[i][mid_index] = interval.lo;
2884            hi[i][mid_index] = interval.hi;
2885            lo_src[i][mid_index] = interval.lo_source;
2886            hi_src[i][mid_index] = interval.hi_source;
2887        }
2888        for direction in [-1i64, 1] {
2889            let mut k = mid_index as i64 + direction;
2890            while k > 0 && (k as usize) < n {
2891                let ku = k as usize;
2892                let previous = (ku as i64 - direction) as usize;
2893                let intervals = engine.intervals_at(level_at(sigma[ku]))?;
2894                if intervals.len() != count {
2895                    return Err(refuse("band_structure", format!("the structure changes inside the band {a}..{b}")));
2896                }
2897                for i in 0..count {
2898                    let centre = 0.5 * (lo[i][previous] + hi[i][previous]);
2899                    let nearest = intervals
2900                        .iter()
2901                        .min_by(|x, y| {
2902                            let dx = engine.o_difference(0.5 * (x.lo + x.hi), centre).abs();
2903                            let dy = engine.o_difference(0.5 * (y.lo + y.hi), centre).abs();
2904                            dx.total_cmp(&dy)
2905                        })
2906                        .expect("nonempty");
2907                    let shift = engine.o_difference(nearest.lo, lo[i][previous]) - (nearest.lo - lo[i][previous]);
2908                    lo[i][ku] = nearest.lo + shift;
2909                    hi[i][ku] = nearest.hi + shift;
2910                    lo_src[i][ku] = nearest.lo_source;
2911                    hi_src[i][ku] = nearest.hi_source;
2912                }
2913                k += direction;
2914            }
2915        }
2916        // Ends: the same source's value at exactly the band's end levels,
2917        // nearest the linear extrapolation of the two nearest samples.
2918        for i in 0..count {
2919            for (end, inner, inner2, inner3, level) in [(0usize, 1usize, 2usize, 3usize, a), (n, n - 1, n - 2, n - 3, b)] {
2920                // A quadratic in the sample index through the three nearest samples.
2921                // The levels cluster as σ² at the ends, so a regular end is quadratic
2922                // in σ and a √ end (a tip) linear: this is exact for both, where
2923                // `2v₁ − v₂` misses the first by the slope times a sample spacing. A
2924                // source whose domain ends at this level has no candidate there, so
2925                // the estimate IS the end value (1e-3 on the bar swung on its edge).
2926                let near = |values: &Vec<f64>| 2.0 * values[inner] - values[inner2];
2927                let quadratic = |values: &Vec<f64>| 3.0 * values[inner] - 3.0 * values[inner2] + values[inner3];
2928                lo[i][end] = end_value(engine, lo_src[i][inner], level, near(&lo[i]), quadratic(&lo[i]));
2929                hi[i][end] = end_value(engine, hi_src[i][inner], level, near(&hi[i]), quadratic(&hi[i]));
2930            }
2931        }
2932        // Accuracy: compare the fitted ends at the σ mid-points with exact values.
2933        let mut worst = 0.0f64;
2934        let mut worst_at = (0usize, 0usize, 0usize, 0.0f64, 0.0f64);
2935        for i in 0..count {
2936            for (side, values) in [&lo[i], &hi[i]].into_iter().enumerate() {
2937                let points: Vec<Vec3> = (0..=n)
2938                    .map(|k| reduced_to_plane(engine, level_at(sigma[k]), values[k]))
2939                    .collect();
2940                let curve = fit_piece(&points)?;
2941                let parameters = chord_parameters(&points);
2942                // The end spans too: an end value is read differently from the samples.
2943                for k in (1..n - 1).step_by((n / 8).max(1)).chain([0, n - 1]) {
2944                    let s = 0.5 * (sigma[k] + sigma[k + 1]);
2945                    let level = level_at(s);
2946                    let intervals = engine.intervals_at(level)?;
2947                    let guess = 0.5 * (values[k] + values[k + 1]);
2948                    let exact = intervals
2949                        .iter()
2950                        .flat_map(|x| [x.lo, x.hi])
2951                        .map(|o| guess + engine.o_difference(o, guess))
2952                        .min_by(|x, y| (x - guess).abs().total_cmp(&(y - guess).abs()))
2953                        .unwrap_or(guess);
2954                    let truth = reduced_to_plane(engine, level, exact);
2955                    let bracket = (parameters[k.saturating_sub(1)], parameters[(k + 2).min(n)]);
2956                    let off = distance_in_bracket(&curve, truth, bracket.0, bracket.1)?;
2957                    if off > worst {
2958                        worst = off;
2959                        worst_at = (i, side, k, level, exact);
2960                    }
2961                }
2962            }
2963        }
2964        if std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
2965            eprintln!("  band {a:.9}..{b:.9} n {n} worst {worst:.3e} at {worst_at:?}");
2966        }
2967        if n >= n_cap && worst > 1e-6 * engine.scale {
2968            return Err(refuse(
2969                "fit_tolerance",
2970                format!(
2971                    "a boundary piece of the band {a}..{b} stays {worst:.3e} off its envelope at {n} samples \
2972                     (interval {}, {}, sample {}, level {}, o {})",
2973                    worst_at.0,
2974                    if worst_at.1 == 0 { "lo" } else { "hi" },
2975                    worst_at.2,
2976                    worst_at.3,
2977                    worst_at.4
2978                ),
2979            ));
2980        }
2981        if worst <= 1e-8 * engine.scale || n >= n_cap {
2982            let mut pieces = Vec::new();
2983            for i in 0..count {
2984                for values in [&lo[i], &hi[i]] {
2985                    pieces.push(Piece {
2986                        points: (0..=n).map(|k| (level_at(sigma[k]), values[k])).collect(),
2987                        sigma: sigma.clone(),
2988                        level_segment: false,
2989                    });
2990                }
2991            }
2992            let bottoms = (0..count).map(|i| (lo[i][0], hi[i][0])).collect();
2993            let tops = (0..count).map(|i| (lo[i][n], hi[i][n])).collect();
2994            return Ok((pieces, bottoms, tops));
2995        }
2996        n = (n * 2).min(n_cap);
2997    }
2998}
2999
3000/// Chord-length parameters for interpolating `points`, normalised to [0, 1].
3001/// Not the sampling's own `σ`: the levels cluster at both ends of a band, which
3002/// near a tip is what keeps a √ end smooth, but at a regular end it makes the
3003/// curve's speed vanish there, and an interpolant through a zero-speed end
3004/// cusps (the screw groove's wall folded where it met the closing arc).
3005fn chord_parameters(points: &[Vec3]) -> Vec<f64> {
3006    let mut parameters = vec![0.0; points.len()];
3007    for k in 1..points.len() {
3008        parameters[k] = parameters[k - 1] + points[k].sub(points[k - 1]).length();
3009    }
3010    let total = parameters[points.len() - 1].max(1e-300);
3011    for parameter in &mut parameters {
3012        *parameter /= total;
3013    }
3014    let last = points.len() - 1;
3015    parameters[last] = 1.0;
3016    parameters
3017}
3018
3019fn fit_piece(points: &[Vec3]) -> Result<NurbsCurve, KernelRefusal> {
3020    interpolate_curve(points, 3, &chord_parameters(points)).or_refuse(KernelStage::Fragment, "piece_fit")
3021}
3022
3023/// A boundary piece in few spans: the least-squares quintic through its exact
3024/// samples `points` (`reduced`, the same in reduced coordinates), its ends
3025/// held, in the fewest spans whose curve stands within the larger of
3026/// `LEAN_FIT_TOLERANCE` of the scale and the cubic `fit_piece`'s own worst
3027/// miss of the exact envelope at every mid-point between samples (the points
3028/// `sample_band` judges the cubic at, here every one): never further from the
3029/// envelope than the cubic it replaces. Else that cubic. The knots sit at the
3030/// chord parameters of evenly spaced samples (which gather where the samples
3031/// do, by the piece's ends, its critical levels), with a ramp of them by each
3032/// end, where it turns fastest.
3033fn lean_fit_piece(engine: &Engine, reduced: &[(f64, f64)], points: &[Vec3]) -> Result<NurbsCurve, KernelRefusal> {
3034    const DEGREE: usize = 5;
3035    let last = points.len() - 1;
3036    let parameters = chord_parameters(points);
3037    let cubic = fit_piece(points)?;
3038    // The exact envelope between each two samples, at the mid-point of their
3039    // σ (the levels run a + (b − a)(1 − cos πσ)/2 along a band's piece).
3040    let (a, b) = (reduced[0].0, reduced[last].0);
3041    if (b - a).abs() <= 1e-12 * engine.scale {
3042        return Ok(cubic);
3043    }
3044    let sigma = |level: f64| (1.0 - 2.0 * (level - a) / (b - a)).clamp(-1.0, 1.0).acos() / PI;
3045    let mut truths = Vec::with_capacity(last);
3046    for k in 0..last {
3047        let s = 0.5 * (sigma(reduced[k].0) + sigma(reduced[k + 1].0));
3048        let level = a + (b - a) * (1.0 - (PI * s).cos()) / 2.0;
3049        let guess = 0.5 * (reduced[k].1 + reduced[k + 1].1);
3050        let exact = engine
3051            .intervals_at(level)?
3052            .iter()
3053            .flat_map(|x| [x.lo, x.hi])
3054            .map(|o| guess + engine.o_difference(o, guess))
3055            .min_by(|x, y| (x - guess).abs().total_cmp(&(y - guess).abs()));
3056        let Some(exact) = exact else { return Ok(cubic) };
3057        truths.push(reduced_to_plane(engine, level, exact));
3058    }
3059    let miss = |curve: &NurbsCurve| -> Result<f64, KernelRefusal> {
3060        let mut worst = 0.0f64;
3061        for (k, truth) in truths.iter().enumerate() {
3062            let bracket = (parameters[k.saturating_sub(1)], parameters[(k + 2).min(last)]);
3063            worst = worst.max(distance_in_bracket(curve, *truth, bracket.0, bracket.1)?);
3064        }
3065        Ok(worst)
3066    };
3067    let tolerance = (LEAN_FIT_TOLERANCE * engine.scale).max(miss(&cubic)?);
3068    let debug = std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok();
3069    for even in [4usize, 6, 8, 12, 16, 24, 32, 48, 64] {
3070        let mut at: Vec<usize> = (1..even).map(|k| (k * last + even / 2) / even).collect();
3071        for ramp in [1usize, 2, 4] {
3072            if 4 * ramp < last {
3073                at.extend([ramp, last - ramp]);
3074            }
3075        }
3076        at.sort_unstable();
3077        at.dedup();
3078        let spans = at.len() + 1;
3079        let count = spans + DEGREE;
3080        if 3 * count > 2 * points.len() {
3081            break;
3082        }
3083        let mut knots = vec![0.0; DEGREE + 1];
3084        knots.extend(at.iter().map(|&k| parameters[k]));
3085        knots.extend([1.0; DEGREE + 1]);
3086        if (DEGREE..DEGREE + spans).any(|k| knots[k + 1] <= knots[k]) {
3087            continue;
3088        }
3089        let Some(controls) = least_squares_controls(points, &parameters, &knots, DEGREE, count) else { continue };
3090        let Ok(curve) = NurbsCurve::new(DEGREE, knots, controls.iter().map(|p| crate::Vec4::from_point(*p, 1.0)).collect()) else {
3091            continue;
3092        };
3093        let worst = miss(&curve)?;
3094        if debug {
3095            eprintln!("  lean fit {} samples {spans} spans: worst mid-point {worst:.3e} (tolerance {tolerance:.3e})", points.len());
3096        }
3097        if worst <= tolerance {
3098            return Ok(curve);
3099        }
3100    }
3101    Ok(cubic)
3102}
3103
3104/// The B-spline basis of `degree` on `knots` at `t`: (first index, values).
3105fn bspline_basis(knots: &[f64], degree: usize, count: usize, t: f64) -> (usize, Vec<f64>) {
3106    let mut span = degree;
3107    while span + 1 < count && knots[span + 1] <= t {
3108        span += 1;
3109    }
3110    let mut values = vec![0.0; degree + 1];
3111    values[0] = 1.0;
3112    let (mut left, mut right) = (vec![0.0; degree + 1], vec![0.0; degree + 1]);
3113    for j in 1..=degree {
3114        left[j] = t - knots[span + 1 - j];
3115        right[j] = knots[span + j] - t;
3116        let mut saved = 0.0;
3117        for r in 0..j {
3118            let temp = values[r] / (right[r + 1] + left[j - r]);
3119            values[r] = saved + right[r + 1] * temp;
3120            saved = left[j - r] * temp;
3121        }
3122        values[j] = saved;
3123    }
3124    (span - degree, values)
3125}
3126
3127/// Control points of the B-spline on `knots` nearest `points` at `parameters`
3128/// in least squares, its first and last points held at the first and last
3129/// sample.
3130fn least_squares_controls(points: &[Vec3], parameters: &[f64], knots: &[f64], degree: usize, count: usize) -> Option<Vec<Vec3>> {
3131    let (first, last) = (points[0], points[points.len() - 1]);
3132    let unknowns = count - 2;
3133    let mut normal = vec![vec![0.0; unknowns]; unknowns];
3134    let mut rhs = vec![[0.0; 3]; unknowns];
3135    for (point, &t) in points.iter().zip(parameters).skip(1).take(points.len() - 2) {
3136        let (start, values) = bspline_basis(knots, degree, count, t);
3137        // What the held ends contribute here moves to the right side.
3138        let mut target = *point;
3139        for (offset, value) in values.iter().enumerate() {
3140            let index = start + offset;
3141            if index == 0 {
3142                target = target.sub(first.scale(*value));
3143            } else if index == count - 1 {
3144                target = target.sub(last.scale(*value));
3145            }
3146        }
3147        for (a, va) in values.iter().enumerate() {
3148            let row = start + a;
3149            if row == 0 || row == count - 1 {
3150                continue;
3151            }
3152            for (b, vb) in values.iter().enumerate() {
3153                let column = start + b;
3154                if column == 0 || column == count - 1 {
3155                    continue;
3156                }
3157                normal[row - 1][column - 1] += va * vb;
3158            }
3159            rhs[row - 1][0] += va * target.x;
3160            rhs[row - 1][1] += va * target.y;
3161            rhs[row - 1][2] += va * target.z;
3162        }
3163    }
3164    // Gaussian elimination with partial pivoting (symmetric positive definite, small).
3165    for column in 0..unknowns {
3166        let pivot = (column..unknowns).max_by(|a, b| normal[*a][column].abs().total_cmp(&normal[*b][column].abs()))?;
3167        if normal[pivot][column].abs() < 1e-300 {
3168            return None;
3169        }
3170        normal.swap(column, pivot);
3171        rhs.swap(column, pivot);
3172        for row in column + 1..unknowns {
3173            let factor = normal[row][column] / normal[column][column];
3174            if factor == 0.0 {
3175                continue;
3176            }
3177            for k in column..unknowns {
3178                normal[row][k] -= factor * normal[column][k];
3179            }
3180            for axis in 0..3 {
3181                rhs[row][axis] -= factor * rhs[column][axis];
3182            }
3183        }
3184    }
3185    let mut solved = vec![[0.0; 3]; unknowns];
3186    for row in (0..unknowns).rev() {
3187        for axis in 0..3 {
3188            let mut value = rhs[row][axis];
3189            for k in row + 1..unknowns {
3190                value -= normal[row][k] * solved[k][axis];
3191            }
3192            solved[row][axis] = value / normal[row][row];
3193        }
3194    }
3195    let mut controls = Vec::with_capacity(count);
3196    controls.push(first);
3197    controls.extend(solved.iter().map(|p| Vec3::new(p[0], p[1], p[2])));
3198    controls.push(last);
3199    controls.iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(controls)
3200}
3201
3202/// Distance from `target` to `curve` over the parameter bracket [a, b].
3203fn distance_in_bracket(curve: &NurbsCurve, target: Vec3, a: f64, b: f64) -> Result<f64, KernelRefusal> {
3204    let distance = |t: f64| -> Result<f64, KernelRefusal> {
3205        Ok(curve.evaluate(t).or_refuse(KernelStage::Fragment, "piece_eval")?.sub(target).length())
3206    };
3207    let ratio = 0.618_033_988_749_894_9;
3208    let (mut lo, mut hi) = (a, b);
3209    for _ in 0..80 {
3210        let c = hi - ratio * (hi - lo);
3211        let d = lo + ratio * (hi - lo);
3212        if distance(c)? < distance(d)? {
3213            hi = d;
3214        } else {
3215            lo = c;
3216        }
3217    }
3218    distance(0.5 * (lo + hi))
3219}
3220
3221/// `below Δ above` as intervals of `o` (both lists at one level).
3222fn symmetric_difference(below: &[(f64, f64)], above: &[(f64, f64)], angular: bool, tolerance: f64) -> Vec<(f64, f64)> {
3223    // Normalise to [base, base + 2π) for angular values, splitting wrapped ones.
3224    let normalise = |list: &[(f64, f64)]| -> Vec<(f64, f64)> {
3225        let mut out = Vec::new();
3226        for &(lo, hi) in list {
3227            if angular {
3228                let shift = lo.rem_euclid(TAU) - lo;
3229                let (lo, hi) = (lo + shift, hi + shift);
3230                if hi > TAU {
3231                    out.push((lo, TAU));
3232                    out.push((0.0, hi - TAU));
3233                } else {
3234                    out.push((lo, hi));
3235                }
3236            } else {
3237                out.push((lo, hi));
3238            }
3239        }
3240        out
3241    };
3242    let a = normalise(below);
3243    let b = normalise(above);
3244    let mut cuts: Vec<f64> = a.iter().chain(&b).flat_map(|&(lo, hi)| [lo, hi]).collect();
3245    cuts.sort_by(|x, y| x.total_cmp(y));
3246    cuts.dedup_by(|y, x| (*y - *x).abs() < tolerance);
3247    let inside = |list: &Vec<(f64, f64)>, x: f64| list.iter().any(|&(lo, hi)| x > lo && x < hi);
3248    let mut out: Vec<(f64, f64)> = Vec::new();
3249    for w in cuts.windows(2) {
3250        let m = 0.5 * (w[0] + w[1]);
3251        if inside(&a, m) != inside(&b, m) && w[1] - w[0] > tolerance {
3252            if let Some(last) = out.last_mut() {
3253                if (last.1 - w[0]).abs() < tolerance {
3254                    last.1 = w[1];
3255                    continue;
3256                }
3257            }
3258            out.push((w[0], w[1]));
3259        }
3260    }
3261    if angular && out.len() > 1 {
3262        let first = out[0];
3263        let last = *out.last().expect("nonempty");
3264        if first.0.abs() < tolerance && (last.1 - TAU).abs() < tolerance {
3265            out.pop();
3266            out[0] = (last.0 - TAU, first.1);
3267        }
3268    }
3269    out
3270}
3271
3272/// A reduced point on the section plane the body is built from.
3273fn reduced_to_plane(engine: &Engine, level: f64, o: f64) -> Vec3 {
3274    let clip = engine.clip;
3275    match engine.class {
3276        Class::Screw(c) => {
3277            let z = clip.axial[0];
3278            let alpha = o + z / c;
3279            engine.frame.world([level * alpha.cos(), level * alpha.sin(), z])
3280        }
3281        Class::Turn => {
3282            let theta = clip.angle.map(|a| a[0]).unwrap_or(0.0);
3283            engine.frame.world([level * theta.cos(), level * theta.sin(), o])
3284        }
3285        Class::Planar => engine.frame.world([level * o.cos(), level * o.sin(), clip.axial[0]]),
3286    }
3287}
3288
3289/// Join pieces end to end into closed loops (in the section plane).
3290fn assemble_loops(engine: &Engine, pieces: Vec<Piece>) -> Result<Vec<Vec<Piece>>, KernelRefusal> {
3291    let tolerance = 1e-6 * engine.scale;
3292    let ends: Vec<(Vec3, Vec3)> = pieces
3293        .iter()
3294        .map(|piece| {
3295            let first = piece.points[0];
3296            let last = *piece.points.last().expect("nonempty");
3297            (reduced_to_plane(engine, first.0, first.1), reduced_to_plane(engine, last.0, last.1))
3298        })
3299        .collect();
3300    let mut used = vec![false; pieces.len()];
3301    let mut orders: Vec<Vec<(usize, bool)>> = Vec::new();
3302    for start in 0..pieces.len() {
3303        if used[start] {
3304            continue;
3305        }
3306        used[start] = true;
3307        let mut order = vec![(start, false)];
3308        let origin = ends[start].0;
3309        let mut cursor = ends[start].1;
3310        let mut guard = 0;
3311        while cursor.sub(origin).length() > tolerance {
3312            guard += 1;
3313            if guard > pieces.len() {
3314                return Err(refuse("loop_open", "the section's boundary does not close".into()));
3315            }
3316            let mut next = None;
3317            let mut best = tolerance;
3318            for k in 0..pieces.len() {
3319                if used[k] {
3320                    continue;
3321                }
3322                for (reversed, end) in [(false, ends[k].0), (true, ends[k].1)] {
3323                    let d = end.sub(cursor).length();
3324                    if d < best {
3325                        best = d;
3326                        next = Some((k, reversed));
3327                    }
3328                }
3329            }
3330            let Some((k, reversed)) = next else {
3331                return Err(refuse(
3332                    "loop_open",
3333                    format!("the section's boundary does not close (a gap at {:?})", cursor),
3334                ));
3335            };
3336            used[k] = true;
3337            order.push((k, reversed));
3338            cursor = if reversed { ends[k].0 } else { ends[k].1 };
3339        }
3340        orders.push(order);
3341    }
3342    if orders.len() > 1 {
3343        // A loop inside another is a hole; not built here.
3344        let polygon = |order: &Vec<(usize, bool)>| -> Vec<Vec3> {
3345            order
3346                .iter()
3347                .flat_map(|&(k, _)| pieces[k].points.iter().map(|p| reduced_to_plane(engine, p.0, p.1)))
3348                .collect()
3349        };
3350        let polygons: Vec<Vec<Vec3>> = orders.iter().map(polygon).collect();
3351        for (i, a) in polygons.iter().enumerate() {
3352            for (j, b) in polygons.iter().enumerate() {
3353                if i != j && point_in_polygon(engine, a[0], b) {
3354                    return Err(refuse("section_hole", "the section has a hole, which is not built here".into()));
3355                }
3356            }
3357        }
3358    }
3359    let mut slots: Vec<Option<Piece>> = pieces.into_iter().map(Some).collect();
3360    Ok(orders
3361        .into_iter()
3362        .map(|order| {
3363            order
3364                .into_iter()
3365                .map(|(k, reversed)| {
3366                    let mut piece = slots[k].take().expect("each piece once");
3367                    if reversed {
3368                        piece.points.reverse();
3369                        piece.sigma = piece.sigma.iter().rev().map(|s| 1.0 - s).collect();
3370                    }
3371                    piece
3372                })
3373                .collect()
3374        })
3375        .collect())
3376}
3377
3378pub fn point_in_polygon(engine: &Engine, p: Vec3, polygon: &[Vec3]) -> bool {
3379    let local = |x: Vec3| -> [f64; 2] {
3380        let l = engine.frame.local(x);
3381        match engine.class {
3382            Class::Turn => [l[0].hypot(l[1]), l[2]],
3383            _ => [l[0], l[1]],
3384        }
3385    };
3386    let q = local(p);
3387    let mut inside = false;
3388    for k in 0..polygon.len() {
3389        let a = local(polygon[k]);
3390        let b = local(polygon[(k + 1) % polygon.len()]);
3391        if (a[1] > q[1]) != (b[1] > q[1]) {
3392            let x = a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
3393            if x > q[0] {
3394                inside = !inside;
3395            }
3396        }
3397    }
3398    inside
3399}
3400
3401/// Fit each piece and build the body for one loop.
3402fn build_body(engine: &Engine, pieces: &[Piece]) -> Result<BrepSolid, KernelRefusal> {
3403    let clip = engine.clip;
3404    let mut profile: Vec<NurbsCurve> = Vec::new();
3405    // Snap shared ends so consecutive curves meet exactly.
3406    let count = pieces.len();
3407    let mut start_points: Vec<Vec3> = pieces
3408        .iter()
3409        .map(|p| reduced_to_plane(engine, p.points[0].0, p.points[0].1))
3410        .collect();
3411    // A level segment is built exactly from its own ends, so the piece after
3412    // it starts where it ends.
3413    for (index, piece) in pieces.iter().enumerate() {
3414        if piece.level_segment && engine.class != Class::Turn {
3415            let (level, o1) = *piece.points.last().expect("nonempty");
3416            start_points[(index + 1) % count] = reduced_to_plane(engine, level, o1);
3417        }
3418    }
3419    for (index, piece) in pieces.iter().enumerate() {
3420        let start = start_points[index];
3421        let end = start_points[(index + 1) % count];
3422        if piece.level_segment {
3423            let (level, o0) = piece.points[0];
3424            let o1 = piece.points.last().expect("nonempty").1;
3425            let curve = match engine.class {
3426                Class::Turn => make_line(start, end),
3427                Class::Screw(c) => {
3428                    let shift = clip.axial[0] / c;
3429                    level_arc(engine, level, o0 + shift, o1 + shift)
3430                }
3431                Class::Planar => level_arc(engine, level, o0, o1),
3432            }
3433            .or_refuse(KernelStage::Fragment, "level_segment")?;
3434            profile.push(curve);
3435            continue;
3436        }
3437        let mut points: Vec<Vec3> = piece
3438            .points
3439            .iter()
3440            .map(|p| reduced_to_plane(engine, p.0, p.1))
3441            .collect();
3442        points[0] = start;
3443        let last = points.len() - 1;
3444        points[last] = end;
3445        profile.push(if lean_walls_on() && matches!(engine.class, Class::Screw(_)) {
3446            lean_fit_piece(engine, &piece.points, &points)?
3447        } else {
3448            fit_piece(&points)?
3449        });
3450    }
3451    match engine.class {
3452        Class::Screw(c) => {
3453            let span = (clip.axial[1] - clip.axial[0]) / c; // radians of screw
3454            // Over a crest the walls are re-carried below to high order, so 12 a turn is enough.
3455            // A bar's walls are carried to high order too: a cubic through 64
3456            // sections a turn stands r·h⁴/384 off the screw (1e-6 at a groove's
3457            // floor), the quintic through 48 below 1e-9.
3458            let carried = engine.crest_gap || engine.bar.is_some() || screw_carry_on();
3459            let per_turn = if engine.crest_gap {
3460                12.0
3461            } else if carried && lean_walls_on() {
3462                LEAN_CARRY_PER_TURN
3463            } else if carried {
3464                48.0
3465            } else {
3466                64.0
3467            };
3468            // Every turn is the screw image of the first: build one and stack
3469            // copies, so no surface or edge runs the thread's whole length.
3470            let rows = if carried && thread_rows_on() { (span.abs() / TAU / TURNS_PER_ROW).round().max(1.0) as usize } else { 1 };
3471            let span = span / rows as f64;
3472            let sections = ((span.abs() / TAU * per_turn).ceil() as usize).max(8) + 1;
3473            let mut lofted = Vec::with_capacity(sections);
3474            for k in 0..sections {
3475                let angle = span * k as f64 / (sections - 1) as f64;
3476                let lift = engine.frame.ez.scale(c * angle);
3477                let moved: Vec<NurbsCurve> = profile
3478                    .iter()
3479                    .map(|curve| transform_curve(curve, |x| rotate(x, clip.axis_origin, engine.frame.ez, angle).add(lift)))
3480                    .collect::<Result<_, _>>()?;
3481                lofted.push(moved);
3482            }
3483            let mut body = loft_profile_brep(&lofted)?;
3484            if carried {
3485                carry_along_screw(&mut body, engine, c, span, sections - 1)?;
3486            }
3487            if rows > 1 {
3488                body = stack_screw_rows(&body, engine, c, span, sections - 1, rows)?;
3489            }
3490            Ok(body)
3491        }
3492        Class::Turn => {
3493            let angle = clip.angle.map(|a| a[1] - a[0]).unwrap_or(TAU);
3494            revolve_profile_brep(&profile, clip.axis_origin, engine.frame.ez, angle)
3495                .or_refuse(KernelStage::Fragment, "revolve")
3496        }
3497        Class::Planar => extrude_profile_brep(&profile, engine.frame.ez, clip.axial[1] - clip.axial[0]),
3498    }
3499}
3500
3501fn level_arc(engine: &Engine, level: f64, a0: f64, a1: f64) -> Result<NurbsCurve, String> {
3502    let centre = engine.frame.world([0.0, 0.0, match engine.class {
3503        Class::Screw(_) | Class::Planar => engine.clip.axial[0],
3504        Class::Turn => 0.0,
3505    }]);
3506    let (start, end) = if a1 >= a0 { (a0, a1) } else { (a1, a0) };
3507    let arc = make_arc(centre, engine.frame.ex, engine.frame.ey, level, start, end)?;
3508    if a1 >= a0 {
3509        Ok(arc)
3510    } else {
3511        arc.reversed()
3512    }
3513}
3514
3515fn transform_curve(curve: &NurbsCurve, map: impl Fn(Vec3) -> Vec3) -> Result<NurbsCurve, KernelRefusal> {
3516    let control_points = curve
3517        .control_points
3518        .iter()
3519        .map(|p| {
3520            let w = p.w;
3521            let x = map(Vec3::new(p.x / w, p.y / w, p.z / w));
3522            crate::Vec4 { x: x.x * w, y: x.y * w, z: x.z * w, w }
3523        })
3524        .collect();
3525    NurbsCurve::new(curve.degree, curve.knots.clone(), control_points).or_refuse(KernelStage::Fragment, "curve_new")
3526}
3527
3528/// Refuse a screw or turn whose first or last position reaches the clip.
3529fn check_ends_clear(engine: &Engine) -> Result<(), KernelRefusal> {
3530    let clip = engine.clip;
3531    // Tool boundary samples at its own place (clip frame).
3532    let mut samples: Vec<[f64; 3]> = Vec::new();
3533    for (index, source) in engine.sources.iter().enumerate() {
3534        if let Some(grid) = &engine.grids[index] {
3535            for i in 0..grid.nu {
3536                for j in 0..grid.nv {
3537                    let (u, v) = Engine::grid_param(grid, i, j);
3538                    samples.push(engine.frame.local(engine.source_point(*source, u, v)));
3539                }
3540            }
3541        }
3542    }
3543    let margin = 1e-6 * engine.scale;
3544    for t in [engine.motion.from, engine.motion.to] {
3545        for p in &samples {
3546            let x = engine.frame.local(engine.motion_apply(t, engine.frame.world(*p)));
3547            let level = x[0].hypot(x[1]);
3548            if level > clip.radius[1] + margin || level < clip.radius[0] - margin {
3549                continue;
3550            }
3551            if x[2] < clip.axial[0] - margin || x[2] > clip.axial[1] + margin {
3552                continue;
3553            }
3554            if let Some([a0, a1]) = clip.angle {
3555                let angle = x[1].atan2(x[0]);
3556                let mid = 0.5 * (a0 + a1);
3557                let rel = wrap_pi(angle - mid);
3558                if rel.abs() > 0.5 * (a1 - a0) + 1e-9 {
3559                    continue;
3560                }
3561            }
3562            return Err(refuse(
3563                "ends_reach_clip",
3564                format!(
3565                    "the tool reaches the clip region at the motion's {} (t = {t}); the sweep is \
3566                     not invariant there, so the region would be wrong",
3567                    if t == engine.motion.from { "start" } else { "end" }
3568                ),
3569            ));
3570        }
3571    }
3572    Ok(())
3573}
3574