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