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