Skip to main content

brep_geometry/geometry/analytic_surface/
revolution.rs

1use super::*;
2pub use super::recognition::{full_circle_knots, nearly_equal_points, surface_scale};
3
4/// Frame, generatrix, and sweep of any surface built by `make_revolution`
5/// (full or partial), validated by exact reconstruction. Unlike
6/// `AnalyticSurface` this does not require the generatrix to be a line or
7/// classic quadric profile.
8pub struct RevolutionStructure {
9    pub frame: RevolutionFrame,
10    pub generatrix: NurbsCurve,
11    pub sweep: f64,
12}
13
14pub fn circumcenter(a: Vec3, b: Vec3, c: Vec3) -> Option<Vec3> {
15    let ab = b.sub(a);
16    let ac = c.sub(a);
17    let normal = ab.cross(ac);
18    let normal_squared = normal.dot(normal);
19    if !normal_squared.is_finite() || normal_squared <= 1e-28 * ab.dot(ab) * ac.dot(ac) {
20        return None;
21    }
22    let offset = normal
23        .cross(ab)
24        .scale(ac.dot(ac))
25        .add(ac.cross(normal).scale(ab.dot(ab)))
26        .scale(1.0 / (2.0 * normal_squared));
27    Some(a.add(offset))
28}
29
30pub fn revolution_structure(surface: &NurbsSurface) -> Option<RevolutionStructure> {
31    if surface.degree_u != 2 {
32        return None;
33    }
34    let rows = &surface.control_points;
35    if rows.len() < 3 || rows.len() % 2 == 0 {
36        return None;
37    }
38    let spans = (rows.len() - 1) / 2;
39    if spans > 4 {
40        return None;
41    }
42    let expected = full_circle_knots(spans);
43    if surface.knots_u.len() != expected.len()
44        || surface
45            .knots_u
46            .iter()
47            .zip(&expected)
48            .any(|(a, b)| (a - b).abs() > 1e-12)
49    {
50        return None;
51    }
52    let scale = surface_scale(surface);
53    // The mid-row weight ratio encodes the per-span arc angle.
54    let mut sweep = None;
55    for column in 0..rows[0].len() {
56        let corner = rows[0][column].w;
57        let middle = rows[1][column].w;
58        if corner.abs() <= 1e-12 {
59            continue;
60        }
61        let ratio = middle / corner;
62        if !(ratio > 0.0 && ratio <= 1.0 + 1e-12) {
63            return None;
64        }
65        let arc_angle = 2.0 * ratio.min(1.0).acos();
66        if arc_angle <= 1e-9 {
67            return None;
68        }
69        sweep = Some(arc_angle * spans as f64);
70        break;
71    }
72    let sweep = sweep?;
73    if sweep > std::f64::consts::TAU + 1e-9 {
74        return None;
75    }
76    // Frame from three points on a radiused angular arc (0.4/0.8 avoid the
77    // closed-circle wraparound where evaluate(1.0) == evaluate(0.0)).
78    let mut frame = None;
79    for column in 0..rows[0].len() {
80        let arc_points: Vec<crate::Vec4> = rows.iter().map(|row| row[column]).collect();
81        let Ok(arc) = NurbsCurve::new(2, surface.knots_u.clone(), arc_points) else {
82            return None;
83        };
84        let p0 = arc.evaluate(0.0).ok()?;
85        let p1 = arc.evaluate(0.4).ok()?;
86        let p2 = arc.evaluate(0.8).ok()?;
87        let Some(center) = circumcenter(p0, p1, p2) else {
88            continue;
89        };
90        let radial = p0.sub(center);
91        let radius = radial.length();
92        if radius <= RECOGNITION_TOLERANCE * scale.max(1.0) {
93            continue;
94        }
95        let axis = radial.cross(p1.sub(center)).normalized().ok()?;
96        let x_axis = radial.scale(1.0 / radius);
97        let y_axis = axis.cross(x_axis);
98        frame = Some(RevolutionFrame {
99            origin: center,
100            axis,
101            x_axis,
102            y_axis,
103        });
104        break;
105    }
106    let frame = frame?;
107    let generatrix =
108        NurbsCurve::new(surface.degree_v, surface.knots_v.clone(), rows[0].clone()).ok()?;
109    let rebuilt = make_revolution(frame.origin, frame.axis, &generatrix, sweep).ok()?;
110    if !nearly_equal_points(surface, &rebuilt, scale) {
111        // A turn of 90 to 180 degrees in ONE span, as
112        // `make_revolution_one_span` builds it (a one-conic corner's torus
113        // sector or horn; `BREP_REVOLUTION_ONE_SPAN_READ`).
114        if !(spans == 1 && sweep > std::f64::consts::FRAC_PI_2 && sweep < std::f64::consts::PI - 1e-6 && one_span_read_on()) {
115            return None;
116        }
117        let one_span = crate::surface::make_revolution_one_span(frame.origin, frame.axis, &generatrix, sweep).ok()?;
118        if !nearly_equal_points(surface, &one_span, scale) {
119            return None;
120        }
121    }
122    Some(RevolutionStructure {
123        frame,
124        generatrix,
125        sweep,
126    })
127}
128
129pub(super) fn rotate_curve_about_axis(
130    curve: &NurbsCurve,
131    origin: Vec3,
132    axis: Vec3,
133    angle: f64,
134) -> Option<NurbsCurve> {
135    let (sin, cos) = angle.sin_cos();
136    let controls = curve
137        .control_points
138        .iter()
139        .map(|control| {
140            let point = control.point().ok()?;
141            let d = point.sub(origin);
142            let axial = axis.scale(d.dot(axis));
143            let radial = d.sub(axial);
144            let ortho = axis.cross(radial);
145            let rotated = origin
146                .add(axial)
147                .add(radial.scale(cos))
148                .add(ortho.scale(sin));
149            Some(crate::Vec4::from_point(rotated, control.w))
150        })
151        .collect::<Option<Vec<_>>>()?;
152    NurbsCurve::new(curve.degree, curve.knots.clone(), controls).ok()
153}
154
155/// Exact intersection of two surfaces of revolution about a COMMON axis:
156/// by rotational symmetry the intersection is the revolution of the 2D
157/// profile intersections, i.e. circular arcs over the angular overlap.
158/// One exact curve×surface hit-test on a generatrix placed mid-overlap
159/// finds the (radius, height) pairs; empty hits prove the surfaces
160/// disjoint (skipping the marcher, which is ill-conditioned exactly here
161/// when the profiles touch tangentially).
162pub(super) fn intersect_coaxial_revolutions(
163    first: &NurbsSurface,
164    second: &NurbsSurface,
165    tolerance: f64,
166) -> Option<Vec<NurbsCurve>> {
167    let a = revolution_structure(first)?;
168    let b = revolution_structure(second)?;
169    let scale = surface_scale(first).max(surface_scale(second)).max(1.0);
170    let alignment = a.frame.axis.dot(b.frame.axis);
171    if alignment.abs() < 1.0 - 1e-9 {
172        return None;
173    }
174    let offset = b.frame.origin.sub(a.frame.origin);
175    let perpendicular = offset.sub(a.frame.axis.scale(offset.dot(a.frame.axis)));
176    if perpendicular.length() > 1e-9 * scale {
177        return None;
178    }
179    // Angular interval of `second` expressed in `first`'s frame, its start
180    // brought into [0, τ) first. `atan2` lands in (-π, π], so an anti-aligned
181    // full-sweep `second` read as (start − τ, start) began as low as −3π and
182    // the ±τ shifts below reached only three quarters of it: the hosted
183    // 2026-11-02 "boolean fails" reports' revolve caps (axis down) against a
184    // bore cylinder (axis up) imprinted a 270° arc and the bore never
185    // pierced the cap.
186    let b_start = b
187        .frame
188        .x_axis
189        .dot(a.frame.y_axis)
190        .atan2(b.frame.x_axis.dot(a.frame.x_axis));
191    let tau = std::f64::consts::TAU;
192    let (b_lo, b_hi) = if alignment > 0.0 {
193        (b_start, b_start + b.sweep)
194    } else {
195        (b_start - b.sweep, b_start)
196    };
197    let b_wrapped = b_lo.rem_euclid(tau);
198    let (b_lo, b_hi) = (b_wrapped, b_hi + (b_wrapped - b_lo));
199    let mut intervals = Vec::new();
200    for shift in [-tau, 0.0, tau] {
201        let lo = (b_lo + shift).max(0.0);
202        let hi = (b_hi + shift).min(a.sweep);
203        if hi - lo > 1e-9 {
204            intervals.push((lo, hi));
205        }
206    }
207    // The pieces of one overlap that the wrap cut apart are one arc again,
208    // so a full turn comes back as the one closed circle it is.
209    intervals.sort_by(|x, y| x.0.total_cmp(&y.0));
210    let mut merged: Vec<(f64, f64)> = Vec::new();
211    for (lo, hi) in intervals {
212        if let Some(last) = merged.last_mut() {
213            if lo <= last.1 + 1e-9 {
214                last.1 = last.1.max(hi);
215                continue;
216            }
217        }
218        merged.push((lo, hi));
219    }
220    let intervals = merged;
221    if intervals.is_empty() {
222        return Some(Vec::new());
223    }
224    let middle = (intervals[0].0 + intervals[0].1) / 2.0;
225    let generatrix = rotate_curve_about_axis(&a.generatrix, a.frame.origin, a.frame.axis, middle)?;
226    let hits = crate::intersect_curve_surface(&generatrix, second, tolerance).ok()?;
227    if hits.len() > 8 {
228        // A hit spray means the profiles overlap (coincident surfaces);
229        // leave that to the cosurface machinery.
230        return None;
231    }
232    let radius_floor = (tolerance * 10.0).max(1e-9 * scale);
233    let mut seen: Vec<(f64, f64)> = Vec::new();
234    let mut curves = Vec::new();
235    for hit in hits {
236        // TANGENT-CONTACT SKIP: a meridian hit whose curve tangent lies IN
237        // the other surface (hit.tangential — computed exactly by the
238        // curve×surface intersector, no projector involved) sweeps a CONTACT
239        // circle where the coaxial surfaces touch without crossing. Minting
240        // it duplicates the true section ring (the cap-plane circle) and
241        // strands one-use edges at assembly. A transversal meridian crossing
242        // keeps tangential=false and is unaffected. Escape hatch:
243        // BREP_COAXIAL_TANGENT_SKIP=0.
244        if hit.tangential
245            && std::env::var("BREP_COAXIAL_TANGENT_SKIP").as_deref() != Ok("0")
246        {
247            continue;
248        }
249        let (_, radius, axial) = a.frame.cylindrical(hit.point);
250        if radius <= radius_floor {
251            continue;
252        }
253        if seen
254            .iter()
255            .any(|(r, z)| (r - radius).abs() + (z - axial).abs() <= radius_floor)
256        {
257            continue;
258        }
259        seen.push((radius, axial));
260        for (lo, hi) in &intervals {
261            let center = a.frame.origin.add(a.frame.axis.scale(axial));
262            curves.push(
263                make_arc(center, a.frame.x_axis, a.frame.y_axis, radius, *lo, *hi).ok()?,
264            );
265        }
266    }
267    Some(curves)
268}
269
270/// COAXIAL ISO SECTION (`BREP_COAXIAL_ISO_SECTION`, default on). A cylinder
271/// (a revolution whose generatrix is a straight segment parallel to its axis)
272/// against a surface whose distance from that axis does not change along one
273/// of its parameters, as a wall carried along a screw or turned about that
274/// axis has: the radius is then a function r(t) of the other parameter alone,
275/// and the section is the iso-curve of the surface at each root of r(t) = R,
276/// exactly, where the marcher fits one through stations to its own tolerance.
277///
278/// No control-net bound proves the invariance (a carried wall follows its
279/// screw only to its carry's error), so the lane stands on dense samples and
280/// answers only when every one agrees, else `None` and the pair goes the way
281/// it went before:
282/// - the radius at every sample stays within `tolerance` of its value at the
283///   middle of the invariant parameter;
284/// - r − R changes sign between the same samples across the other parameter in
285///   every sampled column (no section begins or ends inside the surface), and
286///   no sample comes within ten tolerances of R (no touching root);
287/// - every root is clear of the domain's ends (an edge the face owns);
288/// - every iso-curve lies on the cylinder within `tolerance` at sixteen points
289///   a knot span.
290/// - the cylinder is a whole turn, and its generatrix's control heights are
291///   monotone (so the patch's height range is that of its ends).
292/// Each curve is clipped to that height range on its control points
293/// (`clip_to_cylinder_height`).
294///
295/// The samples are 4 to 16 a knot span. Along the middle column the roots
296/// are proven, not sampled: between two samples of one sign, and on each
297/// side of a found root up to a gap whose control points span `tolerance`,
298/// the column's convex hull is shown to stay on its side
299/// (`column_keeps_side`). What stays sampled is the invariance itself.
300pub(super) fn intersect_cylinder_radius_invariant(
301    cylinder: &NurbsSurface,
302    wall: &NurbsSurface,
303    tolerance: f64,
304) -> Option<Vec<NurbsCurve>> {
305    let structure = revolution_structure(cylinder)?;
306    let frame = &structure.frame;
307    let scale = surface_scale(cylinder).max(surface_scale(wall)).max(1.0);
308    let generatrix: Vec<Vec3> = structure.generatrix.control_points.iter().map(|c| c.point().ok()).collect::<Option<_>>()?;
309    let radial = |p: Vec3| {
310        let d = p.sub(frame.origin);
311        d.sub(frame.axis.scale(d.dot(frame.axis)))
312    };
313    let first_radial = radial(generatrix[0]);
314    let radius = first_radial.length();
315    if radius <= 1e-9 * scale || generatrix.iter().any(|p| radial(*p).sub(first_radial).length() > 1e-12 * scale) {
316        return None;
317    }
318    // The patch's height range is the generatrix's image, read at its ends:
319    // with positive weights and monotone control heights the height along it
320    // is monotone (variation diminishing), else the image is not its ends.
321    let heights: Vec<f64> = generatrix.iter().map(|p| p.sub(frame.origin).dot(frame.axis)).collect();
322    let rising = heights.windows(2).all(|h| h[1] >= h[0]);
323    let falling = heights.windows(2).all(|h| h[1] <= h[0]);
324    if !(rising || falling) || structure.generatrix.control_points.iter().any(|c| c.w <= 0.0) {
325        return None;
326    }
327    let [g0, g1] = structure.generatrix.domain().ok()?;
328    let height_at = |t: f64| -> Option<f64> { Some(structure.generatrix.evaluate(t).ok()?.sub(frame.origin).dot(frame.axis)) };
329    let (h0, h1) = (height_at(g0)?, height_at(g1)?);
330    let (low, high) = (h0.min(h1), h0.max(h1));
331    if high - low <= 1e-9 * scale {
332        return None;
333    }
334    if structure.sweep < std::f64::consts::TAU - 1e-9 {
335        return None; // a part of a turn: its azimuth is not clipped
336    }
337    let r_at = |u: f64, v: f64| -> Option<f64> { Some(radial(wall.evaluate(u, v).ok()?).length()) };
338    let samples = |knots: &[f64], degree: usize| -> Vec<f64> {
339        let (lo, hi) = (knots[degree], knots[knots.len() - degree - 1]);
340        let mut breaks: Vec<f64> = knots[degree..knots.len() - degree].to_vec();
341        breaks.dedup();
342        let per = (64 / breaks.len().max(2)).clamp(4, 16);
343        // Off the knots and off round fractions of a span by an irrational
344        // step, so that no sample lands on a symmetric root by construction.
345        let mut out = vec![lo];
346        for pair in breaks.windows(2) {
347            for k in 0..per {
348                out.push(pair[0] + (pair[1] - pair[0]) * (k as f64 + 0.381_966_011_250_105) / per as f64);
349            }
350        }
351        out.push(hi);
352        out
353    };
354    let us = samples(&wall.knots_u, wall.degree_u);
355    let vs = samples(&wall.knots_v, wall.degree_v);
356    if us.len() * vs.len() > 40_000 {
357        return None;
358    }
359    // r at every sample: grid[i][j] = r(us[i], vs[j]).
360    let grid: Vec<Vec<f64>> = us.iter().map(|&u| vs.iter().map(|&v| r_at(u, v)).collect::<Option<Vec<_>>>()).collect::<Option<_>>()?;
361    for invariant_v in [true, false] {
362        // `across` runs over the parameter r depends on, `along` over the invariant one.
363        let (across, along) = if invariant_v { (&us, &vs) } else { (&vs, &us) };
364        let value = |i: usize, j: usize| if invariant_v { grid[i][j] } else { grid[j][i] };
365        let middle = along.len() / 2;
366        let invariant = (0..across.len()).all(|i| (0..along.len()).all(|j| (value(i, j) - value(i, middle)).abs() <= tolerance));
367        if !invariant {
368            continue;
369        }
370        if (0..across.len()).any(|i| (0..along.len()).any(|j| (value(i, j) - radius).abs() <= 10.0 * tolerance)) {
371            return None;
372        }
373        let signs = |j: usize| -> Vec<bool> { (0..across.len()).map(|i| value(i, j) > radius).collect() };
374        let pattern = signs(middle);
375        if (0..along.len()).any(|j| signs(j) != pattern) {
376            return None;
377        }
378        let fixed = along[middle];
379        let g = |t: f64| -> Option<f64> { Some(if invariant_v { r_at(t, fixed)? } else { r_at(fixed, t)? } - radius) };
380        let (domain_lo, domain_hi) = (across[0], across[across.len() - 1]);
381        // The middle column as a curve: between two samples of one sign its
382        // convex hull must prove that side (`column_keeps_side`), so a dip to
383        // R between samples, however narrow, declines the pair.
384        // It is worked on over a domain RESCALED_LENGTH long (`to`), where a
385        // split's absolute knot tolerance is a relative 1e-13.
386        let (column, c0, c1) = rescaled(&if invariant_v { wall.iso_curve_v(fixed).ok()? } else { wall.iso_curve_u(fixed).ok()? })?;
387        let to = |t: f64| (t - c0) / (c1 - c0) * RESCALED_LENGTH;
388        for i in 0..across.len() - 1 {
389            if pattern[i] == pattern[i + 1] {
390                column_keeps_side(&sub_curve(&column, to(across[i]), to(across[i + 1]))?, &radial, radius, pattern[i], 10.0 * tolerance)?;
391            }
392        }
393        let mut curves = Vec::new();
394        for i in 0..across.len() - 1 {
395            if pattern[i] == pattern[i + 1] {
396                continue;
397            }
398            let (a0, b0) = (across[i], across[i + 1]);
399            let (mut a, mut b) = (a0, b0);
400            let positive_at_a = pattern[i];
401            for _ in 0..200 {
402                let mid = 0.5 * (a + b);
403                if mid <= a || mid >= b {
404                    break;
405                }
406                if (g(mid)? > 0.0) == positive_at_a {
407                    a = mid;
408                } else {
409                    b = mid;
410                }
411            }
412            let root = 0.5 * (a + b);
413            if (root - domain_lo).abs() <= 1e-9 * (domain_hi - domain_lo) || (domain_hi - root).abs() <= 1e-9 * (domain_hi - domain_lo) {
414                return None;
415            }
416            // One root in the interval: each side of it keeps its sample's
417            // side up to a gap about the root whose control points span no
418            // more than `tolerance` (any further root there is that close).
419            let (root_s, a0, b0) = (to(root), to(a0), to(b0));
420            let mut delta = 1e-6 * (b0 - a0);
421            loop {
422                if delta < 4.0 * crate::KNOT_IDENTITY_TOL || root_s - delta <= a0 + 2.0 * crate::KNOT_IDENTITY_TOL || root_s + delta >= b0 - 2.0 * crate::KNOT_IDENTITY_TOL {
423                    return None;
424                }
425                let gap = sub_curve(&column, root_s - delta, root_s + delta)?;
426                let points: Vec<Vec3> = gap.control_points.iter().map(|c| c.point().ok()).collect::<Option<_>>()?;
427                if points.iter().all(|p| p.sub(points[0]).length() <= 0.5 * tolerance) {
428                    break;
429                }
430                delta *= 0.1;
431            }
432            column_keeps_side(&sub_curve(&column, a0, root_s - delta)?, &radial, radius, positive_at_a, 0.0)?;
433            column_keeps_side(&sub_curve(&column, root_s + delta, b0)?, &radial, radius, !positive_at_a, 0.0)?;
434            let curve = if invariant_v { wall.iso_curve_u(root).ok()? } else { wall.iso_curve_v(root).ok()? };
435            // On the cylinder at sixteen points a span.
436            let mut breaks: Vec<f64> = curve.knots[curve.degree..curve.knots.len() - curve.degree].to_vec();
437            breaks.dedup();
438            for pair in breaks.windows(2) {
439                for k in 0..=16 {
440                    let point = curve.evaluate(pair[0] + (pair[1] - pair[0]) * k as f64 / 16.0).ok()?;
441                    if (radial(point).length() - radius).abs() > tolerance {
442                        return None;
443                    }
444                }
445            }
446            curves.extend(clip_to_cylinder_height(&curve, frame, low, high, tolerance)?);
447        }
448        return Some(curves);
449    }
450    None
451}
452
453/// The domain length the iso section halves its curves over.
454const RESCALED_LENGTH: f64 = 1e4;
455
456/// `curve` reparametrised affinely onto `[0, RESCALED_LENGTH]`, with its
457/// own domain's ends.
458fn rescaled(curve: &NurbsCurve) -> Option<(NurbsCurve, f64, f64)> {
459    let [t0, t1] = curve.domain().ok()?;
460    if !(t1 > t0) {
461        return None;
462    }
463    let knots = curve.knots.iter().map(|k| (k - t0) / (t1 - t0) * RESCALED_LENGTH).collect();
464    Some((NurbsCurve::new(curve.degree, knots, curve.control_points.clone()).ok()?, t0, t1))
465}
466
467/// `curve` from `a` to `b`; an end within a knot's identity tolerance of
468/// the curve's own end is that end.
469fn sub_curve(curve: &NurbsCurve, a: f64, b: f64) -> Option<NurbsCurve> {
470    let [start, _] = curve.domain().ok()?;
471    let mut piece = curve.clone();
472    if a > start + crate::KNOT_IDENTITY_TOL {
473        piece = piece.split(a).ok()?.1;
474    }
475    let [_, end] = piece.domain().ok()?;
476    if b < end - crate::KNOT_IDENTITY_TOL {
477        piece = piece.split(b).ok()?.0;
478    }
479    Some(piece)
480}
481
482/// `Some` when every point of `curve` is proven to lie outside (`outside`)
483/// or inside the radius `radius` about the axis `radial` measures from, on
484/// its control points (positive weights keep it in their convex hull):
485/// inside when every control point's distance is below `radius` (distance
486/// from the axis is convex), outside when every control point lies beyond
487/// `radius` along the radial direction of the piece's middle. A piece that
488/// proves neither is halved; `None` when a middle is on the wrong side or
489/// within `clearance` of the radius, a weight is not positive, a split
490/// refuses or the pieces pass a budget.
491fn column_keeps_side(curve: &NurbsCurve, radial: &dyn Fn(Vec3) -> Vec3, radius: f64, outside: bool, clearance: f64) -> Option<()> {
492    let mut stack = vec![curve.clone()];
493    let mut budget = 4096usize;
494    while let Some(piece) = stack.pop() {
495        budget = budget.checked_sub(1)?;
496        if piece.control_points.iter().any(|c| c.w <= 0.0) {
497            return None;
498        }
499        let q: Vec<Vec3> = piece.control_points.iter().map(|c| c.point().ok().map(|p| radial(p))).collect::<Option<_>>()?;
500        let [a, b] = piece.domain().ok()?;
501        let mid = 0.5 * (a + b);
502        let m = radial(piece.evaluate(mid).ok()?);
503        let r = m.length();
504        let proven = if outside {
505            if r - radius <= clearance {
506                return None;
507            }
508            let n = m.scale(1.0 / r);
509            q.iter().all(|p| p.dot(n) > radius)
510        } else {
511            if radius - r <= clearance {
512                return None;
513            }
514            q.iter().all(|p| p.length() < radius)
515        };
516        if proven {
517            continue;
518        }
519        let (left, right) = piece.split(mid).ok()?;
520        stack.push(left);
521        stack.push(right);
522    }
523    Some(())
524}
525
526/// The parts of `curve` (on the cylinder about `frame`) from height `low` to
527/// `high`, found on its control points: a piece whose points all lie in the
528/// band is in it, one whose points all lie on one side is out (a rational
529/// curve with positive weights stays in their convex hull), and one that
530/// straddles a side is halved until it is a parameter's rounding long. `None`
531/// for a weight that is not positive.
532pub(super) fn clip_to_cylinder_height(curve: &NurbsCurve, frame: &RevolutionFrame, low: f64, high: f64, tolerance: f64) -> Option<Vec<NurbsCurve>> {
533    if curve.control_points.iter().any(|c| c.w <= 0.0) {
534        return None;
535    }
536    let (work, t0, t1) = rescaled(curve)?;
537    let back = |s: f64| t0 + s / RESCALED_LENGTH * (t1 - t0);
538    let height = |c: &NurbsCurve| -> Option<(f64, f64)> {
539        c.control_points.iter().try_fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| {
540            let h = p.point().ok()?.sub(frame.origin).dot(frame.axis);
541            Some((lo.min(h), hi.max(h)))
542        })
543    };
544    let (low, high) = (low - tolerance, high + tolerance);
545    let mut inside: Vec<(f64, f64)> = Vec::new();
546    let mut stack = vec![(work, 0.0, RESCALED_LENGTH)];
547    while let Some((piece, a, b)) = stack.pop() {
548        let (lo, hi) = height(&piece)?;
549        if hi < low || lo > high {
550            continue;
551        }
552        if lo >= low && hi <= high {
553            inside.push((back(a), back(b)));
554            continue;
555        }
556        let mid = 0.5 * (a + b);
557        // Halved until the split refuses (a knot's identity tolerance long).
558        let halves = if b - a > 1e-13 * RESCALED_LENGTH && mid > a && mid < b { piece.split(mid).ok() } else { None };
559        let Some((left, right)) = halves else {
560            // A piece a rounding long at a side of the band: in when its
561            // middle is, if its heights span no more than `tolerance`; the
562            // split's absolute tolerance can leave a long piece, which declines.
563            if hi - lo > tolerance {
564                return None;
565            }
566            let h = piece.evaluate(mid).ok()?.sub(frame.origin).dot(frame.axis);
567            if h >= low && h <= high {
568                inside.push((back(a), back(b)));
569            }
570            continue;
571        };
572        stack.push((right, mid, b));
573        stack.push((left, a, mid));
574        if stack.len() > 10_000 {
575            return None;
576        }
577    }
578    inside.sort_by(|x, y| x.0.total_cmp(&y.0));
579    let mut merged: Vec<(f64, f64)> = Vec::new();
580    for (a, b) in inside {
581        match merged.last_mut() {
582            Some(last) if a <= last.1 => last.1 = last.1.max(b),
583            _ => merged.push((a, b)),
584        }
585    }
586    let mut out = Vec::new();
587    for (a, b) in merged {
588        if b - a <= 1e-12 * (t1 - t0) {
589            continue;
590        }
591        // An end within a knot's identity tolerance of the domain's is the domain's.
592        let mut piece = curve.clone();
593        if let Ok((_, right)) = piece.split(a) {
594            piece = right;
595        }
596        if let Ok((left, _)) = piece.split(b) {
597            piece = left;
598        }
599        // The ends a refused or snapped split left must still be in the band.
600        let [p0, p1] = piece.domain().ok()?;
601        for t in [p0, p1] {
602            let h = piece.evaluate(t).ok()?.sub(frame.origin).dot(frame.axis);
603            if h < low - tolerance || h > high + tolerance {
604                return None;
605            }
606        }
607        out.push(piece);
608    }
609    Some(out)
610}
611
612/// `BREP_REVOLUTION_ONE_SPAN_READ` (on by default; `=0` reads only
613/// `make_revolution`'s split turns): a turn of 90 to 180 degrees in ONE
614/// rational span is a surface of revolution too.
615fn one_span_read_on() -> bool {
616    crate::switch!(live "BREP_REVOLUTION_ONE_SPAN_READ", true)
617}