Skip to main content

brep_construction/construction/
solid_sweep_upright.rs

1//! An upright solid of revolution carried along a planar cubic (the riding
2//! frame's `up` along the tool's axis, the curve in a plane square to it).
3//!
4//! Turned about `up` by the frame, the tool is unchanged (it is turned about
5//! its own axis), so the motion is a translation along the curve, and what the
6//! tool passes through is exactly
7//!
8//! ```text
9//! S = { p : the planar distance from p to the curve <= radius(h) },
10//! ```
11//!
12//! `h` the height of `p` above the curve's plane and `radius(h)` the tool's
13//! radius there (its section at `h` is a disc about the axis). The motion's
14//! frame turning, the curve's loops and its turns tighter than the tool, which
15//! fold a swept wall, are all one read: the planar distance to the curve.
16//!
17//! This module holds that read: the gate ([`upright_slot`]), the distance
18//! ([`UprightSlot::distance`]), membership ([`UprightSlot::contains`]), the
19//! level outlines of the planar strokes `{ d <= rho }`
20//! ([`UprightSlot::level_loops`]) and the swept volume they integrate to
21//! ([`UprightSlot::volume`]), the referee of the solid built from them.
22
23use crate::{FrameCurve, OutlinePiece, SolidTool, Vec3};
24
25/// The envelope the reads hold in, checked by the gate before any arithmetic:
26/// the tool's height within `ENVELOPE` of its widest radius either way, the
27/// curve's extent within `ENVELOPE` of that radius, all three between 1e-60
28/// and 1e60, every arc's radius within `ENVELOPE` of the tool's, the curve regular (its
29/// speed nowhere below 1e-4 of its control polygon's, so its feet are read
30/// to the last bits), and every meridian arc at most one turn. Outside it the
31/// gate declines (the general sweep answers).
32pub const ENVELOPE: f64 = 1e6;
33
34/// The switch for the upright route in [`crate::sweep_solid_along`] (default
35/// off until promoted).
36pub fn upright_slot_on() -> bool {
37    crate::switch!("BREP_SWEEP_UPRIGHT_SLOT", false)
38}
39
40/// What an upright solid of revolution passes through carried along a planar
41/// cubic ([`UprightSlot::solid`]), or `None` where the tool and the curve are
42/// not of this class ([`upright_slot`]). Whatever the switch: the call a
43/// caller makes for this class by name.
44pub fn sweep_upright_along(tool: &SolidTool, path: &FrameCurve) -> Option<Result<crate::BrepSolid, crate::KernelRefusal>> {
45    upright_slot(tool, path).map(|slot| slot.solid())
46}
47
48/// An upright revolved tool's sweep along a planar cubic, in the curve's
49/// plane: the cubic's controls in plane coordinates and the tool's radius as
50/// a function of height above the plane (its meridian). Its reads rely on the
51/// envelope [`upright_slot`] checks: build one through it (a slot assembled
52/// by hand outside the envelope reads no further than its budgets allow).
53#[derive(Clone, Debug)]
54pub struct UprightSlot {
55    /// The plane's origin (the curve's start) and its axes; `up` is its normal.
56    pub origin: Vec3,
57    pub x: Vec3,
58    pub y: Vec3,
59    pub up: Vec3,
60    /// The cubic's controls in (x, y).
61    pub curve: [[f64; 2]; 4],
62    /// The meridian in (radius, height above the plane).
63    pub meridian: Vec<OutlinePiece>,
64    /// The tool's height range above the plane.
65    pub heights: [f64; 2],
66}
67
68/// The angles `a + 2πk` inside [lo, hi] (any number of turns).
69fn turns_within(a: f64, lo: f64, hi: f64) -> impl Iterator<Item = f64> {
70    let tau = std::f64::consts::TAU;
71    let (first, last) = (((lo - a) / tau).ceil(), ((hi - a) / tau).floor());
72    let count = if first.is_finite() && last.is_finite() && last >= first && last - first < 1e6 { (last - first) as i64 + 1 } else { 0 };
73    (0..count).map(move |k| a + tau * (first + k as f64))
74}
75
76/// A meridian piece's greatest |radius| and |height| over its own extent (an
77/// arc over its angles, not its whole circle). Ellipses read as unbounded.
78fn piece_extent(piece: &OutlinePiece) -> (f64, f64) {
79    match *piece {
80        OutlinePiece::Line { from, to } => (from[0].abs().max(to[0].abs()), from[1].abs().max(to[1].abs())),
81        OutlinePiece::Arc { centre, radius, start, end } => {
82            let (a, b) = (start.min(end), start.max(end));
83            let at = |t: f64| [centre[0] + radius * t.cos(), centre[1] + radius * t.sin()];
84            let mut points = vec![at(start), at(end)];
85            for k in [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, -std::f64::consts::FRAC_PI_2] {
86                points.extend(turns_within(k, a, b).take(1).map(at));
87            }
88            points.iter().fold((0.0f64, 0.0f64), |(r, h), p| (r.max(p[0].abs()), h.max(p[1].abs())))
89        }
90        OutlinePiece::Ellipse { .. } => (f64::INFINITY, f64::INFINITY),
91    }
92}
93
94fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
95    [a[0] - b[0], a[1] - b[1]]
96}
97
98fn dot(a: [f64; 2], b: [f64; 2]) -> f64 {
99    a[0] * b[0] + a[1] * b[1]
100}
101
102/// The sweep of `tool` along `path` when it is of this class: a solid of
103/// revolution whose axis lies along `up` through the curve's start, the curve
104/// in the plane square to `up` there, and every section of the tool square to
105/// its axis a disc about it (its meridian a radius per height). `None`
106/// otherwise.
107pub fn upright_slot(tool: &SolidTool, path: &FrameCurve) -> Option<UprightSlot> {
108    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else { return None };
109    let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
110    let pieces_finite = meridian.iter().all(|piece| match *piece {
111        OutlinePiece::Line { from, to } => from.iter().chain(&to).all(|x| x.is_finite()),
112        OutlinePiece::Arc { centre, radius, start, end } => centre.iter().all(|x| x.is_finite()) && radius.is_finite() && start.is_finite() && end.is_finite(),
113        OutlinePiece::Ellipse { .. } => false,
114    });
115    if !(pieces_finite && path.control.iter().all(|p| finite(*p)) && finite(path.up) && finite(*axis_origin) && finite(*axis_direction) && finite(*radial)) {
116        return None;
117    }
118    // Unit directions read without overflow (scaled by the largest component first).
119    let unit = |d: Vec3| -> Option<Vec3> {
120        let big = d.x.abs().max(d.y.abs()).max(d.z.abs());
121        if !(big > 0.0 && big.is_finite()) {
122            return None;
123        }
124        let n = d.scale(1.0 / big).normalized().ok()?;
125        ((n.length() - 1.0).abs() <= 1e-12).then_some(n)
126    };
127    let up = unit(path.up)?;
128    let axis = unit(*axis_direction)?;
129    let along = axis.dot(up).signum();
130    let start = path.control[0];
131    // Every tolerance a displacement in the tool's own widest radius: the
132    // axis's sideways offset, its drift over the tool's height (its tilt), and
133    // the curve's rise off its plane over its whole run.
134    let (widest, tall) = meridian.iter().map(piece_extent).fold((0.0f64, 0.0f64), |(r, h), (pr, ph)| (r.max(pr), h.max(ph)));
135    if !(widest > 0.0 && widest.is_finite() && tall.is_finite()) {
136        return None;
137    }
138    // Arcs no wider than the envelope allows (a sliver of a huge circle reads
139    // its crossings no finer than its radius).
140    if meridian.iter().any(|piece| matches!(*piece, OutlinePiece::Arc { radius, .. } if !(radius > 0.0 && radius <= ENVELOPE * widest))) {
141        return None;
142    }
143    // The envelope (see `ENVELOPE`).
144    let extent = path.control.iter().map(|p| p.sub(start).length()).fold(0.0f64, f64::max);
145    let one_turn = meridian.iter().all(|piece| match *piece {
146        OutlinePiece::Arc { start, end, .. } => (end - start).abs() <= std::f64::consts::TAU * (1.0 + 1e-12),
147        _ => true,
148    });
149    // And sizes whose products stay in range (the quintic's coefficients
150    // are fourth powers of the curve's extent).
151    let sized = |x: f64| (1e-60..=1e60).contains(&x);
152    if !(one_turn && sized(widest) && sized(extent) && sized(tall.max(widest)) && tall <= ENVELOPE * widest && tall >= widest / ENVELOPE && extent <= ENVELOPE * widest && extent >= widest / ENVELOPE) {
153        return None;
154    }
155    let band = 1e-12 * widest;
156    if axis.cross(up).length() * tall.max(widest) > band {
157        return None;
158    }
159    // The axis through the curve's start, the curve in the plane square to up.
160    let off = axis_origin.sub(start);
161    if off.sub(up.scale(off.dot(up))).length() > band {
162        return None;
163    }
164    if path.control.iter().any(|p| p.sub(start).dot(up).abs() > band) {
165        return None;
166    }
167    // The radial direction square to the axis (it only names the meridian's
168    // first coordinate; the tool is turned about the axis whatever it is).
169    let radial_unit = unit(*radial)?;
170    if radial_unit.dot(axis).abs() > 1e-12 {
171        return None;
172    }
173    // A curve with somewhere to go: its controls not all at its start.
174    if path.control.iter().all(|p| p.sub(start).length() <= band) {
175        return None;
176    }
177    let lift = off.dot(up);
178    let meridian: Vec<OutlinePiece> = meridian
179        .iter()
180        .map(|piece| match *piece {
181            OutlinePiece::Line { from, to } => Some(OutlinePiece::Line { from: [from[0], lift + along * from[1]], to: [to[0], lift + along * to[1]] }),
182            OutlinePiece::Arc { centre, radius, start, end } => {
183                // Reflected in the height when the axis runs down: angles negate.
184                if along > 0.0 {
185                    Some(OutlinePiece::Arc { centre: [centre[0], lift + centre[1]], radius, start, end })
186                } else {
187                    Some(OutlinePiece::Arc { centre: [centre[0], lift - centre[1]], radius, start: -start, end: -end })
188                }
189            }
190            OutlinePiece::Ellipse { .. } => None,
191        })
192        .collect::<Option<_>>()?;
193    let tangent = path.control[1].sub(start);
194    let x = tangent.sub(up.scale(tangent.dot(up))).normalized().or_else(|_| up.perpendicular()).ok()?;
195    let y = up.cross(x);
196    let flat = |p: Vec3| [p.sub(start).dot(x), p.sub(start).dot(y)];
197    let mut slot = UprightSlot { origin: start, x, y, up, curve: path.control.map(flat), meridian, heights: [0.0; 2] };
198    if !slot.regular() {
199        return None;
200    }
201    // The height range, and a disc at every height: the meridian crosses each
202    // level line once off the axis.
203    let ends = slot.meridian.iter().flat_map(|piece| match *piece {
204        OutlinePiece::Line { from, to } => vec![from[1], to[1]],
205        OutlinePiece::Arc { centre, radius, start, end } => {
206            let mut hs = vec![centre[1] + radius * start.sin(), centre[1] + radius * end.sin()];
207            for a in turns_within(std::f64::consts::FRAC_PI_2, start.min(end), start.max(end)).chain(turns_within(-std::f64::consts::FRAC_PI_2, start.min(end), start.max(end))) {
208                hs.push(centre[1] + radius * a.sin());
209            }
210            hs
211        }
212        OutlinePiece::Ellipse { .. } => vec![],
213    });
214    let (low, high) = ends.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), h| (lo.min(h), hi.max(h)));
215    if !(high > low) {
216        return None;
217    }
218    slot.heights = [low, high];
219    if !slot.sections_are_discs() {
220        return None;
221    }
222    Some(slot)
223}
224
225impl UprightSlot {
226    /// Whether every section of the tool square to its axis is a disc about
227    /// it, read off the meridian's pieces (not sampled): one piece runs along
228    /// the axis over the whole height range, and the others chain from its
229    /// bottom end to its top end with the height never turning back along the
230    /// chain (a line's height monotone, an arc holding no vertical tangent
231    /// inside it), so each level line meets the chain once.
232    fn sections_are_discs(&self) -> bool {
233        let [low, high] = self.heights;
234        // Heights in the tool's height, radii in its widest radius.
235        let tol = 1e-12 * (high - low).abs().max(1e-300);
236        let tol_r = 1e-12 * self.widest().max(1e-300);
237        let ends = |piece: &OutlinePiece| -> Option<([f64; 2], [f64; 2])> {
238            match *piece {
239                OutlinePiece::Line { from, to } => Some((from, to)),
240                OutlinePiece::Arc { centre, radius, start, end } => Some((
241                    [centre[0] + radius * start.cos(), centre[1] + radius * start.sin()],
242                    [centre[0] + radius * end.cos(), centre[1] + radius * end.sin()],
243                )),
244                OutlinePiece::Ellipse { .. } => None,
245            }
246        };
247        let on_axis = |p: [f64; 2]| p[0].abs() <= tol_r;
248        let axis_piece = |piece: &OutlinePiece| matches!(*piece, OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to) && (from[1] - to[1]).abs() >= high - low - tol);
249        let Some(axis_index) = self.meridian.iter().position(axis_piece) else { return false };
250        // The chain: the pieces after the axis piece, in order, from its end round to its start.
251        let n = self.meridian.len();
252        let chain: Vec<&OutlinePiece> = (1..n).map(|k| &self.meridian[(axis_index + k) % n]).collect();
253        let Some((first, _)) = chain.first().and_then(|p| ends(p)) else { return false };
254        let Some((_, last)) = chain.last().and_then(|p| ends(p)) else { return false };
255        // The chain closes the meridian: from the axis piece's end back to its start.
256        let Some((axis_from, axis_to)) = ends(&self.meridian[axis_index]) else { return false };
257        let same = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() <= tol_r && (a[1] - b[1]).abs() <= tol;
258        if !(same(first, axis_to) && same(last, axis_from)) {
259            return false;
260        }
261        // Rising or falling along the whole chain, the same way throughout.
262        let rising = last[1] > first[1];
263        let mut previous = first;
264        let last_index = chain.len() - 1;
265        for (index, piece) in chain.iter().enumerate() {
266            let Some((from, to)) = ends(piece) else { return false };
267            if (from[0] - previous[0]).abs() > tol_r || (from[1] - previous[1]).abs() > tol {
268                return false;
269            }
270            let monotone = match **piece {
271                // A flat line may only run along an end (the chain's first or
272                // last piece at the bottom or the top height).
273                OutlinePiece::Line { from, to } => {
274                    let dh = to[1] - from[1];
275                    // Flat to the tool's radius scale (a tall tool's height
276                    // tolerance would pass a slanted floor as flat).
277                    if dh.abs() <= tol_r.min(tol) {
278                        // Only the chain's first or last piece, along an end.
279                        (index == 0 || index == last_index) && ((from[1] - low).abs() <= tol || (from[1] - high).abs() <= tol)
280                    } else {
281                        (dh > 0.0) == rising
282                    }
283                }
284                OutlinePiece::Arc { radius, start, end, .. } => {
285                    // dh/dθ = r cos θ keeps one sign over the arc's interior.
286                    let (a, b) = (start.min(end), start.max(end));
287                    let inner = 1e-12 * (b - a).abs().max(1.0);
288                    let turns = turns_within(std::f64::consts::FRAC_PI_2, a + inner, b - inner)
289                        .chain(turns_within(-std::f64::consts::FRAC_PI_2, a + inner, b - inner))
290                        .next()
291                        .is_some();
292                    !turns && radius > 0.0 && ((to[1] - from[1] > 0.0) == rising || (to[1] - from[1]).abs() <= tol)
293                }
294                OutlinePiece::Ellipse { .. } => false,
295            };
296            if !monotone {
297                return false;
298            }
299            // Off the axis between the chain's ends (a chain touching the axis
300            // in its middle makes two solids meeting at a point).
301            if index != last_index && on_axis(to) {
302                return false;
303            }
304            // Nor anywhere inside a piece: a line's radius is never negative at
305            // its ends (so it stays off the axis between off-axis ends); an arc's
306            // least radius, where it faces the axis (θ = π + 2πk inside it),
307            // stays off the axis.
308            let off = match **piece {
309                OutlinePiece::Line { from, to } => from[0] >= -tol_r && to[0] >= -tol_r,
310                OutlinePiece::Arc { centre, radius, start, end } => {
311                    let (a, b) = (start.min(end), start.max(end));
312                    let inner = 1e-12 * (b - a).abs().max(1.0);
313                    // Its ends in the half-plane, and where it faces the axis
314                    // inside, its least radius off the axis.
315                    let ends_in = centre[0] + radius * start.cos() >= -tol_r && centre[0] + radius * end.cos() >= -tol_r;
316                    ends_in && (turns_within(std::f64::consts::PI, a + inner, b - inner).next().is_none() || centre[0] - radius > tol_r)
317                }
318                OutlinePiece::Ellipse { .. } => false,
319            };
320            if !off {
321                return false;
322            }
323            previous = to;
324        }
325        true
326    }
327
328    /// Whether the curve's speed stays above 1e-4 of its control polygon's
329    /// (the envelope): the least of |B'|² over [0, 1], read at the ends and at
330    /// every root of its derivative (a cubic) bracketed on 256 spans.
331    fn regular(&self) -> bool {
332        let c = &self.curve;
333        let polygon = (0..3).map(|k| sub(c[k + 1], c[k])).map(|d| 3.0 * dot(d, d).sqrt()).fold(0.0f64, f64::max);
334        if !(polygon > 0.0) {
335            return false;
336        }
337        let speed2 = |t: f64| {
338            let d = self.derivative(t);
339            dot(d, d)
340        };
341        let slope = |t: f64| dot(self.derivative(t), self.second(t));
342        let mut least = speed2(0.0).min(speed2(1.0));
343        let n = 256;
344        let mut previous = slope(0.0);
345        for k in 1..=n {
346            let t1 = k as f64 / n as f64;
347            let current = slope(t1);
348            if (previous < 0.0) != (current < 0.0) {
349                let (mut a, mut b, mut sa) = ((k - 1) as f64 / n as f64, t1, previous);
350                for _ in 0..100 {
351                    let m = 0.5 * (a + b);
352                    let sm = slope(m);
353                    if (sm < 0.0) == (sa < 0.0) {
354                        a = m;
355                        sa = sm;
356                    } else {
357                        b = m;
358                    }
359                }
360                least = least.min(speed2(0.5 * (a + b)));
361            }
362            previous = current;
363        }
364        least.sqrt() >= 1e-4 * polygon
365    }
366
367    /// The meridian's crossings with the level line at `h`, off the axis.
368    fn crossings(&self, h: f64) -> Vec<f64> {
369        let mut found: Vec<f64> = Vec::new();
370        for piece in &self.meridian {
371            match *piece {
372                OutlinePiece::Line { from, to } => {
373                    let (a, b) = (from[1] - h, to[1] - h);
374                    if a == 0.0 && b == 0.0 {
375                        continue;
376                    }
377                    if (a <= 0.0 && b >= 0.0) || (a >= 0.0 && b <= 0.0) {
378                        let s = a / (a - b);
379                        found.push(from[0] + s * (to[0] - from[0]));
380                    }
381                }
382                OutlinePiece::Arc { centre, radius, start, end } => {
383                    let s = (h - centre[1]) / radius;
384                    if s.abs() > 1.0 {
385                        continue;
386                    }
387                    let base = s.asin();
388                    for a in [base, std::f64::consts::PI - base] {
389                        for angle in turns_within(a, start.min(end), start.max(end)) {
390                            found.push(centre[0] + radius * angle.cos());
391                        }
392                    }
393                }
394                OutlinePiece::Ellipse { .. } => {}
395            }
396        }
397        // Off the axis, in the tool's own size.
398        let widest = found.iter().fold(0.0f64, |m, r| m.max(r.abs()));
399        let floor = 1e-12 * widest;
400        let mut off: Vec<f64> = found.into_iter().filter(|r| *r > floor).collect();
401        off.sort_by(f64::total_cmp);
402        off.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * a.abs());
403        off
404    }
405
406    /// The tool's radius at height `h` above the plane (0 outside its range).
407    pub fn radius(&self, h: f64) -> f64 {
408        if !(h >= self.heights[0] && h <= self.heights[1]) {
409            return 0.0;
410        }
411        self.crossings(h).last().copied().unwrap_or(0.0)
412    }
413
414    fn point(&self, t: f64) -> [f64; 2] {
415        let c = &self.curve;
416        let s = 1.0 - t;
417        let w = [s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t];
418        [(0..4).map(|k| w[k] * c[k][0]).sum(), (0..4).map(|k| w[k] * c[k][1]).sum()]
419    }
420
421    fn derivative(&self, t: f64) -> [f64; 2] {
422        let c = &self.curve;
423        let s = 1.0 - t;
424        let w = [3.0 * s * s, 6.0 * s * t, 3.0 * t * t];
425        let d = [sub(c[1], c[0]), sub(c[2], c[1]), sub(c[3], c[2])];
426        [(0..3).map(|k| w[k] * d[k][0]).sum(), (0..3).map(|k| w[k] * d[k][1]).sum()]
427    }
428
429    fn second(&self, t: f64) -> [f64; 2] {
430        let c = &self.curve;
431        let a = [c[2][0] - 2.0 * c[1][0] + c[0][0], c[2][1] - 2.0 * c[1][1] + c[0][1]];
432        let b = [c[3][0] - 2.0 * c[2][0] + c[1][0], c[3][1] - 2.0 * c[2][1] + c[1][1]];
433        [6.0 * ((1.0 - t) * a[0] + t * b[0]), 6.0 * ((1.0 - t) * a[1] + t * b[1])]
434    }
435
436    /// The planar distance from `q` (plane coordinates) to the curve and the
437    /// foot's parameter: the least over the ends and every root in [0, 1] of
438    /// the stationarity `g(t) = (B(t) − q)·B'(t)`, a quintic, every root
439    /// isolated by subdividing its Bernstein form (a span whose coefficients
440    /// keep one sign holds none; one sign change, exactly one, bisected to
441    /// the last bit; spans that halve to nothing still undecided, a double
442    /// root, read at their middle).
443    pub fn distance(&self, q: [f64; 2]) -> (f64, f64) {
444        let at = |t: f64| {
445            let r = sub(self.point(t), q);
446            dot(r, r)
447        };
448        let mut best = (at(0.0), 0.0);
449        let end = at(1.0);
450        if end < best.0 {
451            best = (end, 1.0);
452        }
453        for t in self.stationary(q) {
454            let d2 = at(t);
455            if d2 < best.0 {
456                best = (d2, t);
457            }
458        }
459        (best.0.sqrt(), best.1)
460    }
461
462    /// Every root in [0, 1] of `g(t) = (B(t) − q)·B'(t)` (see [`Self::distance`]).
463    fn stationary(&self, q: [f64; 2]) -> Vec<f64> {
464        // Power coefficients of B − q and B', per coordinate.
465        let c = &self.curve;
466        let mut g = [0.0f64; 6];
467        for k in 0..2 {
468            let (p0, p1, p2, p3) = (c[0][k], c[1][k], c[2][k], c[3][k]);
469            let a = [p0 - q[k], 3.0 * (p1 - p0), 3.0 * (p2 - 2.0 * p1 + p0), p3 - 3.0 * p2 + 3.0 * p1 - p0];
470            let d = [a[1], 2.0 * a[2], 3.0 * a[3]];
471            for i in 0..4 {
472                for j in 0..3 {
473                    g[i + j] += a[i] * d[j];
474                }
475            }
476        }
477        // To the Bernstein basis of degree 5: b_k = Σ_{i ≤ k} C(k, i) / C(5, i) · g_i.
478        let choose = |n: usize, r: usize| -> f64 { (0..r).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64) };
479        let mut bern = [0.0f64; 6];
480        for k in 0..6 {
481            bern[k] = (0..=k).map(|i| choose(k, i) / choose(5, i) * g[i]).sum();
482        }
483        let value = |t: f64| g.iter().rev().fold(0.0, |acc, &x| acc * t + x);
484        // A stationarity that vanishes everywhere (a curve standing still) has
485        // no roots to isolate; the ends answer.
486        let size = bern.iter().fold(0.0f64, |m, b| m.max(b.abs()));
487        if !(size > 0.0 && size.is_finite()) {
488            return Vec::new();
489        }
490        let mut roots = Vec::new();
491        let mut spans = 0usize;
492        let mut stack: Vec<([f64; 6], f64, f64, u32)> = vec![(bern, 0.0, 1.0, 0)];
493        while let Some((b, lo, hi, depth)) = stack.pop() {
494            // A quintic has at most five roots; a few hundred spans isolate them.
495            spans += 1;
496            if spans > 4096 {
497                roots.push(0.5 * (lo + hi));
498                continue;
499            }
500            let changes = (0..5).filter(|&i| (b[i] < 0.0) != (b[i + 1] < 0.0) || b[i] == 0.0).count() + usize::from(b[5] == 0.0);
501            if changes == 0 {
502                continue;
503            }
504            let (glo, ghi) = (value(lo), value(hi));
505            if changes == 1 && (glo < 0.0) != (ghi < 0.0) {
506                // One root: bisect it to the last bit.
507                let (mut a, mut z, mut ga) = (lo, hi, glo);
508                for _ in 0..200 {
509                    let m = 0.5 * (a + z);
510                    if m <= a || m >= z {
511                        break;
512                    }
513                    let gm = value(m);
514                    if gm == 0.0 {
515                        a = m;
516                        z = m;
517                        break;
518                    }
519                    if (gm < 0.0) == (ga < 0.0) {
520                        a = m;
521                        ga = gm;
522                    } else {
523                        z = m;
524                    }
525                }
526                // Polished on the stable form: (B(t) − q)·B'(t) by de
527                // Casteljau, not the power coefficients (which cancel).
528                let mut t = 0.5 * (a + z);
529                for _ in 0..4 {
530                    let r = sub(self.point(t), q);
531                    let d = self.derivative(t);
532                    let slope = dot(d, d) + dot(r, self.second(t));
533                    if !(slope != 0.0 && slope.is_finite()) {
534                        break;
535                    }
536                    let next = t - dot(r, d) / slope;
537                    if !(next >= lo && next <= hi) {
538                        break;
539                    }
540                    t = next;
541                }
542                roots.push(t);
543                continue;
544            }
545            if depth >= 60 || hi - lo <= 1e-15 {
546                // Undecided to the last bit (a focal point's double root).
547                roots.push(0.5 * (lo + hi));
548                continue;
549            }
550            // De Casteljau at the middle.
551            let mut left = [0.0f64; 6];
552            let mut right = [0.0f64; 6];
553            let mut work = b;
554            for level in 0..6 {
555                left[level] = work[0];
556                right[5 - level] = work[5 - level];
557                for i in 0..5 - level {
558                    work[i] = 0.5 * (work[i] + work[i + 1]);
559                }
560            }
561            let mid = 0.5 * (lo + hi);
562            stack.push((right, mid, hi, depth + 1));
563            stack.push((left, lo, mid, depth + 1));
564        }
565        roots
566    }
567
568    /// Whether the tool passes through `p`: its planar distance to the curve
569    /// within the tool's radius at its height.
570    pub fn contains(&self, p: Vec3) -> bool {
571        let r = p.sub(self.origin);
572        let h = r.dot(self.up);
573        if !(h >= self.heights[0] && h <= self.heights[1]) {
574            return false;
575        }
576        // A zero radius (an apex on the axis) holds the curve itself.
577        self.distance([r.dot(self.x), r.dot(self.y)]).0 <= self.radius(h)
578    }
579
580    /// The outlines of the planar stroke `{ d <= rho }`: closed loops of
581    /// points on its boundary, each exactly at distance `rho` (bisected on a
582    /// grid of `cell`, to 1e-13 of the cell), the outer ones counter-clockwise
583    /// and the holes clockwise (marching squares, a saddle resolved by its
584    /// cell's middle). They resolve the stroke's features larger than a cell:
585    /// a hole or a neck narrower than one may be missed, which moves the area
586    /// by less than a cell's square (inside its stated O(cell²) error). The
587    /// solid's topology is not read from them.
588    pub fn level_loops(&self, rho: f64, cell: f64) -> Vec<Vec<[f64; 2]>> {
589        if !(cell > 0.0 && cell.is_finite() && rho >= 0.0 && rho.is_finite()) {
590            return Vec::new();
591        }
592        let (lo, hi) = self.curve.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), c| {
593            ([lo[0].min(c[0]), lo[1].min(c[1])], [hi[0].max(c[0]), hi[1].max(c[1])])
594        });
595        let pad = rho + 2.0 * cell;
596        let (x0, y0) = (lo[0] - pad, lo[1] - pad);
597        let (wx, wy) = (((hi[0] - lo[0] + 2.0 * pad) / cell).ceil(), ((hi[1] - lo[1] + 2.0 * pad) / cell).ceil());
598        // A grid of at most 1e8 nodes, else no outline.
599        if !(wx.is_finite() && wy.is_finite() && (wx + 1.0) * (wy + 1.0) <= 1e8) {
600            return Vec::new();
601        }
602        let (nx, ny) = (wx as usize + 1, wy as usize + 1);
603        let node = |i: usize, j: usize| [x0 + cell * i as f64, y0 + cell * j as f64];
604        let f = |p: [f64; 2]| self.distance(p).0 - rho;
605        let values: Vec<f64> = (0..ny).flat_map(|j| (0..nx).map(move |i| (i, j))).map(|(i, j)| f(node(i, j))).collect();
606        let value = |i: usize, j: usize| values[j * nx + i];
607        // The level point on the grid edge between two nodes (inside first).
608        let crossing = |a: [f64; 2], b: [f64; 2]| -> [f64; 2] {
609            let (mut fa, mut lo, mut hi) = (f(a), 0.0f64, 1.0f64);
610            for _ in 0..60 {
611                let m = 0.5 * (lo + hi);
612                let fm = f([a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m]);
613                if (fm <= 0.0) == (fa <= 0.0) {
614                    lo = m;
615                    fa = fm;
616                } else {
617                    hi = m;
618                }
619            }
620            let m = 0.5 * (lo + hi);
621            [a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m]
622        };
623        // Edges keyed by (cell edge id): horizontal (i, j)->(i+1, j) as 2*(j*nx+i), vertical as +1.
624        let h_edge = |i: usize, j: usize| 2 * (j * nx + i);
625        let v_edge = |i: usize, j: usize| 2 * (j * nx + i) + 1;
626        let mut next: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
627        for j in 0..ny - 1 {
628            for i in 0..nx - 1 {
629                let inside = [value(i, j) <= 0.0, value(i + 1, j) <= 0.0, value(i + 1, j + 1) <= 0.0, value(i, j + 1) <= 0.0];
630                // Cell edges in counter-clockwise order: bottom, right, top, left.
631                let edges = [h_edge(i, j), v_edge(i + 1, j), h_edge(i, j + 1), v_edge(i, j)];
632                // A segment goes from the edge where the walk leaves the inside to where it re-enters,
633                // keeping the inside on its left (counter-clockwise outer loops).
634                let mut exits: Vec<usize> = Vec::new();
635                let mut entries: Vec<usize> = Vec::new();
636                for k in 0..4 {
637                    let (a, b) = (inside[k], inside[(k + 1) % 4]);
638                    if a && !b {
639                        exits.push(k);
640                    } else if !a && b {
641                        entries.push(k);
642                    }
643                }
644                match (exits.as_slice(), entries.as_slice()) {
645                    ([e], [n]) => {
646                        next.insert(edges[*n], edges[*e]);
647                    }
648                    ([e0, e1], [n0, n1]) => {
649                        // A saddle: the middle decides which corners join.
650                        let middle = f([x0 + cell * (i as f64 + 0.5), y0 + cell * (j as f64 + 0.5)]) <= 0.0;
651                        // Entries at n pair with the exit after them (inside joined) or before.
652                        let pair = |n: usize, exits: [usize; 2]| -> usize {
653                            let after = |e: usize| (e + 4 - n) % 4;
654                            if middle { *exits.iter().max_by_key(|&&e| after(e)).unwrap() } else { *exits.iter().min_by_key(|&&e| after(e)).unwrap() }
655                        };
656                        next.insert(edges[*n0], edges[pair(*n0, [*e0, *e1])]);
657                        next.insert(edges[*n1], edges[pair(*n1, [*e0, *e1])]);
658                    }
659                    _ => {}
660                }
661            }
662        }
663        // The points: each crossing edge's level point.
664        let edge_point = |id: usize| -> [f64; 2] {
665            let (cell_id, vertical) = (id / 2, id % 2 == 1);
666            let (i, j) = (cell_id % nx, cell_id / nx);
667            let (a, b) = if vertical { (node(i, j), node(i, j + 1)) } else { (node(i, j), node(i + 1, j)) };
668            if f(a) <= 0.0 { crossing(a, b) } else { crossing(b, a) }
669        };
670        let mut loops = Vec::new();
671        let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
672        let mut starts: Vec<usize> = next.keys().copied().collect();
673        starts.sort_unstable();
674        for start in starts {
675            if seen.contains(&start) {
676                continue;
677            }
678            let mut ring = Vec::new();
679            let mut at = start;
680            while seen.insert(at) {
681                ring.push(edge_point(at));
682                match next.get(&at) {
683                    Some(&n) => at = n,
684                    None => break,
685                }
686            }
687            if ring.len() >= 3 {
688                // The walk keeps the inside on its right: reversed, the outer
689                // loops run counter-clockwise and the holes clockwise.
690                ring.reverse();
691                loops.push(ring);
692            }
693        }
694        loops
695    }
696
697    /// The area of the stroke `{ d <= rho }` from its outlines at `cell`
698    /// (signed shoelace: outer loops counter-clockwise, holes clockwise).
699    /// `None` where the grid is not one [`Self::level_loops`] reads (a cell not
700    /// positive and finite, or past its node budget).
701    pub fn level_area(&self, rho: f64, cell: f64) -> Option<f64> {
702        if !self.grid_fits(rho, cell) {
703            return None;
704        }
705        Some(
706            self.level_loops(rho, cell)
707                .iter()
708                .map(|ring| {
709                    let n = ring.len();
710                    0.5 * (0..n).map(|k| ring[k][0] * ring[(k + 1) % n][1] - ring[(k + 1) % n][0] * ring[k][1]).sum::<f64>()
711                })
712                .sum(),
713        )
714    }
715
716    /// Whether [`Self::level_loops`] reads a grid of `cell` for `rho` (positive,
717    /// finite, at most a quarter of `rho`, within its 1e8-node budget).
718    fn grid_fits(&self, rho: f64, cell: f64) -> bool {
719        // A cell no coarser than a quarter of the radius (a coarser grid can
720        // step over a whole stroke and read it as nothing).
721        if !(cell > 0.0 && cell.is_finite() && rho >= 0.0 && rho.is_finite() && cell <= 0.25 * rho) {
722            return false;
723        }
724        let (lo, hi) = self.curve.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), c| {
725            ([lo[0].min(c[0]), lo[1].min(c[1])], [hi[0].max(c[0]), hi[1].max(c[1])])
726        });
727        let pad = rho + 2.0 * cell;
728        let (wx, wy) = (((hi[0] - lo[0] + 2.0 * pad) / cell).ceil(), ((hi[1] - lo[1] + 2.0 * pad) / cell).ceil());
729        wx.is_finite() && wy.is_finite() && (wx + 1.0) * (wy + 1.0) <= 1e8
730    }
731
732    /// The volume the tool passes through between heights `h0` and `h1`: the
733    /// stroke areas at the tool's radius integrated over the height, piece by
734    /// piece of the meridian's chain in the piece's own parameter (a line's
735    /// length, an arc's angle: there the radius and the height are smooth, as
736    /// they are not in the height where an arc meets a flat end), each piece
737    /// in four spans of 8-point Gauss–Legendre, the areas from outlines at `cell`.
738    /// `None` where a stroke's grid is not read (see [`Self::level_area`]).
739    pub fn volume(&self, h0: f64, h1: f64, cell: f64) -> Option<f64> {
740        let (a, b) = (h0.max(self.heights[0]), h1.min(self.heights[1]));
741        if !(b > a) {
742            return Some(0.0);
743        }
744        if !self.grid_fits(self.widest(), cell) {
745            return None;
746        }
747        // Each stroke's own grid is checked where it is read (a radius too
748        // small for the cell reads None, and the volume with it).
749        const X: [f64; 4] = [0.1834346424956498, 0.5255324099163290, 0.7966664774136267, 0.9602898564975363];
750        const W: [f64; 4] = [0.3626837833783620, 0.3137066458778873, 0.2223810344533745, 0.1012285362903763];
751        let gauss = |f: &dyn Fn(f64) -> f64, lo: f64, hi: f64| -> f64 {
752            let mut total = 0.0;
753            for k in 0..4 {
754                let (s0, s1) = (lo + (hi - lo) * k as f64 / 4.0, lo + (hi - lo) * (k + 1) as f64 / 4.0);
755                let (mid, half) = (0.5 * (s0 + s1), 0.5 * (s1 - s0));
756                for i in 0..4 {
757                    total += half * W[i] * (f(mid - half * X[i]) + f(mid + half * X[i]));
758                }
759            }
760            total
761        };
762        let mut total = 0.0;
763        for piece in &self.meridian {
764            match *piece {
765                OutlinePiece::Line { from, to } => {
766                    // Off the axis and rising or falling: its height range clipped to
767                    // [a, b] (the axis piece, by the gate's own tolerance, sweeps nothing).
768                    let tol_r = 1e-12 * self.widest();
769                    if from[0].abs() <= tol_r && to[0].abs() <= tol_r {
770                        continue;
771                    }
772                    let dh = to[1] - from[1];
773                    if dh == 0.0 {
774                        continue;
775                    }
776                    let (s0, s1) = (((a - from[1]) / dh).clamp(0.0, 1.0), ((b - from[1]) / dh).clamp(0.0, 1.0));
777                    let (lo, hi) = (s0.min(s1), s0.max(s1));
778                    if hi <= lo {
779                        continue;
780                    }
781                    let radius = |s: f64| from[0] + s * (to[0] - from[0]);
782                    // A stretch reaching the axis: its strokes shrink to the curve, read
783                    // as the radius times the length plus the disc, by the closed form
784                    // only where the grid cannot read them.
785                    // A side whose radius holds: one stroke for the whole stretch.
786                    if from[0] == to[0] {
787                        total += dh.abs() * (hi - lo) * self.level_area(from[0], cell)?;
788                    } else {
789                        total += dh.abs() * gauss(&|s| self.level_area(radius(s), cell).unwrap_or(f64::NAN), lo, hi);
790                    }
791                }
792                OutlinePiece::Arc { centre, radius, start, end } => {
793                    // θ over the arc where its height lies in [a, b] (the arc
794                    // holds no vertical tangent inside, so height is monotone in θ).
795                    let (t0, t1) = (start.min(end), start.max(end));
796                    let height = |t: f64| centre[1] + radius * t.sin();
797                    let clip = |h: f64| -> f64 {
798                        // The θ in [t0, t1] where the height is h (bisection on the monotone height).
799                        let (mut lo, mut hi) = (t0, t1);
800                        let rising = height(t1) > height(t0);
801                        for _ in 0..200 {
802                            let m = 0.5 * (lo + hi);
803                            if (height(m) < h) == rising { lo = m } else { hi = m }
804                        }
805                        0.5 * (lo + hi)
806                    };
807                    let (ha, hb) = (height(t0), height(t1));
808                    let (hlo, hhi) = (ha.min(hb), ha.max(hb));
809                    let (ca, cb) = (a.max(hlo), b.min(hhi));
810                    if cb <= ca {
811                        continue;
812                    }
813                    let (u0, u1) = (clip(ca), clip(cb));
814                    let (lo, hi) = (u0.min(u1), u0.max(u1));
815                    let f = |t: f64| self.level_area(centre[0] + radius * t.cos(), cell).unwrap_or(f64::NAN) * (radius * t.cos()).abs();
816                    total += gauss(&f, lo, hi);
817                }
818                OutlinePiece::Ellipse { .. } => {}
819            }
820        }
821        total.is_finite().then_some(total)
822    }
823
824    /// The section's reach as its curves' control points place it: the
825    /// greatest radius of the meridian's pieces' control points (built as the
826    /// sweep builds them).
827    fn section_reach(&self) -> f64 {
828        let (o, x, z) = (Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
829        self.meridian
830            .iter()
831            .filter_map(|piece| world_piece(piece, o, x, z).ok())
832            .flat_map(|curve| curve.control_points.into_iter())
833            .filter_map(|c| c.point().ok())
834            .map(|p| p.x.abs())
835            .fold(0.0f64, f64::max)
836    }
837
838    /// The tool's widest radius.
839    fn widest(&self) -> f64 {
840        self.meridian.iter().map(|piece| piece_extent(piece).0).fold(0.0f64, f64::max)
841    }
842}
843
844/// A meridian piece in the world: in the plane through `foot` spanned by the
845/// radial direction `out` (the piece's radius along it) and `up` (its height
846/// above the curve's plane), run as written.
847fn world_piece(piece: &OutlinePiece, foot: Vec3, out: Vec3, up: Vec3) -> Result<crate::NurbsCurve, String> {
848    let at = |p: [f64; 2]| foot.add(out.scale(p[0])).add(up.scale(p[1]));
849    match *piece {
850        OutlinePiece::Line { from, to } => crate::make_line(at(from), at(to)),
851        OutlinePiece::Arc { centre, radius, start, end } => {
852            let c = at(centre);
853            if end > start {
854                crate::make_arc(c, out, up, radius, start, end)
855            } else {
856                crate::make_arc(c, out, up, radius, end, start)?.reversed()
857            }
858        }
859        OutlinePiece::Ellipse { .. } => Err("an elliptic meridian piece".into()),
860    }
861}
862
863impl UprightSlot {
864    /// The meridian's chain (every piece but the one along the axis), in order
865    /// from the axis piece's end round to its start ([`Self::sections_are_discs`]).
866    fn chain(&self) -> Option<Vec<OutlinePiece>> {
867        let tol_r = 1e-12 * self.widest();
868        let along_axis = |piece: &OutlinePiece| matches!(*piece, OutlinePiece::Line { from, to } if from[0].abs() <= tol_r && to[0].abs() <= tol_r);
869        let axis_index = self.meridian.iter().position(along_axis)?;
870        let n = self.meridian.len();
871        Some((1..n).map(|k| self.meridian[(axis_index + k) % n].clone()).collect())
872    }
873
874    /// The tool where the curve has carried it to parameter `t`: its meridian
875    /// turned about the upright axis through B(t).
876    fn tool_at(&self, t: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
877        let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
878        let p = self.point(t);
879        let foot = self.origin.add(self.x.scale(p[0])).add(self.y.scale(p[1]));
880        let curves: Vec<crate::NurbsCurve> = self.meridian.iter().map(|piece| world_piece(piece, foot, self.x, self.up)).collect::<Result<_, _>>().map_err(refuse)?;
881        // The revolve builder's own refusal (a profile it reads as touching the
882        // axis, at its absolute 1e-3) is the construction's range, by name.
883        crate::revolve_profile_brep(&curves, foot, self.up, std::f64::consts::TAU).map_err(|e| {
884            crate::KernelRefusal::input(crate::KernelStage::Collect, "upright_scale", format!("uprightStroke: the tool is outside the construction's range: the revolve builder declined it ({e})"))
885        })
886    }
887
888    /// The tool's axial section at parameter `t` as a closed loop in the
889    /// vertical plane square to the curve there: the chain on the left of the
890    /// curve, then its mirror on the right, back to the start.
891    fn section_at(&self, t: f64) -> Result<Vec<crate::NurbsCurve>, String> {
892        let chain = self.chain().ok_or("no axis piece")?;
893        let p = self.point(t);
894        let d = self.derivative(t);
895        let length = dot(d, d).sqrt();
896        if !(length > 0.0) {
897            return Err("the curve stops".into());
898        }
899        let normal = [-d[1] / length, d[0] / length];
900        let foot = self.origin.add(self.x.scale(p[0])).add(self.y.scale(p[1]));
901        let left = self.x.scale(normal[0]).add(self.y.scale(normal[1]));
902        let mut loop_curves: Vec<crate::NurbsCurve> = chain.iter().map(|piece| world_piece(piece, foot, left, self.up)).collect::<Result<_, _>>()?;
903        let mirrored: Vec<crate::NurbsCurve> = chain.iter().rev().map(|piece| world_piece(piece, foot, left.scale(-1.0), self.up).and_then(|c| c.reversed())).collect::<Result<_, _>>()?;
904        loop_curves.extend(mirrored);
905        Ok(loop_curves)
906    }
907
908    /// The cubic's piece over [a, b] as a world curve (de Casteljau).
909    fn world_piece_of_curve(&self, a: f64, b: f64) -> Result<crate::NurbsCurve, String> {
910        let split = |c: [[f64; 2]; 4], t: f64| -> ([[f64; 2]; 4], [[f64; 2]; 4]) {
911            let l = |x: [f64; 2], y: [f64; 2]| [x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t];
912            let (p01, p12, p23) = (l(c[0], c[1]), l(c[1], c[2]), l(c[2], c[3]));
913            let (p012, p123) = (l(p01, p12), l(p12, p23));
914            let m = l(p012, p123);
915            ([c[0], p01, p012, m], [m, p123, p23, c[3]])
916        };
917        let right = if a > 0.0 { split(self.curve, a).1 } else { self.curve };
918        let piece = if b < 1.0 { split(right, (b - a) / (1.0 - a)).0 } else { right };
919        let world = |p: [f64; 2]| crate::Vec4 { x: self.origin.x + self.x.x * p[0] + self.y.x * p[1], y: self.origin.y + self.x.y * p[0] + self.y.y * p[1], z: self.origin.z + self.x.z * p[0] + self.y.z * p[1], w: 1.0 };
920        crate::NurbsCurve::new(3, vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], piece.iter().map(|p| world(*p)).collect())
921    }
922
923    /// The full section carried along [a, b] (no end tools).
924    fn section_sweep(&self, a: f64, b: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
925        let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
926        let section = self.section_at(a).map_err(refuse)?;
927        let path = self.world_piece_of_curve(a, b).map_err(refuse)?;
928        let chain = crate::SweepPath::new(vec![path], Vec::new())?;
929        crate::sweep_profile_along_chain(&section, &chain, 0.0, None, None, crate::SectionPlacement::Rigid, "an upright tool's section along one piece of a cubic")
930    }
931
932    /// The curve's pieces: tight where the tool's widest radius may reach past
933    /// the curve's radius of curvature (1% to spare; bounded, not sampled),
934    /// gentle elsewhere, each cut where its turning reaches 150° (no piece
935    /// crosses itself). (a, b, tight).
936    pub fn pieces(&self) -> Vec<(f64, f64, bool)> {
937        // Tightness against the section's reach as the section sweep reads it:
938        // its curves' control points (an arc's lie outside the arc), no less
939        // than the tool's own widest radius.
940        let widest = self.section_reach().max(self.widest());
941        // Tight spans, found without missing one: on each span an upper bound
942        // of the curvature |B'×B''|/|B'|³ from its middle and the Lipschitz
943        // bounds of the cross (its derivative B'×B''' ≤ |B'|max·|B'''|) and of
944        // the speed (|B''|max), bisected while the bound reaches the tool but
945        // the middle does not; a span the bound cannot clear is tight.
946        let c = &self.curve;
947        let polygon = (0..3).map(|k| 3.0 * dot(sub(c[k + 1], c[k]), sub(c[k + 1], c[k])).sqrt()).fold(0.0f64, f64::max);
948        let second_most = { let (a, b) = (self.second(0.0), self.second(1.0)); dot(a, a).sqrt().max(dot(b, b).sqrt()) };
949        let third = { let d = sub(self.second(1.0), self.second(0.0)); dot(d, d).sqrt() };
950        let cross = |t: f64| { let (d, dd) = (self.derivative(t), self.second(t)); (d[0] * dd[1] - d[1] * dd[0]).abs() };
951        let speed = |t: f64| dot(self.derivative(t), self.derivative(t)).sqrt();
952        let threshold = 0.99 / widest;
953        let may_be_tight = |a: f64, b: f64| -> bool {
954            let (m, h) = (0.5 * (a + b), 0.5 * (b - a));
955            let low = speed(m) - second_most * h;
956            if !(low > 0.0) {
957                return true;
958            }
959            (cross(m) + polygon * third * h) / (low * low * low) >= threshold
960        };
961        let is_tight_at = |t: f64| cross(t) / speed(t).powi(3) >= threshold;
962        let mut tight_spans: Vec<(f64, f64)> = Vec::new();
963        let mut stack: Vec<(f64, f64, u32)> = (0..256).rev().map(|k| (k as f64 / 256.0, (k + 1) as f64 / 256.0, 0)).collect();
964        // A budget of spans read (the envelope's regular curve needs few); past
965        // it every span left is taken as tight.
966        let mut read = 0usize;
967        while let Some((a, b, depth)) = stack.pop() {
968            read += 1;
969            if !may_be_tight(a, b) {
970                continue;
971            }
972            // Decided tight where its middle is, or where it cannot be split further.
973            if read > 1 << 20 || is_tight_at(0.5 * (a + b)) || depth >= 40 {
974                match tight_spans.last_mut() {
975                    Some(last) if (last.1 - a).abs() <= 1e-15 => last.1 = b,
976                    _ => tight_spans.push((a, b)),
977                }
978                continue;
979            }
980            let m = 0.5 * (a + b);
981            stack.push((m, b, depth + 1));
982            stack.push((a, m, depth + 1));
983        }
984        // Runs: the tight spans and the gentle stretches between them.
985        let mut runs: Vec<(f64, f64, bool)> = Vec::new();
986        let mut at = 0.0;
987        for (a, b) in tight_spans {
988            if a > at {
989                runs.push((at, a, false));
990            }
991            runs.push((a, b, true));
992            at = b;
993        }
994        if at < 1.0 {
995            runs.push((at, 1.0, false));
996        }
997        // Each run cut where its turning reaches 150° (a planar curve that
998        // turns less than half a turn cannot cross itself).
999        let heading = |t: f64| {
1000            let d = self.derivative(t);
1001            d[1].atan2(d[0])
1002        };
1003        let most = 150f64.to_radians();
1004        let mut pieces = Vec::new();
1005        for (a, b, is_tight) in runs {
1006            if !(b > a) {
1007                continue;
1008            }
1009            let steps = 2048;
1010            let mut turn = 0.0;
1011            let mut previous = heading(a);
1012            let mut start = a;
1013            for k in 1..=steps {
1014                let t = a + (b - a) * k as f64 / steps as f64;
1015                let h = heading(t);
1016                let mut delta = h - previous;
1017                while delta > std::f64::consts::PI { delta -= std::f64::consts::TAU; }
1018                while delta < -std::f64::consts::PI { delta += std::f64::consts::TAU; }
1019                turn += delta.abs();
1020                previous = h;
1021                if turn >= most && k < steps {
1022                    pieces.push((start, t, is_tight));
1023                    start = t;
1024                    turn = 0.0;
1025                }
1026            }
1027            pieces.push((start, b, is_tight));
1028        }
1029        pieces
1030    }
1031
1032    /// Everything the tool passes through along the whole curve, where it
1033    /// turns nowhere tighter than the tool reaches: the tool at every break
1034    /// and each piece's section sweep, united (the union also answers the
1035    /// curve crossing itself). A tighter turn is refused by name.
1036    pub fn solid(&self) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1037        // The construction's own range (its curves and booleans read absolute
1038        // tolerances): the tool's widest radius within [5e-2, 1e6], every arc
1039        // at least 1e-6.
1040        let small_arc = self.meridian.iter().any(|piece| matches!(*piece, OutlinePiece::Arc { radius, .. } if radius < 1e-6));
1041        let widest = self.widest();
1042        if small_arc || !(5e-2..=1e6).contains(&widest) {
1043            return Err(crate::KernelRefusal::input(
1044                crate::KernelStage::Collect,
1045                "upright_scale",
1046                format!("uprightStroke: a tool {widest:e} wide is outside the construction's range (5e-2 to 1e6, its arcs at least 1e-6: the revolve builder reads 1e-3 from the axis)"),
1047            ));
1048        }
1049        let pieces = self.pieces();
1050        // A turn tighter than the tool folds its concave wall; the trimmed
1051        // fold is not built yet (the route refuses rather than guess it).
1052        if let Some(&(a, b, _)) = pieces.iter().find(|p| p.2) {
1053            return Err(crate::KernelRefusal::unsupported(
1054                crate::KernelStage::Collect,
1055                "upright_tight_turn",
1056                format!("uprightStroke: the curve turns tighter than the tool reaches over [{a:.4}, {b:.4}]; its folded concave wall is not built"),
1057            ));
1058        }
1059        // The tools at every break first, one after another (overlapping
1060        // tools join cleanly with each other), then each piece's section
1061        // sweep (the union answers the curve crossing itself).
1062        let mut whole = self.tool_at(0.0)?;
1063        for (index, &(_, b, _)) in pieces.iter().enumerate() {
1064            whole = crate::boolean_operation_nary(&[whole, self.tool_at(b)?], crate::BooleanOperation::Union)
1065                .map_err(|e| e.with_message(|m| format!("{m} (adding the tool at break {index}, t = {b})")))?;
1066        }
1067        for (index, &(a, b, _)) in pieces.iter().enumerate() {
1068            whole = crate::boolean_operation_nary(&[whole, self.section_sweep(a, b)?], crate::BooleanOperation::Union)
1069                .map_err(|e| e.with_message(|m| format!("{m} (adding sweep {index} of {}, [{a}, {b}])", pieces.len())))?;
1070        }
1071        Ok(whole)
1072    }
1073
1074    /// What the tool passes through over the curve's piece [a, b], where the
1075    /// piece turns nowhere tighter than the tool reaches and does not cross
1076    /// itself: its axial section carried by the curve's own rigid motion (the
1077    /// section sweep, which refuses a bend tighter than the section), and the
1078    /// tool itself at the two ends, united.
1079    pub fn stroke(&self, a: f64, b: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1080        let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
1081        if !(0.0 <= a && a < b && b <= 1.0) {
1082            return Err(crate::KernelRefusal::input(crate::KernelStage::Collect, "upright_stroke_range", format!("uprightStroke: the piece [{a}, {b}] is not within the curve's [0, 1]")));
1083        }
1084        let section = self.section_at(a).map_err(refuse)?;
1085        let path = self.world_piece_of_curve(a, b).map_err(refuse)?;
1086        let chain = crate::SweepPath::new(vec![path], Vec::new())?;
1087        let swept = crate::sweep_profile_along_chain(&section, &chain, 0.0, None, None, crate::SectionPlacement::Rigid, "an upright tool's section along one piece of a cubic")?;
1088        crate::boolean_operation_nary(&[swept, self.tool_at(a)?, self.tool_at(b)?], crate::BooleanOperation::Union)
1089    }
1090}
1091