Skip to main content

brep_construction/construction/
planar_region.rs

1//! The exact region a polygon covers under a planar rigid motion (turns about
2//! axes along the prism's own direction), extruded: the sweep of a straight-
3//! sided prism within a clip, built from its boundary curves rather than read
4//! level by level (behind `BREP_SWEEP_PLANAR_REGION`, default on; `=0` restores the level engine).
5//!
6//! In the plane square to the turns the boundary of the region lies on
7//! - the paths of the polygon's corners;
8//! - the envelopes of its sides: at each time the point of a side whose
9//!   velocity runs along it (the foot of the perpendicular from the
10//!   instantaneous centre), where that point lies on the side;
11//! - the sides at the two end positions (none when the motion ends where it
12//!   began, as a set);
13//! - the clip's circles (and its angle's rays).
14//!
15//! These curves are cut at their crossings (found on samples, then solved
16//! on the exact curves), and an arc is kept where exact membership differs on
17//! its two sides; membership walks the motion's time by the polygon's signed
18//! distance over a bound on the preimage's speed. The kept arcs close into
19//! loops, which are extruded over the clip's axial range.
20use crate::solid_sweep::{OutlinePiece, ScrewStep, SolidMotion, SweepClip, SweptTool};
21use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
22use crate::{make_line, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, OrRefuse, Vec3, Vec4};
23use std::f64::consts::TAU;
24
25/// The switch (default on; `BREP_SWEEP_PLANAR_REGION=0` restores the level engine).
26pub fn planar_region_on() -> bool {
27    crate::switch!("BREP_SWEEP_PLANAR_REGION", true)
28}
29
30fn refuse(what: &'static str, message: String) -> KernelRefusal {
31    KernelRefusal::unsupported(KernelStage::Classify, what, format!("sweepSolidWithin: {message}"))
32}
33
34fn frag<T>(result: Result<T, String>, what: &'static str) -> Result<T, KernelRefusal> {
35    result.or_refuse(KernelStage::Fragment, what)
36}
37
38type P2 = [f64; 2];
39
40fn sub(a: P2, b: P2) -> P2 {
41    [a[0] - b[0], a[1] - b[1]]
42}
43fn add(a: P2, b: P2) -> P2 {
44    [a[0] + b[0], a[1] + b[1]]
45}
46fn mul(a: P2, s: f64) -> P2 {
47    [a[0] * s, a[1] * s]
48}
49fn dot(a: P2, b: P2) -> f64 {
50    a[0] * b[0] + a[1] * b[1]
51}
52fn cross(a: P2, b: P2) -> f64 {
53    a[0] * b[1] - a[1] * b[0]
54}
55fn norm(a: P2) -> f64 {
56    a[0].hypot(a[1])
57}
58fn rot(a: P2, angle: f64) -> P2 {
59    let (s, c) = angle.sin_cos();
60    [c * a[0] - s * a[1], s * a[0] + c * a[1]]
61}
62
63/// The motion in the plane: turns (centre, rate) applied in order.
64struct Motion {
65    turns: Vec<(P2, f64)>,
66    t0: f64,
67    t1: f64,
68}
69
70impl Motion {
71    /// The pose at t: `x ↦ R(θ) x + b`, as (θ, b), and their rates.
72    fn pose(&self, t: f64) -> (f64, P2, f64, P2) {
73        let (mut theta, mut b, mut dtheta, mut db) = (0.0, [0.0, 0.0], 0.0, [0.0, 0.0]);
74        for &(c, w) in &self.turns {
75            // b ← R(wt)(b − c) + c; db ← R(wt) db + w J R(wt)(b − c)
76            let rel = rot(sub(b, c), w * t);
77            db = add(rot(db, w * t), mul([-rel[1], rel[0]], w));
78            b = add(rel, c);
79            theta += w * t;
80            dtheta += w;
81        }
82        (theta, b, dtheta, db)
83    }
84    fn apply(&self, t: f64, x: P2) -> P2 {
85        let (theta, b, _, _) = self.pose(t);
86        add(rot(x, theta), b)
87    }
88    fn invert(&self, t: f64, y: P2) -> P2 {
89        let (theta, b, _, _) = self.pose(t);
90        rot(sub(y, b), -theta)
91    }
92    /// The velocity of the material point at world `y` at time t.
93    fn velocity(&self, t: f64, y: P2) -> P2 {
94        let (_, b, dtheta, db) = self.pose(t);
95        let r = sub(y, b);
96        add(mul([-r[1], r[0]], dtheta), db)
97    }
98    /// A bound on the preimage's acceleration for a world point `y`, at
99    /// every time: with x = R(−θ)(y − b), |x''| <= |ω|·|v| + |ω|·|b'| + |b''|
100    /// and |v| <= |ω|·|y − b| + |b'|, from bounds on |b|, |b'| and |b''|
101    /// carried through the turns (b ← R(b − c) + c: b' ← R b' + wJR(b − c),
102    /// b'' ← R b'' + 2wJR b' + w²J²R(b − c)).
103    fn accel_bound(&self, y: P2) -> f64 {
104        let (mut b, mut d1, mut d2, mut omega) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
105        for &(c, w) in &self.turns {
106            let arm = b + norm(c);
107            d2 += 2.0 * w.abs() * d1 + w * w * arm;
108            d1 += w.abs() * arm;
109            b += 2.0 * norm(c);
110            omega += w;
111        }
112        let omega = omega.abs();
113        let v = omega * (norm(y) + b) + d1;
114        (omega * v + omega * d1 + d2) * (1.0 + 1e-9) + 1e-300
115    }
116
117    /// Bounds on a material point's world speed and on the rate of its
118    /// velocity, for a point `x` of the tool: with y = R x + b, |y'| <=
119    /// |ω|·|x| + |b'| and |y''| <= ω²·|x| + |b''| (|b'| and |b''| bounded as
120    /// in [`Motion::accel_bound`]).
121    fn point_rate_bounds(&self, x: P2) -> (f64, f64) {
122        let (mut b, mut d1, mut d2, mut omega) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
123        for &(c, w) in &self.turns {
124            let arm = b + norm(c);
125            d2 += 2.0 * w.abs() * d1 + w * w * arm;
126            d1 += w.abs() * arm;
127            b += 2.0 * norm(c);
128            omega += w;
129        }
130        let omega = omega.abs();
131        ((omega * norm(x) + d1) * (1.0 + 1e-9), (omega * omega * norm(x) + d2) * (1.0 + 1e-9))
132    }
133
134    /// A bound on the preimage's speed for a world point `y`.
135    fn speed_bound(&self, y: P2) -> f64 {
136        let mut reach = norm(y);
137        for &(c, _) in &self.turns {
138            reach += 2.0 * norm(c);
139        }
140        self.turns.iter().map(|&(c, w)| w.abs() * (reach + norm(c))).sum::<f64>().max(1e-300)
141    }
142}
143
144/// The polygon (tool frame, counter-clockwise or not) and its signed distance.
145struct Polygon {
146    corners: Vec<P2>,
147}
148
149impl Polygon {
150    fn signed_distance(&self, p: P2) -> f64 {
151        let n = self.corners.len();
152        let mut best = f64::INFINITY;
153        let mut inside = false;
154        for k in 0..n {
155            let (a, b) = (self.corners[k], self.corners[(k + 1) % n]);
156            let e = sub(b, a);
157            let s = (dot(sub(p, a), e) / dot(e, e)).clamp(0.0, 1.0);
158            best = best.min(norm(sub(p, add(a, mul(e, s)))));
159            if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (p[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) {
160                inside = !inside;
161            }
162        }
163        if inside {
164            -best
165        } else {
166            best
167        }
168    }
169}
170
171/// The clip in the plane: an annulus (and an angle range) about the origin.
172struct Clip {
173    r: [f64; 2],
174    angle: Option<[f64; 2]>,
175}
176
177impl Clip {
178    fn holds(&self, y: P2) -> bool {
179        let r = norm(y);
180        if !(r > self.r[0] && r < self.r[1]) {
181            return false;
182        }
183        match self.angle {
184            None => true,
185            Some([a0, a1]) => {
186                let span = if a1 - a0 >= TAU { TAU } else { (a1 - a0).rem_euclid(TAU) };
187                let rel = (y[1].atan2(y[0]) - a0).rem_euclid(TAU);
188                rel > 0.0 && rel < span
189            }
190        }
191    }
192}
193
194/// A boundary candidate: an exact curve over [lo, hi].
195#[derive(Clone, Copy, Debug)]
196enum Kind {
197    /// The path of corner k.
198    Corner(usize),
199    /// The envelope of side k (from corner k to k + 1).
200    Envelope(usize),
201    /// Side k at the start (false) or end (true) position: parameter along it.
202    End(usize, bool),
203    /// A clip circle of radius r: parameter the angle.
204    Circle(f64),
205    /// A clip ray at angle a: parameter the radius.
206    Ray(f64),
207    /// Under turns about one centre: the circle of radius r about it that
208    /// corners and side feet at that distance run on (parameter the angle).
209    Orbit(f64),
210    /// Piece k of the target's outline (a line's fraction, an arc's angle).
211    Target(usize),
212}
213
214struct Curve {
215    kind: Kind,
216    lo: f64,
217    hi: f64,
218}
219
220struct Region<'a> {
221    motion: &'a Motion,
222    polygon: &'a Polygon,
223    clip: &'a Clip,
224    scale: f64,
225    /// A prism the region is cut from: the region is then what it holds
226    /// outside the sweep.
227    target: Option<&'a Target>,
228}
229
230impl Region<'_> {
231    /// Where on side k the velocity runs along it, at time t (a fraction of
232    /// the side; outside [0, 1] where the foot misses it).
233    fn foot(&self, k: usize, t: f64) -> f64 {
234        let n = self.polygon.corners.len();
235        let (a, b) = (self.motion.apply(t, self.polygon.corners[k]), self.motion.apply(t, self.polygon.corners[(k + 1) % n]));
236        let e = sub(b, a);
237        let normal = [e[1], -e[0]];
238        let (g0, g1) = (dot(normal, self.motion.velocity(t, a)), dot(normal, self.motion.velocity(t, b)));
239        if g0 == g1 {
240            f64::NAN
241        } else {
242            g0 / (g0 - g1)
243        }
244    }
245
246    fn eval(&self, kind: Kind, s: f64) -> P2 {
247        let n = self.polygon.corners.len();
248        let corner = |k: usize| self.polygon.corners[k % n];
249        match kind {
250            Kind::Corner(k) => self.motion.apply(s, corner(k)),
251            Kind::Envelope(k) => {
252                let f = self.foot(k, s).clamp(0.0, 1.0);
253                self.motion.apply(s, add(corner(k), mul(sub(corner(k + 1), corner(k)), f)))
254            }
255            Kind::End(k, end) => {
256                let t = if end { self.motion.t1 } else { self.motion.t0 };
257                self.motion.apply(t, add(corner(k), mul(sub(corner(k + 1), corner(k)), s)))
258            }
259            Kind::Circle(r) => [r * s.cos(), r * s.sin()],
260            Kind::Orbit(r) => {
261                let c = self.motion.turns[0].0;
262                [c[0] + r * s.cos(), c[1] + r * s.sin()]
263            }
264            Kind::Ray(a) => [s * a.cos(), s * a.sin()],
265            Kind::Target(k) => self.target.expect("a target's piece").eval(k, s),
266        }
267    }
268
269    /// Is `y` in the region: in the sweep (within the clip), or, cut from a
270    /// target, in the target and not in the sweep.
271    fn member(&self, y: P2) -> bool {
272        match self.target {
273            None => self.inside(y, 0.0),
274            Some(target) => target.holds(y) && !self.inside(y, 0.0),
275        }
276    }
277
278    /// Is `y` inside the swept region and the clip? The walk steps the time
279    /// by the polygon's signed distance over the preimage's speed bound, so it
280    /// skips no time at which the preimage is deeper than `margin`.
281    fn inside(&self, y: P2, margin: f64) -> bool {
282        if !self.clip.holds(y) {
283            return false;
284        }
285        if margin == 0.0 && region_walk_on() {
286            return self.inside_curved(y);
287        }
288        let speed = self.motion.speed_bound(y);
289        let (t0, t1) = (self.motion.t0, self.motion.t1);
290        let floor = (t1 - t0) * 1e-10;
291        let mut t = t0;
292        for _ in 0..5_000_000 {
293            let d = self.polygon.signed_distance(self.motion.invert(t, y));
294            if d < -margin {
295                return true;
296            }
297            if t >= t1 {
298                return false;
299            }
300            t = (t + ((d + margin) / speed).max(floor)).min(t1);
301        }
302        true
303    }
304}
305
306impl Region<'_> {
307    /// [`Region::inside`] (margin 0) by steps of second order: while the
308    /// preimage x is outside the polygon its distance to each side's segment
309    /// is convex in x, so over a step s it stays at least
310    /// d_k + (∇d_k·x')s − ½As² (A bounding |x''|); the step is the least s
311    /// at which any of these could reach zero. Near a tangential approach
312    /// (∇d_k·x' ≈ 0) that is √(2d/A), where a step of d over the speed bound
313    /// crawls.
314    fn inside_curved(&self, y: P2) -> bool {
315        let (t0, t1) = (self.motion.t0, self.motion.t1);
316        let accel = self.motion.accel_bound(y);
317        let floor = (t1 - t0) * 1e-10;
318        let corners = &self.polygon.corners;
319        let n = corners.len();
320        let mut t = t0;
321        for _ in 0..5_000_000 {
322            let (theta, b, dtheta, db) = self.motion.pose(t);
323            let r = sub(y, b);
324            let x = rot(r, -theta);
325            // x' = −R(−θ)·v, v the world velocity of the material point at y.
326            let xv = mul(rot(add(mul([-r[1], r[0]], dtheta), db), -theta), -1.0);
327            let mut inside = false;
328            let mut step = f64::INFINITY;
329            let mut touches = false;
330            for k in 0..n {
331                let (a, c) = (corners[k], corners[(k + 1) % n]);
332                let e = sub(c, a);
333                let length = norm(e);
334                let w = sub(x, a);
335                let f = dot(w, e) / (length * length);
336                if (a[1] > x[1]) != (c[1] > x[1]) && x[0] < a[0] + (x[1] - a[1]) / (c[1] - a[1]) * (c[0] - a[0]) {
337                    inside = !inside;
338                }
339                // The distance to the side's segment and a subgradient of it:
340                // off the side's middle, the side's own unit normal (the
341                // foot's offset there is all rounding near the side, and
342                // would point along it); off an end, from that corner.
343                let (d, gradient) = if f > 0.0 && f < 1.0 {
344                    let h = cross(e, w) / length;
345                    (h.abs(), mul([-e[1], e[0]], h.signum() / length))
346                } else {
347                    let off = if f <= 0.0 { w } else { sub(x, c) };
348                    let d = norm(off);
349                    (d, if d > 0.0 { mul(off, 1.0 / d) } else { [0.0, 0.0] })
350                };
351                // On the side exactly: no step but the floor's. (Near it the
352                // normal above is still the side's own, so a point that
353                // lingers close outside steps on by the curvature bound.)
354                if !(d > 0.0) {
355                    touches = true;
356                    continue;
357                }
358                let g = dot(gradient, xv);
359                step = step.min((g + (g * g + 2.0 * accel * d).sqrt()) / accel);
360            }
361            if inside && !touches {
362                return true;
363            }
364            if t >= t1 {
365                return false;
366            }
367            let step = if touches || !step.is_finite() { floor } else { step.max(floor) };
368            t = (t + step).min(t1);
369        }
370        true
371    }
372}
373
374/// The switch for [`Region::inside_curved`] (default on;
375/// `BREP_SWEEP_REGION_WALK=0` restores the first-order walk).
376pub fn region_walk_on() -> bool {
377    crate::switch!("BREP_SWEEP_REGION_WALK", true)
378}
379
380/// The switch for the side sampling bound in [`region_loops`] (default on;
381/// `BREP_SWEEP_REGION_SIDE_BOUND=0` samples every side on the common grid
382/// and never declines, as before).
383pub fn region_side_bound_on() -> bool {
384    crate::switch!("BREP_SWEEP_REGION_SIDE_BOUND", true)
385}
386
387/// One kept arc: its curve, its parameter range (run with the region on its
388/// left), and its end points.
389struct Arc {
390    kind: Kind,
391    a: f64,
392    b: f64,
393    start: P2,
394    end: P2,
395}
396
397/// The sweep of `tool` along `motion` within `clip` as exact planar regions,
398/// extruded; `None` where this construction does not apply (not a prism of
399/// straight sides, a step that is not a turn about an axis along the prism,
400/// a clip not along it).
401pub fn sweep_prism_planar_region(tool: &SweptTool, motion: &SolidMotion, clip: &SweepClip) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
402    let Some(prepared) = prepare(tool, motion, clip)? else { return Ok(None) };
403    let region = Region { motion: &prepared.motion, polygon: &prepared.polygon, clip: &prepared.clip, scale: prepared.scale, target: None };
404    let Some(loops) = region_loops(&region)? else { return Ok(None) };
405    if loops.is_empty() {
406        return Ok(Some(Vec::new()));
407    }
408    let solids = extrude(&region, &loops, clip.axial, &|p, z| prepared.lift(p, z))?;
409    Ok(Some(solids))
410}
411
412/// The region engine's inputs in the plane square to the clip's axis.
413struct Prepared {
414    motion: Motion,
415    polygon: Polygon,
416    clip: Clip,
417    scale: f64,
418    origin: Vec3,
419    frame: [Vec3; 3],
420}
421
422impl Prepared {
423    fn plane(&self, x: Vec3) -> P2 {
424        let d = x.sub(self.origin);
425        [d.dot(self.frame[0]), d.dot(self.frame[1])]
426    }
427    fn lift(&self, p: P2, z: f64) -> Vec3 {
428        self.origin.add(self.frame[0].scale(p[0])).add(self.frame[1].scale(p[1])).add(self.frame[2].scale(z))
429    }
430}
431
432fn prepare(tool: &SweptTool, motion: &SolidMotion, clip: &SweepClip) -> Result<Option<Prepared>, KernelRefusal> {
433    let SweptTool::Prism { origin, normal, x_axis, outline, from, to } = tool else { return Ok(None) };
434    if !outline.iter().all(|p| matches!(p, OutlinePiece::Line { .. })) || outline.len() < 3 {
435        return Ok(None);
436    }
437    // Each line must end where the next begins (else the level engine refuses
438    // the outline in its own words).
439    let size = outline.iter().map(|p| match p {
440        OutlinePiece::Line { from, .. } => from[0].abs().max(from[1].abs()),
441        _ => 0.0,
442    }).fold(1.0f64, f64::max);
443    let closes = (0..outline.len()).all(|k| match (&outline[k], &outline[(k + 1) % outline.len()]) {
444        (OutlinePiece::Line { to, .. }, OutlinePiece::Line { from, .. }) => (to[0] - from[0]).hypot(to[1] - from[1]) <= 1e-12 * size,
445        _ => false,
446    });
447    if !closes || motion.steps.iter().all(|step| step.turn == 0.0) {
448        return Ok(None);
449    }
450    // An invalid clip or range is the level engine's to refuse, in its words.
451    let finite = clip.radius.iter().chain(&clip.axial).all(|x| x.is_finite()) && motion.from.is_finite() && motion.to.is_finite();
452    if !(finite && clip.radius[0] >= 0.0 && clip.radius[1] > clip.radius[0] && clip.axial[1] > clip.axial[0] && motion.to > motion.from) {
453        return Ok(None);
454    }
455    let ez = clip.axis_direction.normalized().or_refuse(KernelStage::Collect, "clip_axis")?;
456    let n = normal.normalized().or_refuse(KernelStage::Collect, "prism_normal")?;
457    if n.cross(ez).length() > 1e-12 || motion.steps.is_empty() || !(motion.to > motion.from) {
458        return Ok(None);
459    }
460    let ex = clip.reference.sub(ez.scale(clip.reference.dot(ez))).normalized().or_refuse(KernelStage::Collect, "clip_reference")?;
461    let ey = ez.cross(ex);
462    let plane = |x: Vec3| -> P2 {
463        let d = x.sub(clip.axis_origin);
464        [d.dot(ex), d.dot(ey)]
465    };
466    let mut turns = Vec::new();
467    for ScrewStep { axis_origin, axis_direction, turn, advance } in &motion.steps {
468        let axis = axis_direction.normalized().or_refuse(KernelStage::Collect, "step_axis")?;
469        if *advance != 0.0 || axis.cross(ez).length() > 1e-12 {
470            return Ok(None);
471        }
472        turns.push((plane(*axis_origin), turn * axis.dot(ez).signum()));
473    }
474    // The clip's axial range must lie within the prism (as for the level engine).
475    let base = clip.axis_origin.sub(*origin).dot(n);
476    let sense = ez.dot(n);
477    let (h0, h1) = (base + sense * clip.axial[0], base + sense * clip.axial[1]);
478    if h0.min(h1) < *from || h0.max(h1) > *to {
479        return Ok(None);
480    }
481    let xa = x_axis.sub(n.scale(x_axis.dot(n))).normalized().or_refuse(KernelStage::Collect, "prism_x_axis")?;
482    let ya = n.cross(xa);
483    let mut corners: Vec<P2> = Vec::with_capacity(outline.len());
484    for piece in outline {
485        let OutlinePiece::Line { from: q, .. } = piece else { unreachable!() };
486        corners.push(plane(origin.add(xa.scale(q[0])).add(ya.scale(q[1]))));
487    }
488    let polygon = Polygon { corners };
489    let motion2 = Motion { turns, t0: motion.from, t1: motion.to };
490    // An angle range of a whole turn or more is no range.
491    let angle = clip.angle.filter(|[a0, a1]| a1 - a0 < TAU);
492    let clip2 = Clip { r: clip.radius, angle };
493    // Turns about one centre that cancel leave the tool still: not a sweep
494    // this construction draws.
495    let turns = &motion2.turns;
496    if let Some(&(c0, _)) = turns.first() {
497        let one = turns.iter().all(|(c, _)| norm(sub(*c, c0)) <= 1e-12 * norm(c0).max(1.0));
498        if one && turns.iter().map(|(_, w)| w).sum::<f64>().abs() <= 1e-15 * turns.iter().map(|(_, w)| w.abs()).sum::<f64>() {
499            return Ok(None);
500        }
501    }
502    // The geometry's own size: the corners, the turns' centres, and the clip
503    // only as far as the motion can reach (an oversized clip must not widen
504    // the probes past the tool).
505    let corner_reach = polygon.corners.iter().map(|c| norm(*c)).fold(0.0f64, f64::max);
506    let centres: f64 = motion2.turns.iter().map(|(c, _)| norm(*c)).sum();
507    let reach = corner_reach + 2.0 * centres;
508    let scale = corner_reach.max(motion2.turns.iter().map(|(c, _)| norm(*c)).fold(0.0f64, f64::max)).max(clip.radius[1].min(reach));
509    if clip.radius[1] - clip.radius[0] < 1e-6 * scale {
510        return Ok(None);
511    }
512    Ok(Some(Prepared { motion: motion2, polygon, clip: clip2, scale, origin: clip.axis_origin, frame: [ex, ey, ez] }))
513}
514
515/// The switch for [`cut_planar_sweep_from_prism`] (default on;
516/// `BREP_SWEEP_REGION_CUT=0` turns it off).
517pub fn region_cut_on() -> bool {
518    crate::switch!("BREP_SWEEP_REGION_CUT", true)
519}
520
521/// A prism along the clip's axis, its outline in the plane square to it
522/// (exact: lines and circular arcs, in that plane's coordinates).
523struct Target {
524    pieces: Vec<TargetPiece>,
525    /// The outline as y-monotone pieces (for membership).
526    monotone: Vec<(P2, P2, Option<(P2, f64, f64)>)>,
527    /// Radii of clip circles the target's outline covers whole (left out).
528    shadowed: Vec<f64>,
529}
530
531#[derive(Clone, Copy, Debug)]
532enum TargetPiece {
533    Line(P2, P2),
534    /// Centre, radius, and the angles from and to (either way round).
535    Arc(P2, f64, f64, f64),
536}
537
538impl Target {
539    fn eval(&self, k: usize, s: f64) -> P2 {
540        match self.pieces[k] {
541            TargetPiece::Line(a, b) => add(a, mul(sub(b, a), s)),
542            TargetPiece::Arc(c, r, _, _) => [c[0] + r * s.cos(), c[1] + r * s.sin()],
543        }
544    }
545    fn span(&self, k: usize) -> (f64, f64) {
546        match self.pieces[k] {
547            TargetPiece::Line(..) => (0.0, 1.0),
548            TargetPiece::Arc(_, _, a, b) => (a.min(b), a.max(b)),
549        }
550    }
551    /// Is `p` inside the outline? Crossings of the ray to +x, counted as a
552    /// polygon's sides are (a piece crosses where one end lies above p and
553    /// the other not), over y-monotone pieces: the lines, and the arcs split
554    /// at their highest and lowest points, each ending at the outline's own
555    /// shared corners so neighbours agree on which side of p a corner lies.
556    fn holds(&self, p: P2) -> bool {
557        let mut inside = false;
558        for &(a, b, arc) in &self.monotone {
559            if (a[1] > p[1]) == (b[1] > p[1]) {
560                continue;
561            }
562            let x = match arc {
563                None => a[0] + (p[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]),
564                Some((c, r, side)) => {
565                    let dy = p[1] - c[1];
566                    c[0] + side * (r * r - dy * dy).max(0.0).sqrt()
567                }
568            };
569            if p[0] < x {
570                inside = !inside;
571            }
572        }
573        inside
574    }
575
576    /// The outline's y-monotone pieces: (from, to, for an arc its centre,
577    /// radius and the side of the centre it runs on); `corners[k]` is where
578    /// piece k begins (and piece k − 1 ends).
579    fn monotone_pieces(pieces: &[TargetPiece], corners: &[P2]) -> Vec<(P2, P2, Option<(P2, f64, f64)>)> {
580        let n = pieces.len();
581        let mut out = Vec::new();
582        for k in 0..n {
583            let (start, end) = (corners[k], corners[(k + 1) % n]);
584            match pieces[k] {
585                TargetPiece::Line(..) => out.push((start, end, None)),
586                TargetPiece::Arc(c, r, a0, a1) => {
587                    // Angles of the arc's extremes in y, strictly inside its run.
588                    let (lo, hi) = (a0.min(a1), a0.max(a1));
589                    let mut breaks: Vec<f64> = Vec::new();
590                    let mut m = ((lo - std::f64::consts::FRAC_PI_2) / std::f64::consts::PI).floor() + 1.0;
591                    loop {
592                        let angle = std::f64::consts::FRAC_PI_2 + m * std::f64::consts::PI;
593                        if angle >= hi {
594                            break;
595                        }
596                        if angle > lo {
597                            breaks.push(angle);
598                        }
599                        m += 1.0;
600                    }
601                    if a1 < a0 {
602                        breaks.reverse();
603                    }
604                    let mut points = vec![(start, a0)];
605                    points.extend(breaks.iter().map(|&t| ([c[0] + r * t.cos(), c[1] + r * t.sin()], t)));
606                    points.push((end, a1));
607                    for w in points.windows(2) {
608                        let mid = 0.5 * (w[0].1 + w[1].1);
609                        out.push((w[0].0, w[1].0, Some((c, r, if mid.cos() >= 0.0 { 1.0 } else { -1.0 }))));
610                    }
611                }
612            }
613        }
614        out
615    }
616}
617
618/// Does a target piece run along one of the sweep's own boundary curves
619/// (where the two would both be kept, the boundary traced twice)? Under
620/// turns about one centre: an arc about it on a corner's or a side foot's
621/// orbit; at the motion's ends: a line along a side's end position.
622fn on_sweep_curve(prepared: &Prepared, pieces: &[TargetPiece], tolerance: f64) -> bool {
623    let motion = &prepared.motion;
624    let corners = &prepared.polygon.corners;
625    let n = corners.len();
626    let centre = motion.turns[0].0;
627    let one_centre = motion.turns.iter().all(|(c, _)| norm(sub(*c, centre)) <= 1e-12 * prepared.scale);
628    let mut orbits = Vec::new();
629    if one_centre {
630        for k in 0..n {
631            let (a, b) = (corners[k], corners[(k + 1) % n]);
632            orbits.push(norm(sub(motion.apply(motion.t0, a), centre)));
633            // The side's nearest point to the centre runs an orbit too.
634            let (pa, pb) = (motion.apply(motion.t0, a), motion.apply(motion.t0, b));
635            let e = sub(pb, pa);
636            let f = (dot(sub(centre, pa), e) / dot(e, e)).clamp(0.0, 1.0);
637            orbits.push(norm(sub(add(pa, mul(e, f)), centre)));
638        }
639    }
640    let mut sides = Vec::new();
641    for t in [motion.t0, motion.t1] {
642        for k in 0..n {
643            sides.push((motion.apply(t, corners[k]), motion.apply(t, corners[(k + 1) % n])));
644        }
645    }
646    pieces.iter().any(|piece| match *piece {
647        TargetPiece::Arc(c, r, ..) => one_centre && norm(sub(c, centre)) <= tolerance && orbits.iter().any(|&o| (o - r).abs() <= tolerance),
648        TargetPiece::Line(a, b) => sides.iter().any(|&(p, q)| {
649            let e = sub(q, p);
650            let length = norm(e);
651            if !(length > 0.0) {
652                return false;
653            }
654            let along = |x: P2| (cross(e, sub(x, p)) / length).abs() <= tolerance;
655            if !(along(a) && along(b)) {
656                return false;
657            }
658            // Collinear: overlapping by more than the tolerance?
659            let s = |x: P2| dot(sub(x, p), e) / length;
660            let (lo, hi) = (s(a).min(s(b)), s(a).max(s(b)));
661            hi.min(length) - lo.max(0.0) > tolerance
662        }),
663    })
664}
665
666/// Whether the clip-plane point `p` lies in what `tool` sweeps under
667/// `motion` within `clip`, by the region engine's membership walk; `None`
668/// where the engine does not take the sweep. (For tests.)
669#[doc(hidden)]
670pub fn swept_region_holds(tool: &SweptTool, motion: &SolidMotion, clip: &SweepClip, p: [f64; 2]) -> Result<Option<bool>, KernelRefusal> {
671    let Some(prepared) = prepare(tool, motion, clip)? else { return Ok(None) };
672    let region = Region { motion: &prepared.motion, polygon: &prepared.polygon, clip: &prepared.clip, scale: prepared.scale, target: None };
673    Ok(Some(region.inside(p, 0.0)))
674}
675
676/// Whether `p` lies inside a closed outline of lines and circular arcs (in
677/// the outline's own coordinates), as the region cut reads its target;
678/// `None` for an outline it does not take. (For tests.)
679#[doc(hidden)]
680pub fn target_outline_holds(outline: &[OutlinePiece], p: [f64; 2]) -> Option<bool> {
681    let mut pieces = Vec::new();
682    let mut corners = Vec::new();
683    for piece in outline {
684        match *piece {
685            OutlinePiece::Line { from, to } => {
686                pieces.push(TargetPiece::Line(from, to));
687                corners.push(from);
688            }
689            OutlinePiece::Arc { centre, radius, start, end } => {
690                pieces.push(TargetPiece::Arc(centre, radius, start, end));
691                corners.push([centre[0] + radius * start.cos(), centre[1] + radius * start.sin()]);
692            }
693            OutlinePiece::Ellipse { .. } => return None,
694        }
695    }
696    let monotone = Target::monotone_pieces(&pieces, &corners);
697    Some(Target { pieces, monotone, shadowed: Vec::new() }.holds(p))
698}
699
700/// The prism `target` less what `tool` sweeps under `motion` within `clip`,
701/// as one extrusion of the plane region the target's outline holds outside
702/// the swept region (exact where the sweep's own region engine is; behind
703/// [`region_cut_on`], default on). The same solid as subtracting
704/// [`sweep_prism_planar_region`]'s bodies from the target, without the 3D
705/// boolean: the sweep is taken within the clip only, as there.
706///
707/// `None` where it does not apply: the switch off, the sweep not one the
708/// region engine draws, a target that is not a prism along the clip's axis
709/// with an outline of lines and circular arcs end to end, or a target that
710/// runs past the clip's axial range.
711pub fn cut_planar_sweep_from_prism(target: &SweptTool, tool: &SweptTool, motion: &SolidMotion, clip: &SweepClip) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
712    if !region_cut_on() {
713        return Ok(None);
714    }
715    let SweptTool::Prism { origin, normal, x_axis, outline, from, to } = target else { return Ok(None) };
716    if outline.is_empty() || !(from.is_finite() && to.is_finite() && to > from) {
717        return Ok(None);
718    }
719    let Some(prepared) = prepare(tool, motion, clip)? else { return Ok(None) };
720    let ez = prepared.frame[2];
721    let Ok(n) = normal.normalized() else { return Ok(None) };
722    if n.cross(ez).length() > 1e-12 {
723        return Ok(None);
724    }
725    // The target's heights along the clip's axis, within the clip's range.
726    let base = origin.sub(prepared.origin).dot(ez);
727    let sense = n.dot(ez).signum();
728    let (h0, h1) = (base + sense * from, base + sense * to);
729    let axial = [h0.min(h1), h0.max(h1)];
730    let slack = 1e-12 * prepared.scale;
731    if axial[0] < clip.axial[0] - slack || axial[1] > clip.axial[1] + slack {
732        return Ok(None);
733    }
734    let Ok(xa) = x_axis.sub(n.scale(x_axis.dot(n))).normalized() else { return Ok(None) };
735    let ya = n.cross(xa);
736    let at = |q: [f64; 2]| prepared.plane(origin.add(xa.scale(q[0])).add(ya.scale(q[1])));
737    // The outline's angles in the plane: turned by the target's x axis, and
738    // mirrored where its normal runs against the clip's axis.
739    let offset = xa.dot(prepared.frame[1]).atan2(xa.dot(prepared.frame[0]));
740    let mut pieces = Vec::with_capacity(outline.len());
741    let mut ends: Vec<(P2, P2)> = Vec::with_capacity(outline.len());
742    for piece in outline {
743        match *piece {
744            OutlinePiece::Line { from: a, to: b } => {
745                let (a, b) = (at(a), at(b));
746                pieces.push(TargetPiece::Line(a, b));
747                ends.push((a, b));
748            }
749            OutlinePiece::Arc { centre, radius, start, end } => {
750                if !(radius > 0.0 && radius.is_finite() && start.is_finite() && end.is_finite()) || (end - start).abs() > TAU * (1.0 + 1e-12) || end == start {
751                    return Ok(None);
752                }
753                let c = at(centre);
754                let (a0, a1) = (offset + sense * start, offset + sense * end);
755                pieces.push(TargetPiece::Arc(c, radius, a0, a1));
756                ends.push(([c[0] + radius * a0.cos(), c[1] + radius * a0.sin()], [c[0] + radius * a1.cos(), c[1] + radius * a1.sin()]));
757            }
758            OutlinePiece::Ellipse { .. } => return Ok(None),
759        }
760    }
761    let size = ends.iter().flat_map(|(a, b)| [norm(*a), norm(*b)]).fold(prepared.scale, f64::max);
762    let closes = (0..ends.len()).all(|k| norm(sub(ends[k].1, ends[(k + 1) % ends.len()].0)) <= 1e-9 * size);
763    if !closes {
764        return Ok(None);
765    }
766    // The region's tolerances and probes follow the sweep's scale: a target
767    // far smaller or larger than it is not drawn here.
768    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
769    for (k, piece) in pieces.iter().enumerate() {
770        let mut take = |q: P2| {
771            for i in 0..2 {
772                lo[i] = lo[i].min(q[i]);
773                hi[i] = hi[i].max(q[i]);
774            }
775        };
776        take(ends[k].0);
777        if let TargetPiece::Arc(c, r, ..) = piece {
778            take([c[0] - r, c[1] - r]);
779            take([c[0] + r, c[1] + r]);
780        }
781    }
782    let extent = (hi[0] - lo[0]).hypot(hi[1] - lo[1]);
783    if !(extent >= 1e-2 * prepared.scale && extent <= 1e2 * prepared.scale) {
784        return Ok(None);
785    }
786    // A target piece along a clip curve: a whole circle about the clip's
787    // axis on a clip circle stands for it (the clip's circle is left out);
788    // any other overlap (part of a circle, a side along a clip ray) is not
789    // drawn here.
790    let tolerance = 1e-9 * prepared.scale;
791    let mut shadowed = Vec::new();
792    for piece in &pieces {
793        match *piece {
794            TargetPiece::Arc(c, r, a0, a1) => {
795                if norm(c) <= tolerance {
796                    if let Some(&radius) = prepared.clip.r.iter().find(|&&radius| (radius - r).abs() <= tolerance) {
797                        if prepared.clip.angle.is_none() && (a1 - a0).abs() >= TAU * (1.0 - 1e-12) {
798                            shadowed.push(radius);
799                        } else {
800                            return Ok(None);
801                        }
802                    }
803                }
804            }
805            TargetPiece::Line(a, b) => {
806                if let Some([r0, r1]) = prepared.clip.angle {
807                    for ray in [r0, r1] {
808                        let d = [ray.cos(), ray.sin()];
809                        if cross(d, a).abs() <= tolerance && cross(d, b).abs() <= tolerance {
810                            return Ok(None);
811                        }
812                    }
813                }
814            }
815        }
816    }
817    if on_sweep_curve(&prepared, &pieces, tolerance) {
818        return Ok(None);
819    }
820    let corners: Vec<P2> = ends.iter().map(|e| e.0).collect();
821    let monotone = Target::monotone_pieces(&pieces, &corners);
822    let target = Target { pieces, monotone, shadowed };
823    let region = Region { motion: &prepared.motion, polygon: &prepared.polygon, clip: &prepared.clip, scale: prepared.scale, target: Some(&target) };
824    let Some(loops) = region_loops(&region)? else { return Ok(None) };
825    if loops.is_empty() {
826        return Ok(Some(Vec::new()));
827    }
828    Ok(Some(extrude(&region, &loops, axial, &|p, z| prepared.lift(p, z))?))
829}
830
831/// The region's boundary loops (each counter-clockwise about its inside).
832///
833/// A side's foot lies on it while its normal velocity summed at its two ends,
834/// G, is within ω·|e|² of zero (ω the net turn rate, e the side), and G moves
835/// at most L = |e|·(ω(|a'| + |b'|) + |a''| + |b''|): a run about any zero of G
836/// lasts ω|e|²/L to either side, so samples that far apart see every run
837/// through a zero and no sign change of G slips between two samples. A side
838/// whose bound asks for more than a million samples (ω all but zero: turns
839/// that cancel leave a translation along a curve, whose boundary takes a
840/// whole side at an instant, no envelope this engine draws) is declined:
841/// `None`.
842fn region_loops(region: &Region) -> Result<Option<Vec<Vec<Arc>>>, KernelRefusal> {
843    let motion = region.motion;
844    let polygon = region.polygon;
845    let n = polygon.corners.len();
846    let (t0, t1) = (motion.t0, motion.t1);
847    let scale = region.scale;
848    // Does the motion end where it began, as a set (every corner at the end on
849    // some corner at the start)? Then there are no end positions.
850    let closed = (0..n).all(|k| {
851        let end = motion.apply(t1, polygon.corners[k]);
852        (0..n).any(|j| norm(sub(end, motion.apply(t0, polygon.corners[j]))) <= 1e-9 * scale)
853    });
854    // Sample density: by the fastest point's travel.
855    let travel = motion.speed_bound([0.0, 0.0]) * (t1 - t0);
856    let samples = ((travel / (1e-3 * scale)).ceil() as usize).clamp(2000, 200_000);
857    let mut curves: Vec<Curve> = Vec::new();
858    // Turns about one centre: every corner path and side envelope is an arc
859    // of a circle about it, and those at one distance coincide; each distance
860    // gets one curve over the union of its arcs.
861    let centre = motion.turns[0].0;
862    let one_centre = motion.turns.iter().all(|(c, _)| norm(sub(*c, centre)) <= 1e-12 * scale);
863    if one_centre {
864        let rate: f64 = motion.turns.iter().map(|(_, w)| w).sum();
865        let mut arcs_at: Vec<(f64, f64, f64)> = Vec::new(); // (radius, angle from, angle to)
866        let mut push = |x: P2| {
867            let at = motion.apply(t0, x);
868            let r = norm(sub(at, centre));
869            let a = (at[1] - centre[1]).atan2(at[0] - centre[0]);
870            let (a0, a1) = (a, a + rate * (t1 - t0));
871            arcs_at.push((r, a0.min(a1), a0.max(a1)));
872        };
873        for k in 0..n {
874            push(polygon.corners[k]);
875            // A side's foot is fixed on it: inside the side, it runs a circle.
876            let f = region.foot(k, t0);
877            if f > 0.0 && f < 1.0 {
878                let (a, b) = (polygon.corners[k], polygon.corners[(k + 1) % n]);
879                push(add(a, mul(sub(b, a), f)));
880            }
881        }
882        arcs_at.sort_by(|x, y| x.0.total_cmp(&y.0));
883        let mut i = 0;
884        while i < arcs_at.len() {
885            let mut j = i;
886            while j + 1 < arcs_at.len() && (arcs_at[j + 1].0 - arcs_at[i].0).abs() <= 1e-12 * scale {
887                j += 1;
888            }
889            let r = arcs_at[i].0;
890            // Union of the angle intervals on the circle.
891            let mut spans: Vec<(f64, f64)> = arcs_at[i..=j].iter().map(|x| {
892                let lo = x.1.rem_euclid(TAU);
893                (lo, lo + (x.2 - x.1))
894            }).collect();
895            spans.sort_by(|x, y| x.0.total_cmp(&y.0));
896            let mut merged: Vec<(f64, f64)> = Vec::new();
897            for (lo, hi) in spans {
898                match merged.last_mut() {
899                    Some(last) if lo <= last.1 => last.1 = last.1.max(hi),
900                    _ => merged.push((lo, hi)),
901                }
902            }
903            // The last may wrap onto the first.
904            if merged.len() > 1 {
905                let first = merged[0];
906                let last = *merged.last().expect("merged");
907                if last.1 >= first.0 + TAU {
908                    merged.remove(0);
909                    let l = merged.last_mut().expect("merged");
910                    l.1 = l.1.max(first.1 + TAU);
911                }
912            }
913            for (lo, hi) in merged {
914                let hi = hi.min(lo + TAU);
915                if r > 0.0 && hi > lo {
916                    curves.push(Curve { kind: Kind::Orbit(r), lo, hi });
917                }
918            }
919            i = j + 1;
920        }
921    }
922    for k in 0..n {
923        if one_centre {
924            if !closed {
925                curves.push(Curve { kind: Kind::End(k, false), lo: 0.0, hi: 1.0 });
926                curves.push(Curve { kind: Kind::End(k, true), lo: 0.0, hi: 1.0 });
927            }
928            continue;
929        }
930        curves.push(Curve { kind: Kind::Corner(k), lo: t0, hi: t1 });
931        // Envelope runs: where the foot lies on the side, sampled at most the
932        // bound's spacing apart (the common grid where that is finer).
933        let mut side_samples = samples;
934        if region_side_bound_on() {
935            let (a, b) = (polygon.corners[k], polygon.corners[(k + 1) % n]);
936            let omega = motion.turns.iter().map(|(_, w)| w).sum::<f64>().abs();
937            let length = norm(sub(b, a));
938            let ((va, aa), (vb, ab)) = (motion.point_rate_bounds(a), motion.point_rate_bounds(b));
939            let reach = omega * length / (omega * (va + vb) + aa + ab).max(1e-300);
940            let need = (t1 - t0) / reach;
941            if !(need <= 1e6) {
942                return Ok(None);
943            }
944            if need > samples as f64 {
945                side_samples = need.ceil() as usize + 1;
946            }
947        }
948        let ts: Vec<f64> = (0..=side_samples).map(|i| t0 + (t1 - t0) * i as f64 / side_samples as f64).collect();
949        let on = |t: f64| {
950            let f = region.foot(k, t);
951            (0.0..=1.0).contains(&f)
952        };
953        let flags: Vec<bool> = ts.iter().map(|&t| on(t)).collect();
954        let edge = |mut tin: f64, mut tout: f64| {
955            for _ in 0..80 {
956                let m = 0.5 * (tin + tout);
957                if on(m) {
958                    tin = m;
959                } else {
960                    tout = m;
961                }
962            }
963            tin
964        };
965        let mut i = 0;
966        while i < ts.len() {
967            if !flags[i] {
968                i += 1;
969                continue;
970            }
971            let mut j = i;
972            while j + 1 < ts.len() && flags[j + 1] {
973                j += 1;
974            }
975            let lo = if i == 0 { ts[0] } else { edge(ts[i], ts[i - 1]) };
976            let hi = if j == ts.len() - 1 { ts[j] } else { edge(ts[j], ts[j + 1]) };
977            if hi > lo {
978                curves.push(Curve { kind: Kind::Envelope(k), lo, hi });
979            }
980            i = j + 1;
981        }
982        if !closed {
983            curves.push(Curve { kind: Kind::End(k, false), lo: 0.0, hi: 1.0 });
984            curves.push(Curve { kind: Kind::End(k, true), lo: 0.0, hi: 1.0 });
985        }
986    }
987    let clip = region.clip;
988    // Every pose keeps the polygon within this distance of the clip's axis
989    // (a turn about c moves a point by at most 2|c| further out): clip curves
990    // beyond it meet nothing and are left out.
991    let reach = polygon.corners.iter().map(|c| norm(*c)).fold(0.0f64, f64::max) + 2.0 * motion.turns.iter().map(|(c, _)| norm(*c)).sum::<f64>();
992    let shadowed = |r: f64| region.target.is_some_and(|t| t.shadowed.contains(&r));
993    let within = |r: f64| r > 0.0 && r <= reach * (1.0 + 1e-12) && !shadowed(r);
994    match clip.angle {
995        None => {
996            for r in clip.r {
997                if within(r) {
998                    curves.push(Curve { kind: Kind::Circle(r), lo: 0.0, hi: TAU });
999                }
1000            }
1001        }
1002        Some([a0, a1]) => {
1003            let a1 = a0 + (a1 - a0).rem_euclid(TAU);
1004            for r in clip.r {
1005                if within(r) {
1006                    curves.push(Curve { kind: Kind::Circle(r), lo: a0, hi: a1 });
1007                }
1008            }
1009            // Past the reach by a margin: a ray must not end on a curve it crosses.
1010            let hi = clip.r[1].min(1.1 * reach);
1011            if hi > clip.r[0] {
1012                for a in [a0, a1] {
1013                    curves.push(Curve { kind: Kind::Ray(a), lo: clip.r[0], hi });
1014                }
1015            }
1016        }
1017    }
1018    if let Some(target) = region.target {
1019        for k in 0..target.pieces.len() {
1020            let (lo, hi) = target.span(k);
1021            curves.push(Curve { kind: Kind::Target(k), lo, hi });
1022        }
1023    }
1024    // Sample every curve.
1025    let per = |c: &Curve| -> usize {
1026        match c.kind {
1027            Kind::Target(k) => match region.target.expect("a target's piece").pieces[k] {
1028                TargetPiece::Arc(_, r, ..) => ((r * (c.hi - c.lo) / (1e-3 * scale)).ceil() as usize).clamp(64, 200_000),
1029                // Segments no longer than the least crossing cell (a long
1030                // side's segments would each fill a box of cells).
1031                TargetPiece::Line(a, b) => ((norm(sub(b, a)) / (1e-3 * scale)).ceil() as usize).clamp(64, 200_000),
1032            },
1033            Kind::Corner(_) | Kind::Envelope(_) => (((c.hi - c.lo) / (t1 - t0) * samples as f64).ceil() as usize).max(64),
1034            Kind::Circle(r) | Kind::Orbit(r) => ((r * (c.hi - c.lo) / (1e-3 * scale)).ceil() as usize).clamp(64, 200_000),
1035            _ => 64,
1036        }
1037    };
1038    let sampled: Vec<(Vec<f64>, Vec<P2>)> = curves
1039        .iter()
1040        .map(|c| {
1041            let m = per(c);
1042            let ts: Vec<f64> = (0..=m).map(|i| c.lo + (c.hi - c.lo) * i as f64 / m as f64).collect();
1043            let ps = ts.iter().map(|&t| region.eval(c.kind, t)).collect();
1044            (ts, ps)
1045        })
1046        .collect();
1047    // Crossings: segments bucketed on a grid, each hit solved on the exact curves.
1048    // Cells about two segments long (between a thousandth and a hundredth of
1049    // the scale): a crossing is found in the cell holding it whatever the
1050    // size, and cells much longer than the segments fill with pairs that
1051    // cannot meet (where many paths run close, 20M pairs for 504 crossings).
1052    let (count, length) = sampled.iter().flat_map(|(_, ps)| ps.windows(2)).fold((0usize, 0.0f64), |(n, l), w| (n + 1, l + norm(sub(w[1], w[0]))));
1053    let mean = if count > 0 { length / count as f64 } else { 0.0 };
1054    let cell = (2.0 * mean).clamp(1e-3 * scale, 1e-2 * scale);
1055    // The cell index of a coordinate: floor(x / cell) (in integers, as
1056    // f64::floor would give it, without the library's floor).
1057    let index = |x: f64| -> i64 {
1058        let q = x / cell;
1059        let i = q as i64;
1060        if (i as f64) > q {
1061            i - 1
1062        } else {
1063            i
1064        }
1065    };
1066    // Segments by cell, sorted by cell (each cell's run is its bucket).
1067    let mut grid: Vec<((i64, i64), usize, usize)> = Vec::new();
1068    for (ci, (_, ps)) in sampled.iter().enumerate() {
1069        for k in 0..ps.len() - 1 {
1070            let (p, q) = (ps[k], ps[k + 1]);
1071            let (gx0, gx1) = (index(p[0].min(q[0])), index(p[0].max(q[0])));
1072            let (gy0, gy1) = (index(p[1].min(q[1])), index(p[1].max(q[1])));
1073            for gx in gx0..=gx1 {
1074                for gy in gy0..=gy1 {
1075                    grid.push(((gx, gy), ci, k));
1076                }
1077            }
1078        }
1079    }
1080    grid.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1081    let buckets = grid.chunk_by(|a, b| a.0 == b.0);
1082    let mut splits: Vec<Vec<f64>> = vec![Vec::new(); curves.len()];
1083    // A segment's cell range; a pair is tested once, in the lowest cell both share.
1084    let cells = |ci: usize, k: usize| -> (i64, i64) {
1085        let (p, q) = (sampled[ci].1[k], sampled[ci].1[k + 1]);
1086        (index(p[0].min(q[0])), index(p[1].min(q[1])))
1087    };
1088    for items in buckets {
1089        let (gx, gy) = items[0].0;
1090        for x in 0..items.len() {
1091            for y in x + 1..items.len() {
1092                let ((_, ci, k), (_, cj, l)) = (items[x], items[y]);
1093                if ci == cj && k.abs_diff(l) <= 1 {
1094                    continue;
1095                }
1096                let ((ax, ay), (bx, by)) = (cells(ci, k), cells(cj, l));
1097                if ax.max(bx) != gx || ay.max(by) != gy {
1098                    continue;
1099                }
1100                let (ts_i, ps_i) = &sampled[ci];
1101                let (ts_j, ps_j) = &sampled[cj];
1102                let (p, q, r, s) = (ps_i[k], ps_i[k + 1], ps_j[l], ps_j[l + 1]);
1103                let (d1, d2) = (sub(q, p), sub(s, r));
1104                let den = cross(d1, d2);
1105                if den.abs() < 1e-300 {
1106                    continue;
1107                }
1108                let w = sub(r, p);
1109                let (u, v) = (cross(w, d2) / den, cross(w, d1) / den);
1110                if !((0.0..1.0).contains(&u) && (0.0..1.0).contains(&v)) {
1111                    continue;
1112                }
1113                let mut ta = ts_i[k] + u * (ts_i[k + 1] - ts_i[k]);
1114                let mut tb = ts_j[l] + v * (ts_j[l + 1] - ts_j[l]);
1115                let (ka, kb) = (curves[ci].kind, curves[cj].kind);
1116                for _ in 0..40 {
1117                    let f = sub(region.eval(ka, ta), region.eval(kb, tb));
1118                    let (ha, hb) = (1e-7 * (curves[ci].hi - curves[ci].lo), 1e-7 * (curves[cj].hi - curves[cj].lo));
1119                    let ja = scale_p(sub(region.eval(ka, ta + ha), region.eval(ka, ta - ha)), 0.5 / ha);
1120                    let jb = scale_p(sub(region.eval(kb, tb + hb), region.eval(kb, tb - hb)), 0.5 / hb);
1121                    let det = cross(ja, mul(jb, -1.0));
1122                    if det.abs() < 1e-300 {
1123                        break;
1124                    }
1125                    // [ja, −jb] (da, db) = −f
1126                    let da = cross(mul(f, -1.0), mul(jb, -1.0)) / det;
1127                    let db = cross(ja, mul(f, -1.0)) / det;
1128                    ta += da;
1129                    tb += db;
1130                    if da.abs() + db.abs() < 1e-15 * (1.0 + ta.abs() + tb.abs()) {
1131                        break;
1132                    }
1133                }
1134                let gap = norm(sub(region.eval(ka, ta), region.eval(kb, tb)));
1135                // An envelope touches its side's corner paths tangentially at
1136                // its ends (added below, exactly): a near-touch there is that.
1137                let end_touch = |e: usize, other: Kind, te: f64| -> bool {
1138                    let Kind::Envelope(k) = curves[e].kind else { return false };
1139                    let own = matches!(other, Kind::Corner(j) if j == k || j == (k + 1) % n);
1140                    let span = curves[e].hi - curves[e].lo;
1141                    own && ((te - curves[e].lo).abs() < 1e-2 * span || (curves[e].hi - te).abs() < 1e-2 * span)
1142                };
1143                if gap > 1e-9 * scale && (end_touch(ci, kb, ta) || end_touch(cj, ka, tb)) {
1144                    continue;
1145                }
1146                if gap > 1e-9 * scale {
1147                    return Err(refuse("planar_crossing", format!("two boundary curves' crossing did not solve: {ka:?} at {ta} and {kb:?} at {tb}, gap {gap:.3e} (from samples {} / {})", ts_i[k], ts_j[l])));
1148                }
1149                splits[ci].push(ta);
1150                splits[cj].push(tb);
1151            }
1152        }
1153    }
1154    // Where the motion has ends, a side's envelope (or, about one centre, its
1155    // foot's orbit) meets that side's end position tangentially, at its foot.
1156    if !closed {
1157        for k in 0..n {
1158            for (end, t) in [(false, t0), (true, t1)] {
1159                let f = region.foot(k, t);
1160                let reaches = one_centre || curves.iter().any(|c| matches!(c.kind, Kind::Envelope(j) if j == k) && ((t - c.lo).abs() <= 1e-12 * (t1 - t0) || (c.hi - t).abs() <= 1e-12 * (t1 - t0)));
1161                if reaches && f > 0.0 && f < 1.0 {
1162                    if let Some(cj) = curves.iter().position(|c| matches!(c.kind, Kind::End(j, e) if j == k && e == end)) {
1163                        splits[cj].push(f);
1164                    }
1165                }
1166            }
1167        }
1168    }
1169    // An envelope's ends lie on its side's corner paths (tangent there).
1170    for ci in 0..curves.len() {
1171        if let Kind::Envelope(k) = curves[ci].kind {
1172            for t in [curves[ci].lo, curves[ci].hi] {
1173                let corner = if region.foot(k, t) < 0.5 { k } else { (k + 1) % n };
1174                if let Some(cj) = curves.iter().position(|c| matches!(c.kind, Kind::Corner(j) if j == corner)) {
1175                    splits[cj].push(t);
1176                }
1177            }
1178        }
1179    }
1180    // Arcs: kept where membership differs across them.
1181    // Probes beside an arc: well inside any feature the clip allows (a clip
1182    // thinner than a millionth of the scale is declined above).
1183    let eps = (1e-7 * scale).min(1e-3 * (region.clip.r[1] - region.clip.r[0]));
1184    let mut arcs = Vec::new();
1185    for (ci, c) in curves.iter().enumerate() {
1186        let mut ps: Vec<f64> = splits[ci].iter().copied().filter(|t| *t > c.lo && *t < c.hi).collect();
1187        ps.push(c.lo);
1188        ps.push(c.hi);
1189        ps.sort_by(|a, b| a.total_cmp(b));
1190        ps.dedup_by(|b, a| (*b - *a).abs() <= 1e-13 * (c.hi - c.lo));
1191        for w in ps.windows(2) {
1192            let (a, b) = (w[0], w[1]);
1193            let m = 0.5 * (a + b);
1194            let y = region.eval(c.kind, m);
1195            let h = 1e-6 * (b - a);
1196            let d = sub(region.eval(c.kind, m + h), region.eval(c.kind, m - h));
1197            let nd = norm(d);
1198            if !(nd > 0.0) {
1199                continue;
1200            }
1201            let left = [-d[1] / nd, d[0] / nd];
1202            let (l, r) = (region.member(add(y, mul(left, eps))), region.member(add(y, mul(left, -eps))));
1203            if l == r {
1204                continue;
1205            }
1206            let (a, b) = if l { (a, b) } else { (b, a) };
1207            arcs.push(Arc { kind: c.kind, a, b, start: region.eval(c.kind, a), end: region.eval(c.kind, b) });
1208        }
1209    }
1210    // Chain the arcs into loops by their end points.
1211    let tolerance = 1e-7 * scale;
1212    let mut used = vec![false; arcs.len()];
1213    let mut loops: Vec<Vec<usize>> = Vec::new();
1214    for first in 0..arcs.len() {
1215        if used[first] {
1216            continue;
1217        }
1218        used[first] = true;
1219        let mut chain = vec![first];
1220        loop {
1221            let tail = arcs[*chain.last().expect("chain")].end;
1222            if norm(sub(tail, arcs[first].start)) <= tolerance && chain.len() > 1 {
1223                break;
1224            }
1225            let next = (0..arcs.len()).filter(|&k| !used[k]).min_by(|&x, &y| norm(sub(arcs[x].start, tail)).total_cmp(&norm(sub(arcs[y].start, tail))));
1226            match next {
1227                Some(k) if norm(sub(arcs[k].start, tail)) <= tolerance => {
1228                    used[k] = true;
1229                    chain.push(k);
1230                }
1231                _ => {
1232                    if norm(sub(tail, arcs[first].start)) <= tolerance {
1233                        break;
1234                    }
1235                    let open: Vec<String> = chain.iter().map(|&k| format!("{:?} {:.6}..{:.6} {:?}->{:?}", arcs[k].kind, arcs[k].a, arcs[k].b, arcs[k].start, arcs[k].end)).collect();
1236                    let nearest = (0..arcs.len()).filter(|&k| !used[k]).map(|k| (norm(sub(arcs[k].start, tail)), k)).min_by(|a, b| a.0.total_cmp(&b.0));
1237                    return Err(refuse("planar_loops", format!("the region's boundary arcs do not close into loops: {} arcs, chain {open:?}, nearest start {:?}", arcs.len(), nearest.map(|(d, k)| (d, arcs[k].kind, arcs[k].start)))));
1238                }
1239            }
1240        }
1241        loops.push(chain);
1242    }
1243    let mut arcs: Vec<Option<Arc>> = arcs.into_iter().map(Some).collect();
1244    Ok(Some(loops.into_iter().map(|chain| chain.into_iter().map(|k| arcs[k].take().expect("once")).collect()).collect()))
1245}
1246
1247fn scale_p(a: P2, s: f64) -> P2 {
1248    mul(a, s)
1249}
1250
1251/// An arc as a planar curve (in the plane's coordinates, z = 0) over [0, 1]:
1252/// a line or circle exactly, any other interpolated (quintic) through exact
1253/// points, doubled until its midpoints miss by under 1e-10 of the scale.
1254fn arc_curve(region: &Region, arc: &Arc) -> Result<NurbsCurve, KernelRefusal> {
1255    let p3 = |p: P2| Vec3::new(p[0], p[1], 0.0);
1256    match arc.kind {
1257        Kind::End(..) | Kind::Ray(_) => return frag(make_line(p3(arc.start), p3(arc.end)), "planar_line"),
1258        Kind::Target(k) => match region.target.expect("a target's piece").pieces[k] {
1259            TargetPiece::Line(..) => return frag(make_line(p3(arc.start), p3(arc.end)), "planar_line"),
1260            TargetPiece::Arc(c, r, ..) => {
1261                let (x, y) = (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0));
1262                let (lo, hi) = (arc.a.min(arc.b), arc.a.max(arc.b));
1263                let curve = frag(crate::make_arc(p3(c), x, y, r, lo, hi), "planar_arc")?;
1264                return if arc.a <= arc.b { Ok(curve) } else { frag(curve.reversed(), "planar_arc") };
1265            }
1266        },
1267        _ => {}
1268    }
1269    let mut count = 32usize;
1270    loop {
1271        let params: Vec<f64> = (0..=count).map(|i| i as f64 / count as f64).collect();
1272        let points: Vec<Vec3> = params.iter().map(|&u| p3(region.eval(arc.kind, arc.a + (arc.b - arc.a) * u))).collect();
1273        let curve = frag(crate::interpolate_curve(&points, 5, &params), "planar_curve")?;
1274        let mut worst = 0.0f64;
1275        for i in 0..count {
1276            let u = (i as f64 + 0.5) / count as f64;
1277            let exact = p3(region.eval(arc.kind, arc.a + (arc.b - arc.a) * u));
1278            worst = worst.max(frag(curve.evaluate(u), "planar_curve")?.sub(exact).length());
1279        }
1280        if worst <= 1e-10 * region.scale || count >= 8192 {
1281            if worst > 1e-7 * region.scale {
1282                return Err(refuse("planar_fit", format!("a boundary arc's fit misses by {worst:.2e}")));
1283            }
1284            return Ok(curve);
1285        }
1286        count *= 2;
1287    }
1288}
1289
1290/// Green's area of one loop (counter-clockwise positive), by exact samples.
1291fn loop_area(region: &Region, arcs: &[Arc]) -> f64 {
1292    let mut area = 0.0;
1293    for arc in arcs {
1294        let m = 4096;
1295        let mut previous = region.eval(arc.kind, arc.a);
1296        for i in 1..=m {
1297            // Simpson on x dy − y dx per pair of steps would be finer; the
1298            // samples are dense enough for the check this serves.
1299            let p = region.eval(arc.kind, arc.a + (arc.b - arc.a) * i as f64 / m as f64);
1300            area += 0.5 * cross(previous, p);
1301            previous = p;
1302        }
1303    }
1304    area
1305}
1306
1307/// Extrude the loops (outer loops with the holes inside them) over the clip's
1308/// axial range: one solid per outer loop.
1309fn extrude(region: &Region, loops: &[Vec<Arc>], axial: [f64; 2], lift: &dyn Fn(P2, f64) -> Vec3) -> Result<Vec<BrepSolid>, KernelRefusal> {
1310    let areas: Vec<f64> = loops.iter().map(|l| loop_area(region, l)).collect();
1311    let outers: Vec<usize> = (0..loops.len()).filter(|&k| areas[k] > 0.0).collect();
1312    // Each hole goes to the smallest outer loop holding its first point.
1313    let holds = |outer: usize, p: P2| -> bool {
1314        let mut inside = false;
1315        let pts: Vec<P2> = loops[outer].iter().flat_map(|arc| (0..64).map(move |i| region.eval(arc.kind, arc.a + (arc.b - arc.a) * i as f64 / 64.0))).collect();
1316        let n = pts.len();
1317        for k in 0..n {
1318            let (a, b) = (pts[k], pts[(k + 1) % n]);
1319            if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (p[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) {
1320                inside = !inside;
1321            }
1322        }
1323        inside
1324    };
1325    let mut groups: Vec<(usize, Vec<usize>)> = outers.iter().map(|&o| (o, Vec::new())).collect();
1326    for h in (0..loops.len()).filter(|&k| areas[k] <= 0.0) {
1327        let p = loops[h][0].start;
1328        let owner = groups.iter_mut().filter(|g| holds(g.0, p)).min_by(|a, b| areas[a.0].total_cmp(&areas[b.0]));
1329        match owner {
1330            Some(g) => g.1.push(h),
1331            None => return Err(refuse("planar_loops", "a hole of the region lies in no outer loop".into())),
1332        }
1333    }
1334    let (z0, z1) = (axial[0], axial[1]);
1335    let height = z1 - z0;
1336    let mut solids = Vec::new();
1337    for (outer, holes) in groups {
1338        let mut next = 1u64;
1339        let mut id = || {
1340            next += 1;
1341            next
1342        };
1343        let members: Vec<usize> = std::iter::once(outer).chain(holes.iter().copied()).collect();
1344        let mut vertices = Vec::new();
1345        let mut edges = Vec::new();
1346        let mut faces = Vec::new();
1347        let mut bottom_loops = Vec::new();
1348        let mut top_loops = Vec::new();
1349        let mut expected = 0.0;
1350        for &l in &members {
1351            expected += areas[l] * height;
1352            let arcs = &loops[l];
1353            let m = arcs.len();
1354            // Corner vertices (bottom, top) and their upright edges.
1355            let mut low = Vec::with_capacity(m);
1356            let mut high = Vec::with_capacity(m);
1357            let mut uprights = Vec::with_capacity(m);
1358            for arc in arcs {
1359                let (a, b) = (lift(arc.start, z0), lift(arc.start, z1));
1360                let (va, vb) = (id(), id());
1361                vertices.push(VertexRecord { id: va, point: a });
1362                vertices.push(VertexRecord { id: vb, point: b });
1363                let e = id();
1364                edges.push(EdgeRecord { id: e, curve: frag(make_line(a, b), "planar_upright")?, t0: 0.0, t1: 1.0, start_vertex_id: va, end_vertex_id: vb, degenerate: false, name: None });
1365                low.push(va);
1366                high.push(vb);
1367                uprights.push(e);
1368            }
1369            let mut bottom = Vec::new();
1370            let mut top = Vec::new();
1371            for (i, arc) in arcs.iter().enumerate() {
1372                let j = (i + 1) % m;
1373                let plane = arc_curve(region, arc)?;
1374                let at = |z: f64| -> Result<NurbsCurve, KernelRefusal> {
1375                    let points: Vec<Vec4> = plane
1376                        .control_points
1377                        .iter()
1378                        .map(|c| {
1379                            let p = c.point().unwrap_or(Vec3::new(0.0, 0.0, 0.0));
1380                            Vec4::from_point(lift([p.x, p.y], z), c.w)
1381                        })
1382                        .collect();
1383                    frag(NurbsCurve::new(plane.degree, plane.knots.clone(), points), "planar_lift")
1384                };
1385                let (cb, ct) = (at(z0)?, at(z1)?);
1386                let (eb, et) = (id(), id());
1387                edges.push(EdgeRecord { id: eb, curve: cb.clone(), t0: 0.0, t1: 1.0, start_vertex_id: low[i], end_vertex_id: low[j], degenerate: false, name: None });
1388                edges.push(EdgeRecord { id: et, curve: ct.clone(), t0: 0.0, t1: 1.0, start_vertex_id: high[i], end_vertex_id: high[j], degenerate: false, name: None });
1389                // The side: ruled between the bottom and top curves (u along
1390                // the arc, v up); outward is to the arc's right (the region
1391                // lies on its left).
1392                let net = vec![cb.control_points.clone(), ct.control_points.clone()];
1393                let side = frag(NurbsSurface::new(1, plane.degree, vec![0.0, 0.0, 1.0, 1.0], plane.knots.clone(), net), "planar_side")?;
1394                // Surface parameters (v along the arc, u up); the loop runs
1395                // bottom forward, upright j up, top backward, upright i down.
1396                let uv = |a: [f64; 2], b: [f64; 2]| frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "planar_pcurve");
1397                let coedges = vec![
1398                    (eb, true, uv([0.0, 0.0], [0.0, 1.0])?),
1399                    (uprights[j], true, uv([0.0, 1.0], [1.0, 1.0])?),
1400                    (et, false, uv([1.0, 1.0], [1.0, 0.0])?),
1401                    (uprights[i], false, uv([1.0, 0.0], [0.0, 0.0])?),
1402                ];
1403                let records: Vec<CoedgeRecord> = coedges.into_iter().map(|(edge, forward, pcurve)| CoedgeRecord { id: id(), edge_id: edge, forward, pcurve }).collect();
1404                // (u up, v along) × … : the surface's normal is ∂u × ∂v = up × along,
1405                // which points to the arc's left (inside): flip the sense.
1406                let loop_id = id();
1407                faces.push(FaceRecord { id: id(), surface: side, same_sense: false, loops: vec![LoopRecord { id: loop_id, coedges: records }], name: None });
1408                bottom.push((eb, plane.clone()));
1409                top.push((et, plane));
1410            }
1411            bottom_loops.push(bottom);
1412            top_loops.push(top);
1413        }
1414        // Caps: the plane's own coordinates as parameters; the bottom faces
1415        // down (its loops run backward), the top up.
1416        let corner = |z: f64| -> Result<NurbsSurface, KernelRefusal> {
1417            let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
1418            for &l in &members {
1419                for arc in &loops[l] {
1420                    for i in 0..=64 {
1421                        let p = region.eval(arc.kind, arc.a + (arc.b - arc.a) * i as f64 / 64.0);
1422                        for k in 0..2 {
1423                            lo[k] = lo[k].min(p[k]);
1424                            hi[k] = hi[k].max(p[k]);
1425                        }
1426                    }
1427                }
1428            }
1429            let pad = 0.01 * region.scale;
1430            let (lo, hi) = ([lo[0] - pad, lo[1] - pad], [hi[0] + pad, hi[1] + pad]);
1431            let at = |x: f64, y: f64| Vec4::from_point(lift([x, y], z), 1.0);
1432            frag(
1433                NurbsSurface::new(1, 1, vec![lo[0], lo[0], hi[0], hi[0]], vec![lo[1], lo[1], hi[1], hi[1]], vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]]),
1434                "planar_cap",
1435            )
1436        };
1437        for (z, cap_loops, up) in [(z0, &bottom_loops, false), (z1, &top_loops, true)] {
1438            let surface = corner(z)?;
1439            let mut records = Vec::new();
1440            for coedges in cap_loops {
1441                let mut list: Vec<(u64, bool, NurbsCurve)> = coedges.iter().map(|(e, plane)| (*e, true, plane.clone())).collect();
1442                if !up {
1443                    list.reverse();
1444                    for c in &mut list {
1445                        c.1 = false;
1446                        c.2 = frag(c.2.reversed(), "planar_pcurve")?;
1447                    }
1448                }
1449                let coedge_records: Vec<CoedgeRecord> = list.into_iter().map(|(edge, forward, pcurve)| CoedgeRecord { id: id(), edge_id: edge, forward, pcurve }).collect();
1450                records.push(LoopRecord { id: id(), coedges: coedge_records });
1451            }
1452            faces.push(FaceRecord { id: id(), surface, same_sense: up, loops: records, name: None });
1453        }
1454        let edges_count = edges.len() as i64;
1455        // Each hole is a loop of both caps.
1456        let euler = vertices.len() as i64 - edges_count + faces.len() as i64 - 2 * holes.len() as i64;
1457        let shell = id();
1458        let solid_id = id();
1459        let body = BrepSolid {
1460            mass_properties_cache: Default::default(),
1461            id: solid_id,
1462            vertices,
1463            edges,
1464            shells: vec![ShellRecord { id: shell, faces }],
1465            genus: (2 - euler) / 2,
1466            kind: Default::default(),
1467            cells: Default::default(),
1468        };
1469        let issues = body.validate();
1470        if !issues.is_empty() {
1471            return Err(refuse("planar_assembly", format!("the extruded region does not validate: {:?}", issues.first())));
1472        }
1473        let built = frag(crate::solid_mass_properties(&body).map(|p| p.volume), "planar_volume")?;
1474        if (built - expected).abs() > 1e-6 * expected.abs().max(region.scale.powi(3) * 1e-6) {
1475            return Err(refuse("planar_volume", format!("the extruded region's volume {built:.9} disagrees with its area's {expected:.9}")));
1476        }
1477        solids.push(body);
1478    }
1479    Ok(solids)
1480}
1481
1482/// The screw section (default on; `BREP_SWEEP_SCREW_SECTION=0` restores the level engine): under a screw about the clip's axis, a
1483/// straight-sided prism along that axis has as its reduced section the
1484/// region its outline covers turned by −z/c over its height (each slice at
1485/// height z lands on the reduced plane turned back by z/c), built here as a
1486/// planar region.
1487pub fn screw_section_on() -> bool {
1488    crate::switch!("BREP_SWEEP_SCREW_SECTION", true)
1489}
1490
1491/// One boundary arc of the screw section: its points in the clip's plane, and
1492/// whether it is an arc about the axis (a constant level).
1493pub type SectionArc = (Vec<[f64; 2]>, bool);
1494
1495/// The reduced section of the prism with `corners` (clip plane) between
1496/// heights `z` (along the clip's axis) under a screw of advance `c` per
1497/// radian, within `radius` of the axis: its loops of arcs. `None` where it is
1498/// not one region without holes (the level engine reads those).
1499pub fn screw_section_loops(corners: Vec<[f64; 2]>, z: [f64; 2], c: f64, radius: [f64; 2]) -> Result<Option<Vec<Vec<SectionArc>>>, KernelRefusal> {
1500    if !(c.is_finite() && c != 0.0 && z[1] > z[0] && radius[1] > radius[0] && radius[0] >= 0.0) || corners.len() < 3 {
1501        return Ok(None);
1502    }
1503    let polygon = Polygon { corners };
1504    let motion = Motion { turns: vec![([0.0, 0.0], -1.0 / c)], t0: z[0], t1: z[1] };
1505    let clip = Clip { r: radius, angle: None };
1506    let corner_reach = polygon.corners.iter().map(|q| norm(*q)).fold(0.0f64, f64::max);
1507    let scale = corner_reach.max(radius[1].min(corner_reach));
1508    if scale <= 0.0 || radius[1] - radius[0] < 1e-6 * scale {
1509        return Ok(None);
1510    }
1511    let region = Region { motion: &motion, polygon: &polygon, clip: &clip, scale, target: None };
1512    let Some(loops) = region_loops(&region)? else { return Ok(None) };
1513    if loops.is_empty() || loops.iter().any(|l| loop_area(&region, l) <= 0.0) {
1514        return Ok(None);
1515    }
1516    let mut out = Vec::with_capacity(loops.len());
1517    for arcs in &loops {
1518        // A loft takes at least two curves a section: a loop of one arc (a
1519        // whole circle) is split at its middle.
1520        let halves: Vec<Arc>;
1521        let arcs: &[Arc] = if let [one] = arcs.as_slice() {
1522            let m = 0.5 * (one.a + one.b);
1523            let middle = region.eval(one.kind, m);
1524            halves = vec![
1525                Arc { kind: one.kind, a: one.a, b: m, start: one.start, end: middle },
1526                Arc { kind: one.kind, a: m, b: one.b, start: middle, end: one.end },
1527            ];
1528            &halves
1529        } else {
1530            arcs
1531        };
1532        let mut list = Vec::with_capacity(arcs.len());
1533        for arc in arcs {
1534            let level = matches!(arc.kind, Kind::Circle(_) | Kind::Orbit(_));
1535            // A level arc's samples step under a quarter turn, so the angle
1536            // unwrapped from them keeps its winding (a whole circle too).
1537            let count = if level { (((arc.b - arc.a).abs() / (0.25 * std::f64::consts::PI)).ceil() as usize).max(2) } else { 16 };
1538            let points: Vec<[f64; 2]> = (0..=count).map(|i| region.eval(arc.kind, arc.a + (arc.b - arc.a) * i as f64 / count as f64)).collect();
1539            list.push((points, level));
1540        }
1541        out.push(list);
1542    }
1543    Ok(Some(out))
1544}