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