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