Skip to main content

brep_construction/construction/
solid_sweep_apex.rs

1//! A pyramid frustum swept by turns about axes through its apex: a gear's
2//! tooth rolled in mesh on shafts that meet (a bevel gear cut by its
3//! pinion), or any convex-sided cutter whose flanks are planes through the
4//! point its motion holds still.
5//!
6//! Every turn holds the apex O still and every side of the pyramid is a plane
7//! through O, so the pyramid (without its end planes) at every time is the
8//! cone over a convex spherical polygon, and what all of them sweep is the
9//! cone over the region of directions those polygons sweep on the sphere.
10//! The frustum's end planes cut it off: within the distances from O between
11//! the inner end's farthest point and the outer end's nearest, the sweep is
12//! exactly that cone ([`sweep_pyramid_within`] refuses a range outside them).
13//!
14//! The region is read in the plane square to a middle direction m, at
15//! distance 1 from O (each direction d its point d/(d·m)). Its boundary
16//! lies on three kinds of curve, each known in closed form at every time:
17//! - the track of a corner (a corner direction turned);
18//! - the envelope of a side: at each time the point of the side whose
19//!   velocity lies in the side's own plane, where that point lies on the side;
20//! - the sides at the first and last time.
21//!
22//! Each curve is sampled, the samples crossing one another found and solved
23//! on the exact curves (a side's envelope meets the corner it hands over to
24//! at the time its point reaches the end, solved on that), and each stretch
25//! between crossings kept where membership differs on its two sides.
26//! Membership steps the time by the largest angle by which the direction
27//! lies outside a side's plane (in the moving tool's frame) over a bound on
28//! how fast the direction turns there, so it skips no time at which the
29//! direction is inside. The kept stretches close into one loop; its curves
30//! are fitted through their exact points on the planes square to m at the
31//! range's ends, and lofted (each wall a ruled cone through O).
32
33use crate::{loft_profile_brep, KernelRefusal, KernelStage, NurbsCurve, SolidMotion, Vec3};
34
35/// The prefix of every refusal of this operation.
36pub const APEX_SWEEP_REFUSAL: &str = "sweepPyramidWithin";
37
38fn refuse(what: &'static str, message: String) -> KernelRefusal {
39    KernelRefusal::unsupported(KernelStage::Collect, what, format!("{APEX_SWEEP_REFUSAL}: {message}"))
40}
41
42fn input(what: &'static str, message: String) -> KernelRefusal {
43    KernelRefusal::input(KernelStage::Collect, what, format!("{APEX_SWEEP_REFUSAL}: {message}"))
44}
45
46/// A frustum of a pyramid: the convex polygon `section` (corners in order, in
47/// the plane square to `axis` at distance `at` from `apex`, coordinates along
48/// `x_axis` and `axis × x_axis` from the axis's point there), the pyramid
49/// from `apex` over it, cut off by the planes square to `axis` at distances
50/// `from` and `to` from the apex.
51#[derive(Clone, Debug)]
52pub struct Pyramid {
53    pub apex: Vec3,
54    pub axis: Vec3,
55    pub x_axis: Vec3,
56    pub at: f64,
57    pub section: Vec<[f64; 2]>,
58    pub from: f64,
59    pub to: f64,
60}
61
62type P2 = [f64; 2];
63
64fn rotate(v: Vec3, axis: Vec3, angle: f64) -> Vec3 {
65    let (c, s) = (angle.cos(), angle.sin());
66    v.scale(c).add(axis.cross(v).scale(s)).add(axis.scale(axis.dot(v) * (1.0 - c)))
67}
68
69/// The motion: turns about unit axes through the apex at rates, applied in
70/// order (the first to the tool first).
71struct Turns {
72    axes: Vec<(Vec3, f64)>,
73    t0: f64,
74    t1: f64,
75}
76
77impl Turns {
78    fn apply(&self, t: f64, v: Vec3) -> Vec3 {
79        self.axes.iter().fold(v, |v, &(a, w)| rotate(v, a, w * t))
80    }
81    fn invert(&self, t: f64, v: Vec3) -> Vec3 {
82        self.axes.iter().rev().fold(v, |v, &(a, w)| rotate(v, a, -w * t))
83    }
84    /// The angular velocity at t, in the world: each turn's axis carried
85    /// by the turns after it.
86    fn omega(&self, t: f64) -> Vec3 {
87        let mut total = Vec3::new(0.0, 0.0, 0.0);
88        for (k, &(a, w)) in self.axes.iter().enumerate() {
89            let carried = self.axes[k + 1..].iter().fold(a, |v, &(b, u)| rotate(v, b, u * t));
90            total = total.add(carried.scale(w));
91        }
92        total
93    }
94    /// A bound on how fast a direction turns in the tool's frame.
95    fn rate(&self) -> f64 {
96        self.axes.iter().map(|(_, w)| w.abs()).sum::<f64>() * (1.0 + 1e-12)
97    }
98}
99
100/// A boundary candidate.
101#[derive(Clone, Copy, Debug, PartialEq)]
102enum Kind {
103    Corner(usize),
104    Envelope(usize),
105    /// Side k at the first (false) or last (true) time: parameter its fraction.
106    End(usize, bool),
107}
108
109struct Region {
110    turns: Turns,
111    /// Corner directions in the tool's frame (unit), in order round.
112    corners: Vec<Vec3>,
113    /// Each side's outward unit normal in the tool's frame (its plane through O).
114    normals: Vec<Vec3>,
115    /// The chart: middle direction and its frame.
116    m: Vec3,
117    e1: Vec3,
118    e2: Vec3,
119}
120
121impl Region {
122    fn chart(&self, d: Vec3) -> P2 {
123        let n = d.dot(self.m);
124        [d.dot(self.e1) / n, d.dot(self.e2) / n]
125    }
126    fn direction(&self, y: P2) -> Vec3 {
127        let d = self.m.add(self.e1.scale(y[0])).add(self.e2.scale(y[1]));
128        d.scale(1.0 / d.length())
129    }
130
131    /// The fraction along side k (from corner k to k + 1, as the chord of the
132    /// two directions) of its envelope point at t: where the side's points'
133    /// velocities lie in its plane.
134    fn foot(&self, k: usize, t: f64) -> f64 {
135        let n = self.corners.len();
136        let (a, b) = (self.turns.apply(t, self.corners[k]), self.turns.apply(t, self.corners[(k + 1) % n]));
137        let normal = self.turns.apply(t, self.normals[k]);
138        let w = self.turns.omega(t);
139        // (ω × x)·n = x·(n × ω), linear in x along the chord
140        let g = normal.cross(w);
141        let (ga, gb) = (a.dot(g), b.dot(g));
142        if ga == gb { f64::NAN } else { ga / (ga - gb) }
143    }
144
145    fn eval(&self, kind: Kind, s: f64) -> P2 {
146        let n = self.corners.len();
147        let on_side = |k: usize, f: f64, t: f64| {
148            let (a, b) = (self.corners[k], self.corners[(k + 1) % n]);
149            self.turns.apply(t, a.scale(1.0 - f).add(b.scale(f)))
150        };
151        let d = match kind {
152            Kind::Corner(k) => self.turns.apply(s, self.corners[k]),
153            Kind::Envelope(k) => on_side(k, self.foot(k, s).clamp(0.0, 1.0), s),
154            Kind::End(k, end) => on_side(k, s, if end { self.turns.t1 } else { self.turns.t0 }),
155        };
156        self.chart(d)
157    }
158
159    /// Whether the direction of chart point `y` lies in the swept region:
160    /// the time stepped by the largest angle outside a side's plane over
161    /// the turning rate. None where ten million steps do not reach the end
162    /// (a direction lingering just outside a side; cross review: it was
163    /// read as inside).
164    fn member(&self, y: P2) -> Option<bool> {
165        let d = self.direction(y);
166        let (t0, t1) = (self.turns.t0, self.turns.t1);
167        let rate = self.turns.rate();
168        let floor = (t1 - t0) * 1e-12;
169        let mut t = t0;
170        for _ in 0..10_000_000 {
171            let p = self.turns.invert(t, d);
172            let outside = self.normals.iter().map(|n| p.dot(*n).clamp(-1.0, 1.0).asin()).fold(f64::NEG_INFINITY, f64::max);
173            if outside < 0.0 {
174                return Some(true);
175            }
176            if t >= t1 {
177                return Some(false);
178            }
179            t = (t + (outside / rate).max(floor)).min(t1);
180        }
181        None
182    }
183}
184
185/// A stretch of a candidate between two parameters.
186#[derive(Clone, Copy, Debug)]
187struct Piece {
188    kind: Kind,
189    a: f64,
190    b: f64,
191}
192
193/// The root of `f` on [a, b] where it changes sign, by bisection.
194fn bisect(f: impl Fn(f64) -> f64, mut a: f64, mut b: f64) -> f64 {
195    let fa = f(a);
196    for _ in 0..200 {
197        let m = 0.5 * (a + b);
198        if m <= a || m >= b {
199            break;
200        }
201        if (f(m) < 0.0) == (fa < 0.0) { a = m } else { b = m }
202    }
203    0.5 * (a + b)
204}
205
206const SAMPLES: usize = 512;
207
208/// The region's boundary: one loop of stretches, the region on its left.
209fn boundary(region: &Region) -> Result<Vec<Piece>, KernelRefusal> {
210    let n = region.corners.len();
211    let (t0, t1) = (region.turns.t0, region.turns.t1);
212    // The candidates: each corner's track, each side's envelope over the runs
213    // of time its point lies on the side, each side at both ends.
214    let mut candidates: Vec<Piece> = Vec::new();
215    for k in 0..n {
216        candidates.push(Piece { kind: Kind::Corner(k), a: t0, b: t1 });
217        candidates.push(Piece { kind: Kind::End(k, false), a: 0.0, b: 1.0 });
218        candidates.push(Piece { kind: Kind::End(k, true), a: 0.0, b: 1.0 });
219        let at = |i: usize| t0 + (t1 - t0) * i as f64 / SAMPLES as f64;
220        let on = |t: f64| { let f = region.foot(k, t); f.is_finite() && (0.0..=1.0).contains(&f) };
221        let mut start: Option<f64> = if on(t0) { Some(t0) } else { None };
222        for i in 1..=SAMPLES {
223            let (ta, tb) = (at(i - 1), at(i));
224            match (on(ta), on(tb)) {
225                (false, true) => start = Some(edge_of_run(region, k, ta, tb)),
226                (true, false) => {
227                    let end = edge_of_run(region, k, ta, tb);
228                    if let Some(s) = start.take() {
229                        if end > s {
230                            candidates.push(Piece { kind: Kind::Envelope(k), a: s, b: end });
231                        }
232                    }
233                }
234                _ => {}
235            }
236        }
237        if let Some(s) = start {
238            if t1 > s {
239                candidates.push(Piece { kind: Kind::Envelope(k), a: s, b: t1 });
240            }
241        }
242    }
243    // Sample each, and find where any two cross (solved on the exact curves).
244    let polyline = |p: &Piece| -> Vec<(f64, P2)> { (0..=SAMPLES).map(|i| { let s = p.a + (p.b - p.a) * i as f64 / SAMPLES as f64; (s, region.eval(p.kind, s)) }).collect() };
245    let lines: Vec<Vec<(f64, P2)>> = candidates.iter().map(polyline).collect();
246    let size = lines.iter().flatten().map(|(_, q)| q[0].abs().max(q[1].abs())).fold(0.0f64, f64::max).max(1e-3);
247    let mut cuts: Vec<Vec<f64>> = candidates.iter().map(|p| vec![p.a, p.b]).collect();
248    // An envelope hands over (tangent) to the corner its point reaches, or
249    // starts or ends on a side at the first or last time: cut that curve there.
250    let index = |kind: Kind| candidates.iter().position(|c| c.kind == kind);
251    for i in 0..candidates.len() {
252        let Kind::Envelope(k) = candidates[i].kind else { continue };
253        for t in [candidates[i].a, candidates[i].b] {
254            let f = region.foot(k, t);
255            let (target, at) = if t == t0 {
256                (Kind::End(k, false), f.clamp(0.0, 1.0))
257            } else if t == t1 {
258                (Kind::End(k, true), f.clamp(0.0, 1.0))
259            } else if f < 0.5 {
260                (Kind::Corner(k), t)
261            } else {
262                (Kind::Corner((k + 1) % n), t)
263            };
264            if let Some(j) = index(target) {
265                cuts[j].push(at);
266            }
267        }
268    }
269    for i in 0..candidates.len() {
270        for j in i + 1..candidates.len() {
271            for w in 0..SAMPLES {
272                for v in 0..SAMPLES {
273                    let (p0, p1, q0, q1) = (lines[i][w].1, lines[i][w + 1].1, lines[j][v].1, lines[j][v + 1].1);
274                    // a quick box reject
275                    if p0[0].max(p1[0]) < q0[0].min(q1[0]) || q0[0].max(q1[0]) < p0[0].min(p1[0]) || p0[1].max(p1[1]) < q0[1].min(q1[1]) || q0[1].max(q1[1]) < p0[1].min(p1[1]) {
276                        continue;
277                    }
278                    let (r, s) = ([p1[0] - p0[0], p1[1] - p0[1]], [q1[0] - q0[0], q1[1] - q0[1]]);
279                    let den = r[0] * s[1] - r[1] * s[0];
280                    if den == 0.0 {
281                        continue;
282                    }
283                    let (dx, dy) = (q0[0] - p0[0], q0[1] - p0[1]);
284                    let (u, z) = ((dx * s[1] - dy * s[0]) / den, (dx * r[1] - dy * r[0]) / den);
285                    // the sample stretches' ends (shared points of curves that
286                    // hand over) are found as ends, not crossings
287                    if !(u > 1e-9 && u < 1.0 - 1e-9 && z > 1e-9 && z < 1.0 - 1e-9) {
288                        continue;
289                    }
290                    let (sa, sb) = (lines[i][w].0 + u * (lines[i][w + 1].0 - lines[i][w].0), lines[j][v].0 + z * (lines[j][v + 1].0 - lines[j][v].0));
291                    if let Some((sa, sb)) = newton(region, candidates[i], candidates[j], sa, sb, size) {
292                        cuts[i].push(sa);
293                        cuts[j].push(sb);
294                    }
295                }
296            }
297        }
298    }
299    // The stretches between cuts, kept where membership differs across them.
300    let eps = 1e-7 * size;
301    let mut kept: Vec<(Piece, P2, P2)> = Vec::new();
302    for (i, piece) in candidates.iter().enumerate() {
303        let mut c = cuts[i].clone();
304        c.sort_by(|x, y| x.total_cmp(y));
305        c.dedup_by(|x, y| (*x - *y).abs() <= 1e-12 * (piece.b - piece.a).abs().max(1e-300));
306        for w in c.windows(2) {
307            let (a, b) = (w[0], w[1]);
308            if !(b > a) {
309                continue;
310            }
311            let m = 0.5 * (a + b);
312            let h = 1e-6 * (b - a);
313            let (y, ya, yb) = (region.eval(piece.kind, m), region.eval(piece.kind, m - h), region.eval(piece.kind, m + h));
314            let (dx, dy) = (yb[0] - ya[0], yb[1] - ya[1]);
315            let l = dx.hypot(dy);
316            if !(l > 0.0) {
317                continue;
318            }
319            let left = [-dy / l, dx / l];
320            let read = |q: P2| region.member(q).ok_or_else(|| refuse("apex_member", format!("membership at ({:.6}, {:.6}) does not settle", q[0], q[1])));
321            let (inside_left, inside_right) = (read([y[0] + left[0] * eps, y[1] + left[1] * eps])?, read([y[0] - left[0] * eps, y[1] - left[1] * eps])?);
322            if inside_left == inside_right {
323                continue;
324            }
325            let stretch = if inside_left { Piece { kind: piece.kind, a, b } } else { Piece { kind: piece.kind, a: b, b: a } };
326            kept.push((stretch, region.eval(piece.kind, stretch.a), region.eval(piece.kind, stretch.b)));
327        }
328    }
329    // One loop, end to start.
330    if kept.is_empty() {
331        return Err(refuse("apex_empty", "the section sweeps no region".into()));
332    }
333    let close = 1e-7 * size;
334    let gap = |p: P2, q: P2| (p[0] - q[0]).hypot(p[1] - q[1]);
335    let mut used = vec![false; kept.len()];
336    let mut chain = vec![0usize];
337    used[0] = true;
338    loop {
339        let end = kept[*chain.last().unwrap()].2;
340        if gap(end, kept[chain[0]].1) <= close && chain.len() > 1 {
341            break;
342        }
343        let next = (0..kept.len()).filter(|&j| !used[j]).min_by(|&x, &y| gap(end, kept[x].1).total_cmp(&gap(end, kept[y].1)));
344        match next {
345            Some(j) if gap(end, kept[j].1) <= close => {
346                used[j] = true;
347                chain.push(j);
348            }
349            _ => return Err(refuse("apex_open", format!("the region's boundary does not close (at ({:.6}, {:.6}))", end[0], end[1]))),
350        }
351    }
352    if used.iter().any(|u| !u) {
353        return Err(refuse("apex_loops", format!("the region's boundary is more than one loop ({} stretches left)", used.iter().filter(|u| !**u).count())));
354    }
355    Ok(chain.into_iter().map(|j| kept[j].0).collect())
356}
357
358/// The edge of a run of time where side k's envelope point lies on the side,
359/// between `ta` and `tb` (one on it, one off): where the fraction crosses 0
360/// or 1, by bisection (the envelope hands over to that corner's track there).
361fn edge_of_run(region: &Region, k: usize, ta: f64, tb: f64) -> f64 {
362    let (fa, fb) = (region.foot(k, ta), region.foot(k, tb));
363    let bound = if fa.is_finite() && fb.is_finite() && (fa < 0.0 || fb < 0.0) && !(fa > 1.0 || fb > 1.0) { 0.0 } else { 1.0 };
364    bisect(|t| region.foot(k, t) - bound, ta, tb)
365}
366
367/// Two candidates' crossing near (sa, sb), by Newton's method; None where it
368/// does not converge within both stretches.
369fn newton(region: &Region, p: Piece, q: Piece, mut sa: f64, mut sb: f64, size: f64) -> Option<(f64, f64)> {
370    let (lo_a, hi_a) = (p.a.min(p.b), p.a.max(p.b));
371    let (lo_b, hi_b) = (q.a.min(q.b), q.a.max(q.b));
372    for _ in 0..60 {
373        let (x, y) = (region.eval(p.kind, sa), region.eval(q.kind, sb));
374        let r = [x[0] - y[0], x[1] - y[1]];
375        if r[0].hypot(r[1]) <= 1e-14 * size {
376            return (sa >= lo_a && sa <= hi_a && sb >= lo_b && sb <= hi_b).then_some((sa, sb));
377        }
378        let (ha, hb) = (1e-7 * (hi_a - lo_a), 1e-7 * (hi_b - lo_b));
379        let (xa, yb) = (region.eval(p.kind, sa + ha), region.eval(q.kind, sb + hb));
380        let j = [[(xa[0] - x[0]) / ha, -(yb[0] - y[0]) / hb], [(xa[1] - x[1]) / ha, -(yb[1] - y[1]) / hb]];
381        let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
382        if !(det.is_finite() && det != 0.0) {
383            return None;
384        }
385        sa -= (j[1][1] * r[0] - j[0][1] * r[1]) / det;
386        sb -= (-j[1][0] * r[0] + j[0][0] * r[1]) / det;
387        if !(sa.is_finite() && sb.is_finite()) {
388            return None;
389        }
390    }
391    None
392}
393
394/// What `tool` sweeps under `motion` (turns about axes through its apex),
395/// within the distances `within` = [r0, r1] from the apex: the cone over the
396/// region its section sweeps, capped by planes square to the region's middle
397/// direction (inside r0 for its widest direction, and at r1): within [r0, r1]
398/// it is the sweep, beyond it the result is not. Refuses a motion with an advance or an axis missing the apex,
399/// a section that is not convex, a range beyond where the sweep is the cone
400/// (past the inner end's farthest point and short of the outer end's
401/// nearest), and a region whose boundary is not one loop.
402pub fn sweep_pyramid_within(tool: &Pyramid, motion: &SolidMotion, within: [f64; 2]) -> Result<crate::BrepSolid, KernelRefusal> {
403    let axis = tool.axis.normalized().map_err(|e| input("apex_axis", e))?;
404    let x = tool.x_axis.sub(axis.scale(tool.x_axis.dot(axis))).normalized().map_err(|e| input("apex_x_axis", e))?;
405    let y = axis.cross(x);
406    let n = tool.section.len();
407    if n < 3 || !(tool.at > 0.0 && tool.from > 0.0 && tool.to > tool.from) {
408        return Err(input("apex_tool", "a section of three or more corners, at a positive distance, between positive end distances".into()));
409    }
410    // convex, counter-clockwise or not
411    let turn = |k: usize| {
412        let (a, b, c) = (tool.section[k], tool.section[(k + 1) % n], tool.section[(k + 2) % n]);
413        (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
414    };
415    let sense = turn(0).signum();
416    if sense == 0.0 || (0..n).any(|k| turn(k).signum() != sense) {
417        return Err(input("apex_convex", "the section must be convex".into()));
418    }
419    let point = |q: P2, at: f64| axis.scale(at).add(x.scale(q[0] * at / tool.at)).add(y.scale(q[1] * at / tool.at));
420    let corners: Vec<Vec3> = tool.section.iter().map(|&q| { let p = point(q, tool.at); p.scale(1.0 / p.length()) }).collect();
421    // each side's plane through O, its normal pointing out of the pyramid
422    let normals: Vec<Vec3> = (0..n)
423        .map(|k| {
424            let c = corners[k].cross(corners[(k + 1) % n]);
425            let c = c.scale(1.0 / c.length());
426            if c.dot(corners[(k + 2) % n]) > 0.0 { c.scale(-1.0) } else { c }
427        })
428        .collect();
429    // where the sweep is the cone: past the inner end's farthest point, short of the outer end's nearest
430    let inner = tool.section.iter().map(|&q| point(q, tool.from).length()).fold(0.0f64, f64::max);
431    let outer = {
432        // the outer end's nearest point to O: its foot if the axis meets the section, else on its rim
433        let inside = (0..n).all(|k| { let (a, b) = (tool.section[k], tool.section[(k + 1) % n]); ((b[0] - a[0]) * (0.0 - a[1]) - (b[1] - a[1]) * (0.0 - a[0])).signum() == sense });
434        if inside {
435            tool.to
436        } else {
437            (0..n).map(|k| {
438                let (a, b) = (point(tool.section[k], tool.to), point(tool.section[(k + 1) % n], tool.to));
439                let e = b.sub(a);
440                let s = (-a.dot(e) / e.dot(e)).clamp(0.0, 1.0);
441                a.add(e.scale(s)).length()
442            }).fold(f64::INFINITY, f64::min)
443        }
444    };
445    let [r0, r1] = within;
446    if !(r0.is_finite() && r1.is_finite() && r1 > r0) {
447        return Err(input("apex_within", "the distances must be finite, the first below the second".into()));
448    }
449    if !(r0 >= inner && r1 <= outer) {
450        return Err(refuse("apex_within", format!("the sweep is the cone only between {inner} and {outer} from the apex, not across [{r0}, {r1}]")));
451    }
452    // the motion: turns about axes through the apex, no advance
453    let mut axes = Vec::with_capacity(motion.steps.len());
454    for step in &motion.steps {
455        let a = step.axis_direction.normalized().map_err(|e| input("apex_step", e))?;
456        let off = step.axis_origin.sub(tool.apex);
457        let miss = off.sub(a.scale(off.dot(a))).length();
458        // the tool's own size sets the tolerance (cross review: a far
459        // origin along the axis must not hide a miss)
460        if step.advance != 0.0 || miss > 1e-12 * tool.to {
461            return Err(refuse("apex_motion", "every step must be a turn about an axis through the apex".into()));
462        }
463        axes.push((a, step.turn));
464    }
465    if !(motion.to > motion.from) || axes.iter().all(|(_, w)| *w == 0.0) {
466        return Err(input("apex_motion", "the motion must turn over a positive range".into()));
467    }
468    let turns = Turns { axes, t0: motion.from, t1: motion.to };
469    // the chart: square to the tool's axis at the middle time
470    let m = turns.apply(0.5 * (turns.t0 + turns.t1), axis);
471    let e1 = m.perpendicular().map_err(|e| input("apex_chart", e))?;
472    let e2 = m.cross(e1);
473    // every corner stays within 80° of the middle direction
474    for i in 0..=64 {
475        let t = turns.t0 + (turns.t1 - turns.t0) * i as f64 / 64.0;
476        if corners.iter().any(|c| turns.apply(t, *c).dot(m) < 0.17) {
477            return Err(refuse("apex_spread", "the tool turns more than 80° from its middle direction".into()));
478        }
479    }
480    let region = Region { turns, corners, normals, m, e1, e2 };
481    let pieces = boundary(&region)?;
482    // the planes square to m: the inner just inside r0 (every direction's
483    // point there no farther than r0), the outer at r1 (no farther than the
484    // cone is exact)
485    let mut widest = 1.0f64;
486    let mut samples: Vec<Vec<(f64, P2)>> = Vec::with_capacity(pieces.len());
487    for piece in &pieces {
488        let points: Vec<(f64, P2)> = (0..=96).map(|i| { let s = piece.a + (piece.b - piece.a) * i as f64 / 96.0; (s, region.eval(piece.kind, s)) }).collect();
489        for (_, q) in &points {
490            widest = widest.max((1.0 + q[0] * q[0] + q[1] * q[1]).sqrt());
491        }
492        samples.push(points);
493    }
494    // Within [r0, r1] the slab between these planes holds every point of
495    // the cone (x·m lies between |x|/widest and |x|), and there the cone is
496    // the sweep; beyond the range the result is not the sweep.
497    let (near, far) = (r0 / widest * (1.0 - 1e-9), r1);
498    let lift = |q: P2, h: f64| tool.apex.add(region.m.scale(h)).add(region.e1.scale(q[0] * h)).add(region.e2.scale(q[1] * h));
499    let section = |h: f64| -> Result<Vec<NurbsCurve>, KernelRefusal> {
500        samples
501            .iter()
502            .map(|points| {
503                let xs: Vec<Vec3> = points.iter().map(|(_, q)| lift(*q, h)).collect();
504                let mut s = vec![0.0];
505                for w in xs.windows(2) {
506                    s.push(s.last().unwrap() + w[1].sub(w[0]).length());
507                }
508                let total = *s.last().unwrap();
509                let parameters: Vec<f64> = s.iter().map(|v| v / total).collect();
510                crate::interpolate_curve(&xs, 3, &parameters).map_err(|e| refuse("apex_fit", e))
511            })
512            .collect()
513    };
514    let (inner_section, outer_section) = (section(near)?, section(far)?);
515    loft_profile_brep(&[inner_section, outer_section])
516}
517