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