Skip to main content

brep_kernel/construction/sweep_topology/
sweep.rs

1use super::*;
2use super::stations::{
3    StationBudget, StationParam, SweepStationReport, SWEEP_DEFAULT_TOLERANCE, SWEEP_MAX_STATIONS,
4    SWEEP_REFINEMENT_ROUNDS,
5};
6
7/// Sweep a CLOSED PLANAR profile loop along a path curve (§3.3/§5.7),
8/// TRANSPLANTING the profile onto the path — see [`SectionPlacement`] for the
9/// other reading, and for why the choice changes the solid.
10///
11/// Reuses the loft builder rather than a bespoke swept surface: the path is
12/// sampled at `STATIONS` uniform stations, a rotation-minimizing frame is
13/// propagated along it (double-reflection RMF, Wang et al. 2008 — the frame
14/// does NOT spin at inflections the way raw Frenet does), a rigidly
15/// transformed copy of the profile is placed at each station (identical
16/// degree/knots/weights, only the control points moved — which guarantees
17/// loft's per-section compatibility), and the stations are lofted through
18/// to produce the tube plus planar end caps.
19///
20/// Guards return a clear `Err` on an open/non-planar profile, a degenerate
21/// path tangent, or a loft failure. A path that bends TIGHTER than the section
22/// reaches is refused by name before the loft (`ρκ ≥ 1`, §4c of
23/// [`sweep_sections_through_samples`]); it used to be out of scope and the
24/// caller's problem, and what the caller got instead was a wall that passed
25/// through itself.
26pub fn sweep_profile_along_path(
27    profile: &[NurbsCurve],
28    path: &NurbsCurve,
29    name: Option<&str>,
30) -> Result<BrepSolid, KernelRefusal> {
31    // 32 stations is the original fixed sampling — golden parity pins the
32    // emitted geometry to it — and it stays the count for every path whose
33    // tangent turns through at most a full turn. A path that turns further
34    // (a coil) gets the helix builder's density; see [`path_turning_stations`].
35    sweep_profile_along_path_stations(
36        profile,
37        path,
38        name,
39        path_turning_stations(path),
40        0.0,
41        None,
42        SectionPlacement::Transplant,
43        SWEEP_DEFAULT_TOLERANCE,
44    )
45    .map(|swept| swept.solid)
46}
47
48/// Twisted path sweep (§5.7): identical to [`sweep_profile_along_path`], but
49/// the profile additionally ROTATES about the path tangent, linearly in ARC
50/// LENGTH, from 0 at the sweep start to `twist_angle` radians (right-handed
51/// about the tangent) at the end.  The arc-length fraction comes from the
52/// sampled station polyline, not the raw path parameter, so a non-uniformly
53/// parameterized path still twists uniformly in space.
54///
55/// STATION LAW: 16 stations per quarter turn of twist, floored at the path
56/// sweep's 32 and capped at 1024 (the loft's dense interpolation solve is
57/// O(stations³) per control column — the same cap the helix uses).  At
58/// 16/quarter-turn the inter-station twist step is Δφ ≈ 5.6°, so the cubic
59/// v-interpolation error on a profile point circling at radius r is
60/// ≈ r·Δφ⁴/384 ≈ 2.4·10⁻¹⁰·r — far below any geometric tolerance.  The cap
61/// holds that density up to 16 full turns (|twist| = 32π = 1024/16 quarter
62/// turns); a larger twist would silently alias under the cap, so it is
63/// REJECTED with an honest error instead.  Everything else the path sweep
64/// documents (profile validity, the tight-bend refusal) applies unchanged, and
65/// the tight-bend guard measures the TWISTED section's reach because it reads
66/// the axes the sections were actually placed on; twisting about the profile's
67/// own centroid adds no new radial extent of its own.
68pub fn sweep_profile_twisted(
69    profile: &[NurbsCurve],
70    path: &NurbsCurve,
71    twist_angle: f64,
72    name: Option<&str>,
73) -> Result<BrepSolid, KernelRefusal> {
74    use std::f64::consts::{FRAC_PI_2, TAU};
75
76    if !twist_angle.is_finite() {
77        return Err(KernelRefusal::input(
78            KernelStage::Collect,
79            "twist_finite",
80            "sweep_profile_twisted: twist angle must be finite",
81        ));
82    }
83    // 16 turns is where the 1024-station cap meets 16 stations/quarter-turn;
84    // beyond it the cap would degrade the twist sampling density silently.
85    const MAX_TURNS: f64 = 16.0;
86    if twist_angle.abs() > MAX_TURNS * TAU {
87        return Err(KernelRefusal::unsupported(
88            KernelStage::Collect,
89            "twist_cap",
90            format!(
91            "sweep_profile_twisted: twist of {:.3} turns exceeds the {MAX_TURNS}-turn \
92             limit the 1024-station cap can resolve at 16 stations per quarter turn; \
93             split the sweep or reduce the twist",
94            twist_angle.abs() / TAU
95            ),
96        ));
97    }
98    let quarter_turns = (twist_angle.abs() / FRAC_PI_2).ceil() as usize;
99    let stations = (quarter_turns * 16).clamp(32, 1024).max(path_turning_stations(path));
100    sweep_profile_along_path_stations(
101        profile,
102        path,
103        name,
104        stations,
105        twist_angle,
106        None,
107        SectionPlacement::Transplant,
108        SWEEP_DEFAULT_TOLERANCE,
109    )
110    .map(|swept| swept.solid)
111    .map_err(|error| error.with_message(|error| format!("sweep_profile_twisted: {error}")))
112}
113
114/// The station budget of a single-curve path sweep, from how far the path's
115/// TANGENT turns: 8 stations per quarter turn of tangent — the 32 per turn
116/// [`sweep_profile_helix`] lofts a coil with — floored at the original 32 and
117/// capped at the loft's 1024.
118///
119/// A fixed 32 was a budget for a path that bends once. Along a coil it is
120/// FOUR stations a turn (an 8-turn helix edge, 2026-09-25), and a loft through
121/// sections a quarter turn apart does not follow the path between them: the
122/// wall cut its own corner and folded through itself, and the Tube and Path
123/// Sweep features refused the edge. The floor keeps every path that turns
124/// through at most a full turn on exactly the geometry it always had.
125///
126/// The turning is [`segment_turning`]'s — the chain sampler's own reading —
127/// independent of the station count it decides. A path it cannot read is
128/// reported by the sampler itself, in its own words, after the profile has been
129/// checked; here it only leaves the budget on the floor.
130fn path_turning_stations(path: &NurbsCurve) -> usize {
131    use std::f64::consts::FRAC_PI_2;
132    let turning = path
133        .domain()
134        .and_then(|domain| segment_turning(path, domain))
135        .unwrap_or(0.0);
136    // The slack keeps a path of EXACTLY a full turn (a circle) on the floor
137    // rather than one quarter over it from sampling round-off.
138    let quarter_turns = (turning / FRAC_PI_2 - 1e-3).ceil().max(0.0) as usize;
139    (quarter_turns * 8).clamp(32, 1024)
140}
141
142/// HOW a section is placed at each station — the two things "sweep a profile
143/// along a path" can mean, and the reason they are not the same shape.
144///
145/// `Transplant` MOVES the profile onto the path: the anchor origin lands on the
146/// station point and the profile plane becomes the station's NORMAL plane. The
147/// profile's own position and its angle to the path are both discarded — every
148/// sweep comes out centred on the path and square to it. That is the classic
149/// swept-surface reading, and it is what `SWP` builds.
150///
151/// `Rigid` CARRIES the profile: the section at station `k` is the profile moved
152/// by the same rigid motion the PATH undergoes between its start and station
153/// `k`,
154///
155/// ```text
156///     section_k(x) = P_k + R_k · (x − P_0)
157/// ```
158///
159/// where `R_k` is the rotation taking the start frame `(T_0, r_0, s_0)` to the
160/// station's `(T_k, r_k, s_k)`. The profile keeps its drawn POSITION and its
161/// drawn ANGLE to the path; what changes along the sweep is only what the path
162/// itself does. Two consequences are the whole point of the mode:
163///   - a STRAIGHT path makes every `R_k` the identity, so the section merely
164///     translates and the result is the oblique prism `extrude_profile_brep`
165///     builds from the same profile and vector — `pathAlign` and `translate`
166///     agree on a straight path rather than merely having the same volume;
167///   - a circular ARC makes `R_k` the rotation about the ARC'S OWN CENTRE AXIS
168///     (for a planar path the RMF's transport rotation IS that rotation), so
169///     the profile is carried round the pivot and the end cap arrives at the
170///     angle the start cap had to the tangent. A full-circle path degenerates
171///     to exactly a revolve of the profile about that axis;
172///   - a HELIX makes `R_k` the SCREW about the helix's own axis — but only when
173///     the path says it is one ([`SweepPath::screw_axes`]), because the frame
174///     that realizes it is not the RMF. A helix is carried into itself by the
175///     screw, which spins the tangent frame at the helix's torsion; the RMF has
176///     no spin about the tangent by construction, so it rolls away from the
177///     screw by `∫τ ds` (169.75° over three turns of a radius-5, pitch-5 coil).
178///     A helix segment's stations are therefore framed off its axis
179///     (`screw_reference`), and every other segment keeps the RMF — which on a
180///     chain of lines and arcs in ANY planes is still exactly each arc's turn
181///     about its own centre, composed. The two hand over at a joint without a
182///     roll.
183///
184/// Why not one frame for every curve: the Frenet frame is the screw on a helix
185/// but spins where a spatial curve nearly straightens (a planar S-cubic lifted
186/// 1e-3 out of its plane carries a 180° roll through the inflection, which 32
187/// stations read as 0.4°), and one axis fitted to the whole run is the screw on
188/// a helix but rolls a two-arc spatial chain by up to 256° against its arcs.
189///
190/// `R_k = F_k · F_0ᵀ` does NOT depend on which perpendicular `r_0` the RMF was
191/// seeded with: re-seeding rolls `F_0` and every `F_k` by the same angle about
192/// the tangent, and the two rolls cancel in the product. That matters because
193/// `Transplant` maps `pu → r_k` directly, so under IT the profile's roll about
194/// the path is whatever `tangents[0].perpendicular()` happened to return — an
195/// arbitrary orientation no caller can predict. `Rigid` has no such freedom.
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub enum SectionPlacement {
198    /// Move the profile onto the path, square to it (the classic sweep).
199    Transplant,
200    /// Carry the profile by the path's own rigid motion (see above).
201    Rigid,
202}
203
204/// The placement anchor a path sweep transplants its profile with: the plane
205/// frame `(origin = boundary-sample centroid, normal, pu, pv)` the station
206/// loop maps profile points through (`local = p − origin` → `station + ri·(local
207/// ·pu) + si·(local·pv)`). Extracted as data so a HOLE loop can sweep with its
208/// OUTER loop's anchor — sweeping each loop with its OWN centroid would
209/// re-center every loop onto the path and lose the hole's in-plane offset.
210#[derive(Debug, Clone, Copy)]
211pub struct ProfileAnchor {
212    pub origin: Vec3,
213    pub normal: Vec3,
214    pub pu: Vec3,
215    pub pv: Vec3,
216}
217
218/// [`sweep_profile_along_path`] with an explicit placement anchor (see
219/// [`ProfileAnchor`]) — the hole-loop cutter path: the swept loop is validated
220/// as usual but PLACED in its outer loop's frame.
221pub fn sweep_profile_along_path_anchored(
222    profile: &[NurbsCurve],
223    path: &NurbsCurve,
224    name: Option<&str>,
225    anchor: ProfileAnchor,
226) -> Result<BrepSolid, KernelRefusal> {
227    sweep_profile_along_path_stations(
228        profile,
229        path,
230        name,
231        path_turning_stations(path),
232        0.0,
233        Some(anchor),
234        SectionPlacement::Transplant,
235        SWEEP_DEFAULT_TOLERANCE,
236    )
237    .map(|swept| swept.solid)
238}
239
240/// [`sweep_profile_twisted`] with an explicit placement anchor: the hole loop
241/// twists about the SAME path axis as its outer loop (shared anchor), so the
242/// cutter stays registered with the outer wall through the whole twist.
243pub fn sweep_profile_twisted_anchored(
244    profile: &[NurbsCurve],
245    path: &NurbsCurve,
246    twist_angle: f64,
247    name: Option<&str>,
248    anchor: ProfileAnchor,
249) -> Result<BrepSolid, KernelRefusal> {
250    use std::f64::consts::{FRAC_PI_2, TAU};
251
252    if !twist_angle.is_finite() {
253        return Err(KernelRefusal::input(
254            KernelStage::Collect,
255            "twist_finite",
256            "sweep_profile_twisted: twist angle must be finite",
257        ));
258    }
259    const MAX_TURNS: f64 = 16.0;
260    if twist_angle.abs() > MAX_TURNS * TAU {
261        return Err(KernelRefusal::unsupported(
262            KernelStage::Collect,
263            "twist_cap",
264            format!(
265            "sweep_profile_twisted: twist of {:.3} turns exceeds the {MAX_TURNS}-turn \
266             limit the 1024-station cap can resolve at 16 stations per quarter turn; \
267             split the sweep or reduce the twist",
268            twist_angle.abs() / TAU
269            ),
270        ));
271    }
272    let quarter_turns = (twist_angle.abs() / FRAC_PI_2).ceil() as usize;
273    let stations = (quarter_turns * 16).clamp(32, 1024).max(path_turning_stations(path));
274    sweep_profile_along_path_stations(
275        profile,
276        path,
277        name,
278        stations,
279        twist_angle,
280        Some(anchor),
281        SectionPlacement::Transplant,
282        SWEEP_DEFAULT_TOLERANCE,
283    )
284    .map(|swept| swept.solid)
285    .map_err(|error| error.with_message(|error| format!("sweep_profile_twisted: {error}")))
286}
287
288/// Sweep a CLOSED PLANAR profile along a CHAIN of path curves joined
289/// head-to-tail — the multi-segment entry point, with the twist and anchor
290/// options the single-curve family exposes as separate functions folded into
291/// one signature (the feature layer picks all three per loop, so splitting them
292/// four ways here would only push the same match into the caller).
293///
294/// `path` carries the chain AND its classification ([`SweepPath`]): the segment
295/// names for the joint refusal (a short or empty name list degrades to
296/// `<unnamed>` rather than failing), whether the run is CLOSED, the plane it lies
297/// in if it lies in one, and the continuity of every joint. The refusals below
298/// READ that classification rather than each re-deriving it — the corner gate no
299/// longer measures its own tangent break while sampling, and closure is a
300/// property of the path rather than something the sampler notices about its first
301/// and last station.
302///
303/// `corner_advice` is appended to the cornered-joint refusal and is the CALLER's
304/// to write, because the builder has two callers with different answers: path
305/// sweep sends the user to SW (a different feature), while SW's own `pathAlign`
306/// sends them to its `translate` mode. A builder that named one feature would be
307/// telling half its users to switch to the feature they are already in.
308///
309/// A ONE-segment OPEN chain delegates to the single-curve builders unchanged, so
310/// the geometry every existing path sweep emits is untouched by this entry point
311/// existing — the multi-segment sampler is reached only by a path that actually
312/// has a joint. A one-segment CLOSED chain (a resident circular edge) does NOT
313/// delegate: the single-curve samplers cap both ends, which is exactly what a
314/// ring must not do.
315///
316/// A CORNER (a joint past [`MAX_JOINT_TANGENT_BREAK`]) selects the MITRE lane
317/// when every segment is straight — see `sweep_topology/miter.rs` for the
318/// construction and [`CornerPolicy`] for why this entry mitres while
319/// [`sweep_profile_along_chain_with_stations`] refuses. A CLOSED cornered
320/// polyline is a picture FRAME: its closing joint is a mitre like the rest and
321/// the result has no caps. A corner at a CURVED segment is refused by name.
322pub fn sweep_profile_along_chain(
323    profile: &[NurbsCurve],
324    path: &SweepPath,
325    twist_angle: f64,
326    name: Option<&str>,
327    anchor: Option<ProfileAnchor>,
328    placement_mode: SectionPlacement,
329    corner_advice: &str,
330) -> Result<BrepSolid, KernelRefusal> {
331    sweep_profile_along_chain_reported(
332        profile,
333        path,
334        twist_angle,
335        name,
336        anchor,
337        placement_mode,
338        corner_advice,
339        None,
340    )
341    .map(|swept| swept.solid)
342}
343
344/// A swept solid with the MEASURED BOUND of its construction
345/// ([`SweepStationReport`]): `None` where the construction is exact — the
346/// mitre lane (exact pieces on bisector planes) and the envelope lane (a
347/// revolve) — and the station lane's report otherwise.
348#[derive(Debug)]
349pub struct SweptChain {
350    pub solid: BrepSolid,
351    pub report: Option<SweepStationReport>,
352}
353
354impl SweptChain {
355    fn exact(solid: BrepSolid) -> Self {
356        Self {
357            solid,
358            report: None,
359        }
360    }
361}
362
363/// [`sweep_profile_along_chain`] with the requested wall TOLERANCE (mm;
364/// `None` for [`SWEEP_DEFAULT_TOLERANCE`]) and the measured bound the build
365/// reached, for a caller that carries it on (the sweep features put it in
366/// `FeatureResult::approximations`). The station lane refines its stations
367/// until the loft's own interpolant stands within `tolerance` of the kinematic
368/// sweep's wall, or the station cap stops it; the report says which.
369#[allow(clippy::too_many_arguments)]
370pub fn sweep_profile_along_chain_reported(
371    profile: &[NurbsCurve],
372    path: &SweepPath,
373    twist_angle: f64,
374    name: Option<&str>,
375    anchor: Option<ProfileAnchor>,
376    placement_mode: SectionPlacement,
377    corner_advice: &str,
378    tolerance: Option<f64>,
379) -> Result<SweptChain, KernelRefusal> {
380    use std::f64::consts::{FRAC_PI_2, TAU};
381    let tolerance = sweep_tolerance(tolerance)?;
382
383    if path.is_empty() {
384        return Err(KernelRefusal::input(
385            KernelStage::Collect,
386            "chain_empty",
387            "sweepSolid: path chain is empty",
388        ));
389    }
390    // A bend TIGHTER than the section is the envelope lane's, not the loft's, and
391    // it is asked BEFORE the single-curve shortcut below — that shortcut lands in
392    // the same skinning builder, so taking it first would hide the one path shape
393    // this lane exists for (one circular arc) behind it.
394    let envelope_lane = super::envelope::recognize_swept_envelope(profile, path, placement_mode)?
395        .is_ok();
396
397    if !twist_angle.is_finite() {
398        return Err(KernelRefusal::input(
399            KernelStage::Collect,
400            "twist_finite",
401            if path.curves.len() == 1 && placement_mode == SectionPlacement::Transplant {
402                "sweep_profile_twisted: twist angle must be finite"
403            } else {
404                "sweep_profile_along_chain: twist angle must be finite"
405            },
406        ));
407    }
408    const MAX_TURNS: f64 = 16.0;
409    if twist_angle.abs() > MAX_TURNS * TAU {
410        let who = if path.curves.len() == 1 && placement_mode == SectionPlacement::Transplant {
411            "sweep_profile_twisted"
412        } else {
413            "sweep_profile_along_chain"
414        };
415        return Err(KernelRefusal::unsupported(
416            KernelStage::Collect,
417            "twist_cap",
418            format!(
419            "{who}: twist of {:.3} turns exceeds the {MAX_TURNS}-turn \
420             limit the 1024-station cap can resolve at 16 stations per quarter turn; \
421             split the sweep or reduce the twist",
422            twist_angle.abs() / TAU
423            ),
424        ));
425    }
426    // Single segment under `Transplant`: the single-curve sampler's own budget
427    // on the single-curve lane, so an ordinary one-edge path sweep emits the
428    // geometry it always has wherever it reads inside the tolerance. `Rigid`
429    // has no single-curve budget and falls through to the chain sampler, which
430    // samples a 1-element chain over exactly the domain the single-curve
431    // sampler would (no joints, the whole budget on one segment). A CLOSED
432    // single segment falls through too — the single-curve lane ends in a capped
433    // loft, and a ring has no caps.
434    if let ([single], SectionPlacement::Transplant, false, false) =
435        (path.curves.as_slice(), placement_mode, path.closed, envelope_lane)
436    {
437        // The single-curve builders' own budgets ([`path_turning_stations`],
438        // the twisted law), on the single-curve lane, at this tolerance.
439        let stations = if twist_angle == 0.0 {
440            path_turning_stations(single)
441        } else {
442            let quarter_turns = (twist_angle.abs() / FRAC_PI_2).ceil() as usize;
443            (quarter_turns * 16).clamp(32, 1024).max(path_turning_stations(single))
444        };
445        return sweep_profile_along_path_stations(
446            profile,
447            single,
448            name,
449            stations,
450            twist_angle,
451            anchor,
452            SectionPlacement::Transplant,
453            tolerance,
454        )
455        .map_err(|error| {
456            if twist_angle == 0.0 {
457                error
458            } else {
459                error.with_message(|error| format!("sweep_profile_twisted: {error}"))
460            }
461        });
462    }
463
464    // Everything else — any multi-segment chain, and a single segment under
465    // `Rigid` — takes the same station law the single-curve twisted builder
466    // uses, so density scales with twist identically on a chained path.
467    // A CLOSED SPATIAL path lays its counter-twist down on top of the requested
468    // twist, which adds up to half a turn, so the density is set for the most the
469    // lap can roll.
470    let stations = if twist_angle == 0.0 {
471        32
472    } else {
473        let counter = if path.closed && path.planar.is_none() {
474            std::f64::consts::PI
475        } else {
476            0.0
477        };
478        let quarter_turns = ((twist_angle.abs() + counter) / FRAC_PI_2).ceil() as usize;
479        (quarter_turns * 16).clamp(32, 1024)
480    };
481    let _ = name;
482    sweep_profile_along_chain_stations(
483        profile,
484        path,
485        stations,
486        twist_angle,
487        anchor,
488        placement_mode,
489        corner_advice,
490        CornerPolicy::Mitre,
491        tolerance,
492    )
493}
494
495/// The wall tolerance a sweep is refined to: the caller's, or the default;
496/// refused when it is not a positive finite length.
497fn sweep_tolerance(tolerance: Option<f64>) -> Result<f64, KernelRefusal> {
498    let tolerance = tolerance.unwrap_or(SWEEP_DEFAULT_TOLERANCE);
499    if !(tolerance.is_finite() && tolerance > 0.0) {
500        return Err(KernelRefusal::input(
501            KernelStage::Collect,
502            "sweep_tolerance",
503            format!("sweepSolid: the requested wall tolerance must be a positive length, not {tolerance}"),
504        ));
505    }
506    Ok(tolerance)
507}
508
509/// [`sweep_profile_along_chain`] with an explicit STATION budget and no twist
510/// — the entry a caller with a long, smooth chain uses when the default 32
511/// stations would under-sample it (a wire-harness bundle along a many-anchor
512/// spline: three pieces per span, so a handful of spans already starves each
513/// piece of stations). The budget is spread over the chain by arc length
514/// exactly as the twisted builder's law spreads its own; the 1024-station cap
515/// and the tangent-continuity refusal apply unchanged.
516pub fn sweep_profile_along_chain_with_stations(
517    profile: &[NurbsCurve],
518    path: &SweepPath,
519    stations: usize,
520    corner_advice: &str,
521) -> Result<BrepSolid, KernelRefusal> {
522    sweep_profile_along_chain_with_stations_reported(profile, path, stations, corner_advice, None)
523        .map(|swept| swept.solid)
524}
525
526/// [`sweep_profile_along_chain_with_stations`] with the requested wall
527/// tolerance (`None` for the default) and the measured bound: the caller's
528/// budget is the FLOOR, refined where the measured deviation is over the
529/// tolerance.
530pub fn sweep_profile_along_chain_with_stations_reported(
531    profile: &[NurbsCurve],
532    path: &SweepPath,
533    stations: usize,
534    corner_advice: &str,
535    tolerance: Option<f64>,
536) -> Result<SweptChain, KernelRefusal> {
537    let tolerance = sweep_tolerance(tolerance)?;
538    sweep_profile_along_chain_stations(
539        profile,
540        path,
541        stations.clamp(2, 1024),
542        0.0,
543        None,
544        SectionPlacement::Transplant,
545        corner_advice,
546        CornerPolicy::Refuse,
547        tolerance,
548    )
549}
550
551/// Validate a closed planar profile loop and derive its placement anchor —
552/// the path sweep's §1 block, extracted bit-identically: 16 samples per curve,
553/// closure at `tolerance`, Newell normal, boundary-sample-mean origin,
554/// planarity at `tolerance * 100`, `pu = np.perpendicular()`, `pv = np × pu`.
555pub fn profile_anchor(profile: &[NurbsCurve]) -> Result<ProfileAnchor, KernelRefusal> {
556    let tolerance = 1e-6;
557    if profile.len() < 2 {
558        return Err(KernelRefusal::input(
559            KernelStage::Collect,
560            "profile_count",
561            "sweepSolid: profile needs at least 2 curves forming a closed loop",
562        ));
563    }
564    let mut samples = Vec::new();
565    for (index, curve) in profile.iter().enumerate() {
566        let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
567        let next = &profile[(index + 1) % profile.len()];
568        let next_start = next.domain().or_refuse(KernelStage::Collect, "domain")?[0];
569        if curve
570            .evaluate(end).or_refuse(KernelStage::Collect, "evaluate")?
571            .sub(next.evaluate(next_start).or_refuse(KernelStage::Collect, "evaluate")?)
572            .length()
573            > tolerance
574        {
575            return Err(KernelRefusal::input(
576                KernelStage::Collect,
577                "profile_closed",
578                format!("sweepSolid: profile is not closed at curve {index}"),
579            ));
580        }
581        for sample in 0..16 {
582            samples.push(curve.evaluate(start + (end - start) * sample as f64 / 16.0).or_refuse(KernelStage::Collect, "evaluate")?);
583        }
584    }
585    let normal = crate::polygon::newell_normal(&samples);
586    let centroid = samples.iter().fold(Vec3::default(), |sum, &point| sum.add(point));
587    let np = normal.normalized().map_err(|_| {
588        KernelRefusal::input(
589            KernelStage::Collect,
590            "profile_area",
591            "sweepSolid: profile is degenerate (zero enclosed area)",
592        )
593    })?;
594    let origin = centroid.scale(1.0 / samples.len() as f64);
595    if samples
596        .iter()
597        .any(|point| point.sub(origin).dot(np).abs() > tolerance * 100.0)
598    {
599        return Err(KernelRefusal::input(
600            KernelStage::Collect,
601            "profile_planar",
602            "sweepSolid: profile is not planar",
603        ));
604    }
605    let pu = np.perpendicular().or_refuse(KernelStage::Collect, "perpendicular")?;
606    let pv = np.cross(pu).normalized().or_refuse(KernelStage::Collect, "normalized")?;
607    Ok(ProfileAnchor {
608        origin,
609        normal: np,
610        pu,
611        pv,
612    })
613}
614
615/// Core of the path sweep with an explicit station count.  Every consumer of
616/// the station count (path sampling, RMF propagation, section placement)
617/// derives from the one `stations` argument so the density scales as a unit.
618/// `twist_angle` (radians; 0 for the untwisted variants) rotates the placed
619/// profile about the path tangent linearly in sampled arc length — the
620/// `twist_angle == 0.0` fast path leaves the RMF axes bit-identical, so the
621/// untwisted callers keep golden parity.
622fn sweep_profile_along_path_stations(
623    profile: &[NurbsCurve],
624    path: &NurbsCurve,
625    name: Option<&str>,
626    stations: usize,
627    twist_angle: f64,
628    anchor: Option<ProfileAnchor>,
629    placement_mode: SectionPlacement,
630    tolerance: f64,
631) -> Result<SweptChain, KernelRefusal> {
632    // Loft carries no face names; the app stamps them onto the emitted face
633    // order.  Accept `name` for ABI symmetry with the other builders.
634    let _ = name;
635    if stations < 2 {
636        return Err(KernelRefusal::input(
637            KernelStage::Collect,
638            "stations",
639            "sweepSolid: need at least 2 stations",
640        ));
641    }
642
643    // --- 1. Validate the profile: closed + planar; derive (origin, np, pu, pv).
644    //        A caller-supplied anchor OVERRIDES the placement frame (the swept
645    //        loop is still validated against its own plane), so a hole loop
646    //        rides the path in its outer loop's frame instead of re-centering.
647    //        Resolved HERE, before the path is touched, so a bad profile is
648    //        still reported ahead of a bad path exactly as it always was.
649    let placement = resolve_placement(profile, anchor, placement_mode)?;
650
651    // --- 2. Sample the path as a one-segment chain on the single-curve lane:
652    //        `stations` uniform in the parameter, the sampling this builder
653    //        always had, refined only where the measured deviation is over the
654    //        tolerance (`chain_stations`).
655    let chain = std::slice::from_ref(path);
656    let (samples, budget) = chain_stations(chain, false, SamplerLane::SingleCurve, stations, tolerance)?;
657    let StationSamples {
658        points,
659        tangents,
660        curvatures,
661        params,
662        ..
663    } = &samples;
664
665    sweep_sections_through_samples(
666        profile,
667        points,
668        tangents,
669        curvatures,
670        twist_angle,
671        placement,
672        placement_mode,
673        RingFrame::Open,
674        None,
675        None,
676        StationRun {
677            chain,
678            params,
679            budget,
680            tolerance,
681        },
682    )
683}
684
685/// What a CHAIN builder does with a CORNER (a `G0` joint).
686///
687/// Two of this module's entry points sweep chains, and they answer the question
688/// differently — not because the geometry differs but because their callers'
689/// corner POLICIES do, and a builder that guessed would be overriding one of
690/// them:
691///   - [`sweep_profile_along_chain`] MITRES a polyline's corners, a closed
692///     polyline's closing joint included (`sweep_topology/miter.rs`). Its callers
693///     are the two sweep FEATURES, and a mitred corner is the shape they are
694///     asked for.
695///   - [`sweep_profile_along_chain_with_stations`] REFUSES every corner. Its
696///     callers build their own chains and have already decided what a corner
697///     means: the tube ROUNDS one into a tangent bend or joins it with a ball,
698///     and the wire harness routes tangent-continuous splines. A corner
699///     reaching either of them means their own construction did not come out,
700///     and mitring it instead would silently ship a shape neither feature
701///     offers.
702#[derive(Debug, Clone, Copy, PartialEq, Eq)]
703enum CornerPolicy {
704    /// A polyline's corners are mitred, open or closed; anything else is refused.
705    Mitre,
706    /// Every corner is refused by name.
707    Refuse,
708}
709
710/// The SECTION a mitred sweep carries, placed in world, with its plane normal —
711/// the two things `sweep_topology/miter.rs` needs, and all it needs.
712///
713/// The placement modes are resolved HERE rather than in the mitre builder, on
714/// the same frame the skinning lane's station 0 uses (`û₀.perpendicular()`), so
715/// the two lanes place a section identically and a path that crosses the
716/// continuity gate does not also jump in space:
717///   - `Transplant` maps the profile's plane frame onto the path's first station
718///     (anchor origin onto the path, profile square to it), so the section's
719///     normal is the first tangent;
720///   - `Rigid` takes the profile WHERE IT IS, keeping the offset from the path
721///     and the angle to it that it was drawn with, so the section's normal is
722///     the profile's own.
723fn place_section(
724    profile: &[NurbsCurve],
725    placement: ProfileAnchor,
726    placement_mode: SectionPlacement,
727    start: Vec3,
728    tangent: Vec3,
729) -> Result<(Vec<NurbsCurve>, Vec3), KernelRefusal> {
730    if placement_mode == SectionPlacement::Rigid {
731        return Ok((profile.to_vec(), placement.normal));
732    }
733    let ProfileAnchor { origin, pu, pv, .. } = placement;
734    let r0 = tangent.perpendicular().or_refuse(KernelStage::Fragment, "perpendicular")?;
735    let s0 = tangent.cross(r0).normalized().or_refuse(KernelStage::Fragment, "normalized")?;
736    let mut placed = Vec::with_capacity(profile.len());
737    for curve in profile {
738        let control_points = curve
739            .control_points
740            .iter()
741            .map(|control| {
742                let point = control.point()?;
743                let local = point.sub(origin);
744                let world = start
745                    .add(r0.scale(local.dot(pu)))
746                    .add(s0.scale(local.dot(pv)));
747                Ok(Vec4::from_point(world, control.w))
748            })
749            .collect::<Result<Vec<_>, String>>()
750            .or_refuse(KernelStage::Fragment, "control_point")?;
751        placed.push(
752            NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
753                .or_refuse(KernelStage::Fragment, "curve_new")?,
754        );
755    }
756    Ok((placed, tangent))
757}
758
759/// The placement frame a sweep transplants its profile with: the caller's
760/// `anchor` when it supplied one (a hole loop riding its outer loop's frame),
761/// otherwise the profile's own. Either way the profile is VALIDATED — closed and
762/// planar — because `profile_anchor` is what does that validating, and skipping
763/// it for an anchored loop would let an open hole loop through.
764///
765/// Called by each SAMPLER before it touches the path, so the "bad profile" error
766/// still precedes the "bad path" one, as it did when the two lived in one
767/// function.
768fn resolve_placement(
769    profile: &[NurbsCurve],
770    anchor: Option<ProfileAnchor>,
771    placement_mode: SectionPlacement,
772) -> Result<ProfileAnchor, KernelRefusal> {
773    let computed = profile_anchor(profile)?;
774    Ok(match placement_mode {
775        // RIGID never transplants, so there is no frame to borrow: every loop
776        // keeps its own position already, which is the whole reason the anchor
777        // exists under `Transplant`. Taking a caller's anchor here would silently
778        // swap in another loop's NORMAL for the fold-back guard below.
779        SectionPlacement::Rigid => computed,
780        SectionPlacement::Transplant => anchor.unwrap_or(computed),
781    })
782}
783
784
785/// Sweep a CLOSED PLANAR profile along a CHAIN of path curves, joined
786/// head-to-tail, as one continuous tube — or, for a CLOSED path, as a capless
787/// ring.
788///
789/// The chain is sampled as a single trajectory and handed to the shared core,
790/// so ONE rotation-minimizing frame is propagated across the whole path: a joint
791/// is just another pair of adjacent stations to the RMF, which is what makes the
792/// profile arrive at the far end in the orientation the near end implies rather
793/// than snapping at each segment.
794///
795/// STATION BUDGET. `stations` are distributed across the segments in proportion
796/// to estimated ARC LENGTH (chord sums over 16 samples per curve), floored at 2
797/// per segment so a short fillet between two long lines still carries its
798/// curvature. The shared endpoint of two adjacent segments is sampled ONCE, not
799/// twice — a duplicated station would land in the RMF's coincident-step branch
800/// and waste a section on zero advance. A CLOSED path drops one more station for
801/// the same reason: its last station IS its first.
802///
803/// JOINTS decide the LANE. A break within [`MAX_JOINT_TANGENT_BREAK`] is skinned
804/// here; a break past it is a CORNER, which under [`CornerPolicy::Mitre`] hands an
805/// open all-straight run to the mitre builder (`sweep_topology/miter.rs`) and is
806/// otherwise refused by name, with the angle and the two segments. The
807/// classification carried on the path is what says so — this sampler no longer
808/// measures its own.
809#[allow(clippy::too_many_arguments)]
810fn sweep_profile_along_chain_stations(
811    profile: &[NurbsCurve],
812    path: &SweepPath,
813    stations: usize,
814    twist_angle: f64,
815    anchor: Option<ProfileAnchor>,
816    placement_mode: SectionPlacement,
817    corner_advice: &str,
818    corners: CornerPolicy,
819    tolerance: f64,
820) -> Result<SweptChain, KernelRefusal> {
821    let chain = path.curves.as_slice();
822    if chain.is_empty() {
823        return Err(KernelRefusal::input(
824            KernelStage::Collect,
825            "chain_empty",
826            "sweepSolid: path chain is empty",
827        ));
828    }
829    if stations < 2 {
830        return Err(KernelRefusal::input(
831            KernelStage::Collect,
832            "stations",
833            "sweepSolid: need at least 2 stations",
834        ));
835    }
836    // Profile first, matching the single-curve sampler's order of complaint.
837    let placement = resolve_placement(profile, anchor, placement_mode)?;
838
839    // --- The swept ENVELOPE, trimmed at its own self-intersection.
840    //
841    //     Past `ρκ = 1` the sections CROSS and the loft below skins a wall that
842    //     passes through itself. For a CIRCLE carried along one circular planar
843    //     arc the correct solid is a REVOLVE — the section disc truncated at the
844    //     axis, plus the reflection of the part that crossed it, each revolved
845    //     through the path's own turn (`sweep_topology/envelope.rs`) — and this
846    //     is where that lane is taken instead of the loft.
847    //
848    //     Anything else tight is left to the §4c refusal below, which now carries
849    //     WHICH half of the configuration this sweep missed. Nothing under
850    //     `ρκ = 1` reaches the lane at all: the recognition refuses a bend that
851    //     is not tighter than its section, so every shape that builds today keeps
852    //     the builder it has.
853    let envelope_gap =
854        match super::envelope::recognize_swept_envelope(profile, path, placement_mode)? {
855            Ok(plan) => {
856                let mut bodies = super::envelope::build_swept_envelope(&plan)?;
857                if bodies.len() == 1 {
858                    return Ok(SweptChain::exact(bodies.remove(0)));
859                }
860                return Err(KernelRefusal::unsupported(
861                    KernelStage::Fragment,
862                    "envelope_two_bodies",
863                    format!(
864                    "{}: a section that crosses the path's axis (ρ·κ = {:.6}) sweeps TWO \
865                     bodies — the near lobe over the path's own azimuths and the far lobe half \
866                     a turn from them, meeting only along the axis — and this entry returns one \
867                     solid. {} were built; ask `sweep_envelope_bodies` for the pair",
868                    SWEEP_ENVELOPE_REFUSAL,
869                    plan.ratio(),
870                    bodies.len()
871                    ),
872                ));
873            }
874            Err(reason) => reason,
875        };
876
877    // --- A CORNER, read off the path's classification. Every joint was measured
878    //     once when the path was resolved, the CLOSING joint of a closed path
879    //     included — which is how a ring's seam gets the same gate as its
880    //     interior joints instead of being the one joint nobody checked.
881    //
882    //     A corner now selects a LANE rather than ending the build. A POLYLINE —
883    //     every segment straight, at least one corner — is MITRED: the section is
884    //     swept along each segment and the two sweeps are trimmed to the joint's
885    //     bisector plane, sharing one face loop there
886    //     (`sweep_topology/miter.rs`). A CLOSED one is a picture FRAME, whose
887    //     closing joint is mitred like the rest and which has no caps; the frame
888    //     lane's own refusals (a spatial loop, by its holonomy; a self-crossing
889    //     loop; overlapping mitres) live with the construction. What remains
890    //     refused HERE is a corner on a path that is not all straight — there is
891    //     no bisector plane for a curve to be trimmed to, and no lane that mixes
892    //     the two.
893    if let Some(corner) = path.corner() {
894        if corners == CornerPolicy::Mitre && path.cornered_polyline() {
895            // A twist is laid down in arc length over the stations, and a mitre has
896            // none. A CLOSED frame rolls it along the middle of each side instead,
897            // where a roll keeps the shared joint loops (`sweep_topology/miter.rs`),
898            // exactly as it rolls its own counter-twist. An OPEN cornered run does
899            // not have that construction and is refused.
900            if twist_angle != 0.0 && !path.closed {
901                return Err(KernelRefusal::unsupported(
902                    KernelStage::Classify,
903                    "cornered_twist",
904                    "sweepSolid: a CORNERED path cannot carry a twist — its corners are mitred \
905                     from exact pieces that meet on the joint's bisector plane, and a twist laid \
906                     down along the path would roll the two sides of that plane apart, so they \
907                     would no longer share one loop there. Only a CLOSED frame rolls a twist along \
908                     the middle of its sides. Sweep the run without the twist; a \
909                     tangent-continuous (smooth) path is skinned through stations and carries one",
910                ));
911            }
912            let (section, section_normal, _) =
913                mitre_section(profile, placement, placement_mode, path)?;
914            return super::miter::sweep_section_mitered(
915                &section,
916                section_normal,
917                path,
918                twist_angle,
919            )
920            .map(SweptChain::exact);
921        }
922        // A path with BOTH a corner and a curved segment is in NEITHER lane, and
923        // this is the refusal that says so: the mitre lane needs every segment
924        // straight (one direction per side for the bisector plane to bisect) and
925        // the skinning lane needs every joint tangent-continuous (it interpolates
926        // stations, so it would round the corner off). A rounded rectangle with
927        // ONE corner left sharp is exactly that path — three G0 joints the mitre
928        // lane could carry and two G1 joints at an arc it cannot — and mitring
929        // the sharp corners while skinning the arc is a MIXED construction this
930        // builder does not have. Refused with both halves named rather than built
931        // as whichever lane happens to be asked first.
932        let curved = (0..path.len())
933            .find(|index| {
934                let curve = &path.curves[*index];
935                curve.degree != 1 || curve.control_points.len() != 2
936            })
937            .map(|index| format!(" — segment '{}' is CURVED", path.name(index)))
938            .unwrap_or_default();
939        // The MIXED-LANE sentence belongs only to a path that actually has a
940        // curved segment. Under [`CornerPolicy::Refuse`] an ALL-STRAIGHT cornered
941        // chain reaches this same refusal (the tube's and the wire harness's
942        // corners are refused whatever their segments are), and telling those
943        // callers that a straight cornered run is mitred would name a lane they
944        // deliberately do not have — their own `corner_advice` says what to do
945        // instead.
946        let mixed = if curved.is_empty() {
947            String::new()
948        } else {
949            " A path that MIXES the two — corners at some joints and curved segments elsewhere              — is in neither lane: every segment straight is mitred (open or closed), every              joint tangent-continuous is skinned, and nothing builds one construction for some              joints and the other for the rest."
950                .to_string()
951        };
952        return Err(KernelRefusal::unsupported(
953            KernelStage::Classify,
954            "corner",
955            format!(
956            "the path must be tangent-continuous: segments '{}' and '{}' meet at a {:.1}° \
957             corner{curved}. The profile is skinned between sampled stations along the path, so a \
958             corner would be ROUNDED OFF rather than mitred, and a mitre needs two STRAIGHT \
959             segments: it trims both sweeps to the plane that bisects their directions, and a \
960             curve has no single direction to bisect.{mixed} {corner_advice}",
961            path.name(corner.before),
962            path.name(corner.after),
963            corner.tangent_break.to_degrees()
964            ),
965        ));
966    }
967
968    // --- A CLOSED path takes a REQUESTED twist only where it closes. After one lap
969    //     the section comes back rolled by the whole twist, so the twist must be a
970    //     rotational symmetry of the section about the path. The ring lane reads
971    //     that off the section and refuses by name a twist that does not close
972    //     ([`closing_twist`]).
973
974    // --- A bend TIGHTER than the section is refused on the FLOOR stations,
975    //     before any are spent refining a run that folds, and so that the
976    //     refusal quotes the same stations whatever tolerance was asked
977    //     (`sweep_bend_profile` reads the same). Untwisted `Transplant` only —
978    //     the reach of a rolled section is the twisted placement's to read, in
979    //     §4c of `sweep_sections_through_samples`, which stays the backstop.
980    if placement_mode == SectionPlacement::Transplant
981        && twist_angle == 0.0
982        && std::env::var("BREP_SWEEP_BEND_GUARD").as_deref() != Ok("0")
983    {
984        let (floor, _) = chain_stations(path.curves.as_slice(), path.closed, SamplerLane::Chain, stations, 0.0)?;
985        let profile_stations = floor_bend_stations(profile, &placement, path, &floor)?;
986        if let Some(refusal) = tight_bend_refusal(&profile_stations, floor.points.len()) {
987            return Err(with_envelope_gap(refusal, Some(envelope_gap.as_str())));
988        }
989    }
990
991    // --- Sample the chain as ONE trajectory (budget, domains, stations), and
992    //     refine it to the requested tolerance.
993    let (samples, budget) = chain_stations(
994        path.curves.as_slice(),
995        path.closed,
996        SamplerLane::Chain,
997        stations,
998        tolerance,
999    )?;
1000    let StationSamples {
1001        points,
1002        tangents,
1003        curvatures,
1004        segments,
1005        params,
1006    } = &samples;
1007
1008    // --- CLOSED: the ring needs a frame that comes back to itself. A PLANAR path
1009    //     has one for free (see `ring_normal`); a SPATIAL one comes back rolled by
1010    //     its own holonomy and is closed by the counter-twist policy
1011    //     ([`RingFrame::Spatial`]).
1012    let closure = ring_frame(path, tangents)?;
1013
1014    sweep_sections_through_samples(
1015        profile,
1016        points,
1017        tangents,
1018        curvatures,
1019        twist_angle,
1020        placement,
1021        placement_mode,
1022        closure,
1023        Some(envelope_gap.as_str()),
1024        Some((segments.as_slice(), path)),
1025        StationRun {
1026            chain: path.curves.as_slice(),
1027            params,
1028            budget,
1029            tolerance,
1030        },
1031    )
1032}
1033
1034/// How a station run CLOSES — which frame a ring's sections are placed on.
1035///
1036/// Three states, because "is this a ring" and "is its frame written down in
1037/// closed form" are different questions and only a planar ring answers yes to
1038/// both:
1039///   - `Open`: the transported frame and two end caps;
1040///   - `Planar(normal)`: a ring whose reference axis is the path plane's normal
1041///     at every station, which returns to itself EXACTLY (see [`ring_normal`]);
1042///   - `Spatial`: a ring on the TRANSPORTED frame, which returns rolled by the
1043///     path's own holonomy and is closed by the counter-twist policy — see
1044///     [`ring_closure_frames`].
1045#[derive(Debug, Clone, Copy)]
1046enum RingFrame {
1047    Open,
1048    Planar(Vec3),
1049    Spatial,
1050}
1051
1052impl RingFrame {
1053    fn is_ring(self) -> bool {
1054        !matches!(self, RingFrame::Open)
1055    }
1056}
1057
1058/// The ring frame a path's stations close on, read off its classification.
1059fn ring_frame(path: &SweepPath, tangents: &[Vec3]) -> Result<RingFrame, KernelRefusal> {
1060    Ok(match (path.closed, path.planar) {
1061        (false, _) => RingFrame::Open,
1062        (true, Some(normal)) => RingFrame::Planar(ring_normal(normal, tangents)?),
1063        (true, None) => RingFrame::Spatial,
1064    })
1065}
1066
1067/// What a CLOSED sweep did to make its section meet itself after one lap — the
1068/// applied twist the frame-closure policy REPORTS.
1069///
1070/// THE POLICY. Carried once round a closed path, the section frame comes back
1071/// ROLLED about the start tangent by the path's HOLONOMY. That angle is not a
1072/// defect of the sampling: the frame is parallel transport of the section's
1073/// axes in the path's normal plane, which is parallel transport on the unit
1074/// sphere along the path's TANGENT INDICATRIX, so by Gauss–Bonnet the roll is
1075/// the solid angle that indicatrix encloses, modulo `2π`. A planar path's
1076/// indicatrix runs along one great circle and encloses a hemisphere — `2π`,
1077/// the identity — which is why a planar ring closes on its own; a spatial one
1078/// generally does not. (A curve lying ON a sphere reads zero too: the radial
1079/// direction is itself rotation-minimizing along any such curve. Its enclosed
1080/// solid angle is not its holonomy; its indicatrix's is.)
1081///
1082/// The sweep closes the ring with the SMALLEST roll that does it: the
1083/// counter-twist `−holonomy`, wrapped to `(−π, π]`.
1084///   - SMOOTH lane: laid down LINEARLY IN ARC LENGTH over the stations, the wrap
1085///     step from the last station back to station 0 included, so every span —
1086///     the seam span too — rolls at the same rate and the closed loft sees no
1087///     seam at all. A uniform rate is the distribution with the smallest peak
1088///     rate and the smallest `∫(roll rate)² ds`.
1089///   - CORNERED lane (`sweep_topology/miter.rs`): shared over the SEGMENTS in
1090///     proportion to their length, each share laid down over its segment's
1091///     untrimmed middle — a roll AT a mitre would pull the shared loop apart —
1092///     and nothing at all when the untwisted lap already closes within the
1093///     lane's own weld floor.
1094///
1095/// A REQUESTED twist rides on top of that counter-twist and is laid down the same
1096/// way, so `applied_twist = requested_twist − holonomy` (or `requested_twist` alone
1097/// where no counter-twist is needed). It closes only as a rotational symmetry of
1098/// the section about the path, `2π·n/k` for a section with `k` of them, and is
1099/// refused by name otherwise ([`crate::SWEEP_TWIST_CLOSURE_REFUSAL`]). A
1100/// FRACTIONAL turn on a symmetric section lands each wall on a different section
1101/// curve than it left: `curve_shift`.
1102///
1103/// `holonomy` is what the untwisted frame measures; `applied_twist` is what was
1104/// laid down. All three angles are radians, right-handed about the path tangent.
1105#[derive(Debug, Clone, Copy, PartialEq)]
1106pub struct SweepClosure {
1107    /// The roll the UNTWISTED frame returns with after one lap, right-handed
1108    /// about the start tangent, wrapped to `(−π, π]`. Zero for a planar path.
1109    pub holonomy: f64,
1110    /// The twist the caller asked for, snapped to the section symmetry it closes
1111    /// on (it matched at round-off). Zero for an untwisted sweep.
1112    pub requested_twist: f64,
1113    /// The twist laid down over the lap: the requested twist plus the
1114    /// counter-twist `−holonomy`, which is zero where the lane closes without one
1115    /// (a planar path, or a frame whose untwisted lap already closes within the
1116    /// weld floor).
1117    pub applied_twist: f64,
1118    /// How far along the section's curve list one lap carries each curve: the
1119    /// wall leaving section curve `j` arrives on curve `(j + curve_shift) mod m`.
1120    /// Zero for no twist and for a whole number of turns. The curves are counted
1121    /// in the order the builder carries them, which on the MITRE lane is the
1122    /// section's order after its winding is made counter-clockwise about the path.
1123    pub curve_shift: usize,
1124}
1125
1126/// The CLOSURE a sweep of `profile` along `path` applies — the frame-closure
1127/// policy's report, exposed so a caller can read the twist a closed sweep laid
1128/// down (see [`SweepClosure`]). `None` for an OPEN path, which has no lap to
1129/// close.
1130///
1131/// Reads the very construction the sweep builds, not a second measurement of
1132/// it: a cornered polyline asks the mitre lane's own frame plan (its placed
1133/// section, its rings, its weld floor), and any other closed path asks the
1134/// smooth lane's own stations and frames at `stations` — the budget the sweep
1135/// was given (32 for [`sweep_profile_along_chain`] untwisted, the caller's for
1136/// [`sweep_profile_along_chain_with_stations`]). Whatever the builder would
1137/// refuse, this refuses with the same words, a requested `twist_angle` that does
1138/// not close included.
1139pub fn sweep_closure(
1140    profile: &[NurbsCurve],
1141    path: &SweepPath,
1142    placement_mode: SectionPlacement,
1143    stations: usize,
1144    twist_angle: f64,
1145) -> Result<Option<SweepClosure>, KernelRefusal> {
1146    if !path.closed {
1147        return Ok(None);
1148    }
1149    let placement = resolve_placement(profile, None, placement_mode)?;
1150    if path.cornered_polyline() {
1151        let (section, section_normal, _) = mitre_section(profile, placement, placement_mode, path)?;
1152        return super::miter::mitred_frame_closure(&section, section_normal, path, twist_angle)
1153            .map(Some);
1154    }
1155    let (
1156        StationSamples {
1157            points,
1158            tangents,
1159            segments,
1160            ..
1161        },
1162        _,
1163    ) = chain_stations(
1164        path.curves.as_slice(),
1165        path.closed,
1166        SamplerLane::Chain,
1167        stations.clamp(2, 1024),
1168        SWEEP_DEFAULT_TOLERANCE,
1169    )?;
1170    let screw = Some((segments.as_slice(), path)).filter(|_| placement_mode == SectionPlacement::Rigid);
1171    let closure = ring_frame(path, &tangents)?;
1172    let (section, _) = place_section(profile, placement, placement_mode, points[0], tangents[0])?;
1173    let requested = ring_closing_twist(&section, &points, &tangents, twist_angle)?;
1174    Ok(station_frames(&points, &tangents, closure, screw, requested)?.2)
1175}
1176
1177/// The requested twist a RING closes on ([`closing_twist`]), read off the
1178/// section as placed at station 0, about the path's first tangent, against the
1179/// ring's own position floor: `1e-6` of the lap's chord length, the floor the
1180/// mitred frame measures its own closure against.
1181fn ring_closing_twist(
1182    section: &[NurbsCurve],
1183    points: &[Vec3],
1184    tangents: &[Vec3],
1185    twist_angle: f64,
1186) -> Result<ClosingTwist, KernelRefusal> {
1187    let lap: f64 = (0..points.len())
1188        .map(|index| points[(index + 1) % points.len()].sub(points[index]).length())
1189        .sum();
1190    closing_twist(section, points[0], tangents[0], twist_angle, 1e-6 * lap)
1191}
1192
1193/// The placed section a MITRED sweep carries and its plane normal, with the
1194/// first segment's chord direction — shared by the builder and by
1195/// [`sweep_closure`], so the instrument reads the section the frame is built
1196/// from.
1197fn mitre_section(
1198    profile: &[NurbsCurve],
1199    placement: ProfileAnchor,
1200    placement_mode: SectionPlacement,
1201    path: &SweepPath,
1202) -> Result<(Vec<NurbsCurve>, Vec3, Vec3), KernelRefusal> {
1203    let [t0, t1] = path.curves[0].domain().or_refuse(KernelStage::Collect, "domain")?;
1204    let start = path.curves[0].evaluate(t0).or_refuse(KernelStage::Collect, "evaluate")?;
1205    // The CHORD direction, which is both the first station's tangent (a
1206    // straight segment's derivative is its chord) and the direction the
1207    // mitre builder sweeps along, so the placed section is square to the
1208    // same vector the construction uses.
1209    let tangent = path.curves[0]
1210        .evaluate(t1).or_refuse(KernelStage::Collect, "evaluate")?
1211        .sub(start)
1212        .normalized()
1213        .map_err(|_| {
1214            KernelRefusal::input(
1215                KernelStage::Collect,
1216                "segment_length",
1217                "sweepSolid: path segment 0 has zero length",
1218            )
1219        })?;
1220    let (section, section_normal) =
1221        place_section(profile, placement, placement_mode, start, tangent)?;
1222    Ok((section, section_normal, tangent))
1223}
1224
1225/// The station frames §3 places its sections on, extracted so the tight-bend
1226/// INSTRUMENT ([`sweep_bend_profile`]) reads the frame the sweep will use — the
1227/// section's reach into a bend depends on how the section is ROLLED about the
1228/// path, so a second frame that merely agreed on a circle would be a different
1229/// measurement on anything else.
1230///
1231/// `screw` is the chain's segment-of-station map and the path whose
1232/// [`SweepPath::screw_axes`] it indexes, passed only by the `Rigid` placement.
1233/// A station on a HELIX segment is framed off the helix's own axis instead of
1234/// transported (see [`screw_reference`]); every other station takes the RMF step
1235/// from its predecessor, so the two compose across a joint in either direction.
1236///
1237/// The third value is the ring's CLOSURE report: `None` for an open run, zero
1238/// for a planar ring, and the measured holonomy with the counter-twist that
1239/// closes it for a spatial one — whose axes are returned already twisted.
1240///
1241/// `requested` is a RING's requested twist, already known to close
1242/// ([`closing_twist`]). It is laid down in the ring's frames over the whole lap,
1243/// the wrap chord included, together with any counter-twist, so the seam span
1244/// rolls at the rate every other span does. An OPEN run ignores it: its twist is
1245/// laid down by the placement, over the stations it has.
1246fn station_frames(
1247    points: &[Vec3],
1248    tangents: &[Vec3],
1249    closure: RingFrame,
1250    screw: Option<(&[usize], &SweepPath)>,
1251    requested: ClosingTwist,
1252) -> Result<(Vec<Vec3>, Vec<Vec3>, Option<SweepClosure>), KernelRefusal> {
1253    match closure {
1254        RingFrame::Open => {
1255            let (r_axes, s_axes) = transported_frames(points, tangents, screw)?;
1256            Ok((r_axes, s_axes, None))
1257        }
1258        RingFrame::Planar(normal) => {
1259            let mut r_axes = Vec::with_capacity(points.len());
1260            let mut s_axes = Vec::with_capacity(points.len());
1261            for tangent in tangents {
1262                // Project out any tangent component and re-normalize, so the frame is
1263                // orthonormal even where the fitted plane and the sampled tangent
1264                // disagree in the last bits.
1265                let r = normal
1266                    .sub(tangent.scale(normal.dot(*tangent)))
1267                    .normalized()
1268                    .map_err(|_| {
1269                        KernelRefusal::internal(
1270                            KernelStage::Classify,
1271                            "planar_frame",
1272                            "sweepSolid: the closed path's plane normal is parallel to its tangent",
1273                        )
1274                    })?;
1275                s_axes.push(tangent.cross(r).normalized().or_refuse(KernelStage::Classify, "normalized")?);
1276                r_axes.push(r);
1277            }
1278            if requested.twist != 0.0 {
1279                roll_over_the_lap(points, &mut r_axes, &mut s_axes, requested.twist)?;
1280            }
1281            Ok((
1282                r_axes,
1283                s_axes,
1284                Some(SweepClosure {
1285                    holonomy: 0.0,
1286                    requested_twist: requested.twist,
1287                    applied_twist: requested.twist,
1288                    curve_shift: requested.shift,
1289                }),
1290            ))
1291        }
1292        RingFrame::Spatial => {
1293            let (r_axes, s_axes, closure) =
1294                ring_closure_frames(points, tangents, screw, requested)?;
1295            Ok((r_axes, s_axes, Some(closure)))
1296        }
1297    }
1298}
1299
1300/// The frames of a closed SPATIAL ring: the transported frame, counter-twisted
1301/// by its own holonomy so the section meets itself (see [`SweepClosure`]).
1302///
1303/// MEASURED, not assumed. The run is transported ONE STEP FURTHER than an open
1304/// run goes — from the last station back to station 0, by the very rule every
1305/// other step takes (the RMF, or a helix segment's screw frame under `Rigid`) —
1306/// and the returned axis is compared with station 0's: the signed angle between
1307/// them, right-handed about the start tangent, is the holonomy `h`.
1308///
1309/// Then station `k`, at chord-length `s_k` round a lap of chord length `L`
1310/// (the wrap chord included), is rolled about its tangent by `φ_k = −h·s_k/L`.
1311/// Rolling about the tangent commutes with the transport step (each step is a
1312/// rotation carrying one tangent onto the next, and it carries a roll about the
1313/// first onto the same roll about the second), so the frame transported from
1314/// the last twisted station across the wrap arrives rolled by
1315/// `h − h·s_{n−1}/L`, and station 0 sits `−h·(L − s_{n−1})/L` further on — the
1316/// same rate as every other span. The ring closes with no seam to skin.
1317///
1318/// No new station law: the closed lane already floors its budget at 16 stations
1319/// per quarter turn of the path's TURNING, and a closed curve turns at least
1320/// `2π` (Fenchel), so a lap carries at least 64 stations. The largest roll this
1321/// lays down is `π`, under 3° a station — finer than the 16 per quarter turn a
1322/// requested twist gets.
1323///
1324/// A REQUESTED twist `T` that closes ([`closing_twist`]) rides on the same rate:
1325/// each station rolls by `(T − h)·s_k/L`, so the section comes back from the lap
1326/// rolled by `T` alone, onto itself. [`sweep_profile_along_chain`] sizes the
1327/// station budget for `|T| + π`.
1328fn ring_closure_frames(
1329    points: &[Vec3],
1330    tangents: &[Vec3],
1331    screw: Option<(&[usize], &SweepPath)>,
1332    requested: ClosingTwist,
1333) -> Result<(Vec<Vec3>, Vec<Vec3>, SweepClosure), KernelRefusal> {
1334    let stations = points.len();
1335    if stations < 2 {
1336        return Err(KernelRefusal::internal(
1337            KernelStage::Collect,
1338            "station_run",
1339            "sweepSolid: need at least 2 stations",
1340        ));
1341    }
1342    // The lap with its wrap: station 0 again, arriving as the LAST segment's end.
1343    let mut lap_points = points.to_vec();
1344    lap_points.push(points[0]);
1345    let mut lap_tangents = tangents.to_vec();
1346    lap_tangents.push(tangents[0]);
1347    let lap_segments: Option<Vec<usize>> = screw.map(|(segments, _)| {
1348        let mut extended = segments.to_vec();
1349        extended.push(segments[stations - 1]);
1350        extended
1351    });
1352    let lap_screw = match (&lap_segments, screw) {
1353        (Some(segments), Some((_, path))) => Some((segments.as_slice(), path)),
1354        _ => None,
1355    };
1356    let (mut r_axes, mut s_axes) = transported_frames(&lap_points, &lap_tangents, lap_screw)?;
1357    let returned = r_axes.pop().expect("a lap has a wrap station");
1358    s_axes.pop();
1359    let holonomy = returned.dot(s_axes[0]).atan2(returned.dot(r_axes[0]));
1360
1361    let applied = if requested.twist == 0.0 {
1362        -holonomy
1363    } else {
1364        requested.twist - holonomy
1365    };
1366    roll_over_the_lap(points, &mut r_axes, &mut s_axes, applied)?;
1367    Ok((
1368        r_axes,
1369        s_axes,
1370        SweepClosure {
1371            holonomy,
1372            requested_twist: requested.twist,
1373            applied_twist: applied,
1374            curve_shift: requested.shift,
1375        },
1376    ))
1377}
1378
1379/// Roll a ring's station frames about their tangents by `roll` over the lap,
1380/// linearly in chord length with the WRAP chord included: station `k` at `s_k`
1381/// of a lap of length `L` rolls by `roll·s_k/L`.
1382fn roll_over_the_lap(
1383    points: &[Vec3],
1384    r_axes: &mut [Vec3],
1385    s_axes: &mut [Vec3],
1386    roll: f64,
1387) -> Result<(), KernelRefusal> {
1388    let stations = points.len();
1389    let mut travelled = Vec::with_capacity(stations);
1390    let mut length = 0.0;
1391    for index in 0..stations {
1392        travelled.push(length);
1393        length += points[(index + 1) % stations].sub(points[index]).length();
1394    }
1395    if length <= 0.0 {
1396        return Err(KernelRefusal::internal(
1397            KernelStage::Classify,
1398            "lap_length",
1399            "sweepSolid: the closed path has zero length",
1400        ));
1401    }
1402    for station in 0..stations {
1403        let phi = roll * travelled[station] / length;
1404        let (sin_phi, cos_phi) = phi.sin_cos();
1405        let (r, s) = (r_axes[station], s_axes[station]);
1406        r_axes[station] = r.scale(cos_phi).add(s.scale(sin_phi));
1407        s_axes[station] = s.scale(cos_phi).sub(r.scale(sin_phi));
1408    }
1409    Ok(())
1410}
1411
1412/// The TRANSPORTED frames of a station run: seeded on an arbitrary perpendicular
1413/// to the first tangent and carried station to station — by the RMF, or by a
1414/// helix segment's screw frame under `Rigid` (see [`station_frames`]).
1415fn transported_frames(
1416    points: &[Vec3],
1417    tangents: &[Vec3],
1418    screw: Option<(&[usize], &SweepPath)>,
1419) -> Result<(Vec<Vec3>, Vec<Vec3>), KernelRefusal> {
1420    let stations = points.len();
1421    let mut r_axes = Vec::with_capacity(stations);
1422    let mut s_axes = Vec::with_capacity(stations);
1423    {
1424        let r0 = tangents[0].perpendicular().or_refuse(KernelStage::Classify, "perpendicular")?; // any unit vector ⟂ T0
1425        s_axes.push(tangents[0].cross(r0).normalized().or_refuse(KernelStage::Classify, "normalized")?);
1426        r_axes.push(r0);
1427        // The helix segment the running roll was fixed for, and that roll.
1428        let mut roll: Option<(usize, f64)> = None;
1429        for index in 0..stations - 1 {
1430            let t_next = tangents[index + 1];
1431            let helix = screw.and_then(|(segments, path)| {
1432                let segment = segments[index + 1];
1433                path.screw_axes[segment].map(|axis| (segment, axis, path))
1434            });
1435            let r_next = match helix {
1436                None => rmf_step(
1437                    r_axes[index],
1438                    tangents[index],
1439                    t_next,
1440                    points[index + 1].sub(points[index]),
1441                )
1442                .ok_or_else(|| {
1443                    KernelRefusal::internal(
1444                        KernelStage::Classify,
1445                        "frame_step",
1446                        format!("sweepSolid: frame degenerated at station {index}"),
1447                    )
1448                })?,
1449                Some((segment, axis, path)) => {
1450                    // The roll is fixed ONCE per helix segment, at the station it
1451                    // departs from — station 0, or the joint the previous segment
1452                    // arrived at — so the incoming frame continues without a snap.
1453                    let phi = match roll {
1454                        Some((fixed, phi)) if fixed == segment => phi,
1455                        _ => {
1456                            let tangent = tangents[index];
1457                            let reference =
1458                                screw_reference(axis, tangent, path.name(segment), index)?;
1459                            let r = r_axes[index];
1460                            let phi = tangent.dot(reference.cross(r)).atan2(reference.dot(r));
1461                            roll = Some((segment, phi));
1462                            phi
1463                        }
1464                    };
1465                    let reference = screw_reference(axis, t_next, path.name(segment), index + 1)?;
1466                    let (sin_phi, cos_phi) = phi.sin_cos();
1467                    reference
1468                        .scale(cos_phi)
1469                        .add(t_next.cross(reference).scale(sin_phi))
1470                }
1471            };
1472            s_axes.push(t_next.cross(r_next).normalized().or_refuse(KernelStage::Classify, "normalized")?);
1473            r_axes.push(r_next);
1474        }
1475    }
1476    Ok((r_axes, s_axes))
1477}
1478
1479/// A HELIX station's reference axis: the screw axis with its tangent component
1480/// removed, `normalize(W − (W·T)T)`.
1481///
1482/// Why this and not the transported frame: a helix is carried into itself by
1483/// ONE rigid motion — the screw about its axis — and that motion fixes both the
1484/// axis and the tangent's angle to it, so the axis' projection onto the normal
1485/// plane is the same body-fixed direction at every station. A frame built on it
1486/// IS the screw, so `R_k = F_k·F_0ᵀ` carries the profile about the coil's axis
1487/// and up its pitch. A rotation-minimizing frame has no spin about the tangent,
1488/// while the screw's frame spins at the helix's torsion `τ`, so the RMF rolls
1489/// away from it by `∫τ ds` — the rotation the user saw. On a TAPERED helix the
1490/// tangent's angle to the axis drifts with the radius, and this frame keeps the
1491/// section square to the axis all the same, which is what a tapered coil is.
1492///
1493/// Undefined only where the path runs ALONG its own axis, which a helix of
1494/// positive radius never does; refused by name there rather than guessed.
1495fn screw_reference(axis: Vec3, tangent: Vec3, segment: &str, station: usize) -> Result<Vec3, KernelRefusal> {
1496    axis.sub(tangent.scale(axis.dot(tangent)))
1497        .normalized()
1498        .map_err(|_| {
1499            KernelRefusal::ill_posed(
1500                KernelStage::Classify,
1501                "screw_reference",
1502                format!(
1503                "sweepSolid: path segment '{segment}' runs along its own helix axis at station \
1504                 {station}, so the screw motion that carries the section has no direction \
1505                 about the path there"
1506                ),
1507            )
1508        })
1509}
1510
1511/// The stations a path is sampled at, and what each one carries: the point, the
1512/// unit tangent, and the CURVATURE VECTOR `κ·N̂` — the path's own bend there,
1513/// measured from the curve rather than differenced off the station polyline,
1514/// because it is the number the tight-bend refusal quotes.
1515pub(crate) struct StationSamples {
1516    pub(crate) points: Vec<Vec3>,
1517    pub(crate) tangents: Vec<Vec3>,
1518    /// `κ·N̂` per station: its length is the curvature and its direction points
1519    /// at the centre of the osculating circle. Zero on a straight piece.
1520    pub(crate) curvatures: Vec<Vec3>,
1521    /// The path SEGMENT each station belongs to. A joint station is emitted by
1522    /// the segment ARRIVING at it, so it carries that segment's index.
1523    pub(crate) segments: Vec<usize>,
1524    /// Where each station sits for the span AFTER it: the segment it departs
1525    /// into and its parameter there ([`StationParam`]).
1526    pub(crate) params: Vec<StationParam>,
1527}
1528
1529/// The CURVATURE VECTOR of a curve from its first two derivatives:
1530///
1531/// ```text
1532///     κ·N̂ = (r̈ − (r̈·T̂)T̂) / |ṙ|²,      T̂ = ṙ/|ṙ|
1533/// ```
1534///
1535/// the component of the second derivative perpendicular to the tangent over the
1536/// squared speed — the reparameterization-invariant form, so a non-uniformly
1537/// parameterized path reads its own geometric bend rather than its
1538/// parameterization's. A degree-1 piece has a zero second derivative
1539/// (`derivatives` pads past the degree), so a straight segment reads exactly
1540/// zero and needs no special case.
1541pub(crate) fn curvature_vector(first: Vec3, second: Vec3) -> Vec3 {
1542    let speed_squared = first.dot(first);
1543    if speed_squared <= 0.0 {
1544        return Vec3::default();
1545    }
1546    let tangent = first.scale(1.0 / speed_squared.sqrt());
1547    second
1548        .sub(tangent.scale(second.dot(tangent)))
1549        .scale(1.0 / speed_squared)
1550}
1551
1552/// Which sampler asked for the stations — the two differ in their FLOOR and
1553/// in the words of the degenerate-tangent refusal, both pinned by callers.
1554#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1555enum SamplerLane {
1556    /// The chain sweep: every segment floored at its own turning, 16 stations
1557    /// a quarter turn.
1558    Chain,
1559    /// The single-curve builders (`sweep_profile_along_path` and family): the
1560    /// budget [`path_turning_stations`] hands them, uniform in the parameter,
1561    /// exactly as they always sampled — no turning floor on top, so an
1562    /// untwisted single-curve sweep that reads inside the tolerance is
1563    /// bit-identical to the tree before refinement existed.
1564    SingleCurve,
1565}
1566
1567/// Sample a CHAIN as ONE trajectory: the per-segment arc-length estimate, the
1568/// station budget it implies, and the stations themselves — then REFINE the
1569/// stations where the loft's own interpolant of them would stand off the path
1570/// by more than `tolerance` (`sweep_topology/stations.rs`).
1571///
1572/// Extracted from the chain sweep so the tight-bend INSTRUMENT
1573/// ([`sweep_bend_profile`]) measures the very stations the sweep lofts through,
1574/// rather than a second sampling that agrees with it today.
1575///
1576/// STATION BUDGET. `stations` are distributed across the segments in proportion
1577/// to estimated ARC LENGTH (chord sums over 16 samples per curve), floored at 2
1578/// per segment so a short fillet between two long lines still carries its
1579/// curvature, and — on the chain lane — at the segment's own TURNING at 16
1580/// stations per quarter turn, the density the twisted builder already uses.
1581/// That floor is the measured case behind the error rule: shared out by length
1582/// alone, a rounded rectangle's four short corner arcs got the 2-station floor
1583/// and the ring cut the corners, 6.2 % under `A · perimeter` on a 30 × 18 path
1584/// with `r = 4`; the turning floor took the same path to 4.8e-4. The floor is
1585/// kept as the STARTING budget on both lanes; the error rule below is what
1586/// takes the rest.
1587///
1588/// WHAT THE ERROR RULE REPLACES. Until 2026-09-30 an OPEN path had its straight
1589/// segments LIFTED to the density its turning segments were floored at
1590/// (`floor_total × straight length / curved length`), because a coil with a
1591/// straight lead of 2 stations bowed through the lead (2.7e-5 off Pappus on a
1592/// lead of 10, 5.0e-4 on 100). Measured on 2026-09-30, that lift put a pipe of
1593/// two 100-long legs round a 2-radius quarter bend at the 1024-station cap
1594/// (correct, at 25× the stations it needs), and REFUSED the same pipe at
1595/// `r = 1.5`, and any spatial variant, as "past the 1024-station cap" — a
1596/// legitimate sweep refused for its own budget. The rule below reads the bow
1597/// where it is and puts stations there; the lead of 100 gets a handful next to
1598/// the joint instead of a thousand along its length.
1599///
1600/// THE RULE. The loft interpolates each control-point column with one cubic
1601/// through the stations at shared chord parameters; the same fit through the
1602/// station POINTS is the loft's centre track. Per span, the track's distance
1603/// from the true path at the quarter points is measured
1604/// (`stations::spine_deviations`); a span over `tolerance` is split into
1605/// `ceil((deviation / tolerance)^(1/4))` equal parameter steps (the cubic's
1606/// `h⁴` law), and the run is re-measured. At most [`SWEEP_REFINEMENT_ROUNDS`]
1607/// rounds; a round that would pass the [`SWEEP_MAX_STATIONS`] cap refines the
1608/// worst spans as far as the cap allows and the budget records `at_cap` — the
1609/// sweep still builds and its report says the tolerance was not met.
1610/// `BREP_SWEEP_STATION_REFINEMENT=0` switches the rule off (the bite proof).
1611///
1612/// The shared endpoint of two adjacent segments is sampled ONCE, not twice — a
1613/// duplicated station would land in the RMF's coincident-step branch and waste
1614/// a section on zero advance. A CLOSED path drops one more station for the
1615/// same reason: its last station IS its first.
1616fn chain_stations(
1617    chain: &[NurbsCurve],
1618    closed: bool,
1619    lane: SamplerLane,
1620    stations: usize,
1621    tolerance: f64,
1622) -> Result<(StationSamples, StationBudget), KernelRefusal> {
1623    let position_tolerance = 1e-6;
1624    // --- Per-segment arc-length estimate, and the domain each one is sampled
1625    //     over. A degenerate domain is refused here rather than producing a
1626    //     silently collapsed station block.
1627    //
1628    //     Each segment's TURNING — the total angle its tangent sweeps — is measured
1629    //     too, because that, not its length, is what decides how many stations it
1630    //     needs (see the floor below).
1631    let mut domains = Vec::with_capacity(chain.len());
1632    let mut lengths = Vec::with_capacity(chain.len());
1633    let mut turning = Vec::with_capacity(chain.len());
1634    for (index, curve) in chain.iter().enumerate() {
1635        let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
1636        if (t1 - t0).abs() <= position_tolerance {
1637            return Err(KernelRefusal::input(
1638                KernelStage::Collect,
1639                "path_domain",
1640                match lane {
1641                    SamplerLane::Chain => format!("sweepSolid: path segment {index} has a degenerate domain"),
1642                    SamplerLane::SingleCurve => "sweepSolid: path domain is degenerate".to_string(),
1643                },
1644            ));
1645        }
1646        let mut length = 0.0;
1647        let mut previous = curve.evaluate(t0).or_refuse(KernelStage::Collect, "evaluate")?;
1648        for sample in 1..=16 {
1649            let point = curve.evaluate(t0 + (t1 - t0) * sample as f64 / 16.0).or_refuse(KernelStage::Collect, "evaluate")?;
1650            length += point.sub(previous).length();
1651            previous = point;
1652        }
1653        domains.push([t0, t1]);
1654        lengths.push(length);
1655        // `segment_turning` is a stringly reading of the curve's unit tangents;
1656        // a failure there is a degenerate tangent, which is the path's fault.
1657        // The single-curve lane never reads it: its budget was decided by
1658        // [`path_turning_stations`] and a path it cannot read is refused by the
1659        // sampling below, in that lane's own words.
1660        turning.push(match lane {
1661            SamplerLane::Chain => segment_turning(curve, [t0, t1]).map_err(|error| {
1662                KernelRefusal::input(
1663                    KernelStage::Classify,
1664                    "path_tangent",
1665                    format!("sweepSolid: path tangent is degenerate on segment {index}: {error}"),
1666                )
1667            })?,
1668            SamplerLane::SingleCurve => 0.0,
1669        });
1670    }
1671    let total_length: f64 = lengths.iter().sum();
1672    if total_length <= position_tolerance {
1673        return Err(KernelRefusal::input(
1674            KernelStage::Collect,
1675            "path_length",
1676            "sweepSolid: path chain has zero length",
1677        ));
1678    }
1679
1680    // --- Station budget per segment: proportional to arc length, floored at 2
1681    //     (a segment needs its two ends) and at the segment's turning, and the
1682    //     remainder handed to the longest segment so the totals land exactly on
1683    //     `stations`.
1684    let floors: Vec<usize> = turning
1685        .iter()
1686        .map(|turn| ((turn / std::f64::consts::FRAC_PI_2) * 16.0).ceil() as usize)
1687        .collect();
1688    let mut budget: Vec<usize> = lengths
1689        .iter()
1690        .zip(&floors)
1691        .map(|(length, floor)| {
1692            let share = (stations as f64 * length / total_length).round() as usize;
1693            share.max(*floor).max(2)
1694        })
1695        .collect();
1696    // Each interior joint shares one station between its two segments, so the
1697    // emitted total is sum(budget) - (segments - 1). A CLOSED path drops its very
1698    // last station too — it is the first one — so it emits one fewer again.
1699    let shared = chain.len() - 1 + usize::from(closed);
1700    let emitted: usize = budget.iter().sum::<usize>() - shared;
1701    // The 2-per-segment floor means a chain of n segments emits at least n+1
1702    // stations, so a long enough chain cannot be held under the loft's station
1703    // cap by any distribution. The loft's interpolation solve is O(stations³)
1704    // per control column, so silently accepting such a path would look like a
1705    // hang. Refuse with the count instead — the same honesty the twist cap uses.
1706    if emitted > SWEEP_MAX_STATIONS {
1707        return Err(KernelRefusal::unsupported(
1708            KernelStage::Collect,
1709            "station_cap",
1710            format!(
1711            "sweepSolid: a {}-segment path needs at least {emitted} stations, past the \
1712             {SWEEP_MAX_STATIONS}-station cap the loft solve can carry; sweep it in fewer, \
1713             longer pieces",
1714            chain.len()
1715            ),
1716        ));
1717    }
1718    if emitted < stations {
1719        let longest = lengths
1720            .iter()
1721            .enumerate()
1722            .max_by(|a, b| a.1.total_cmp(b.1))
1723            .map(|(index, _)| index)
1724            .unwrap_or(0);
1725        budget[longest] += stations - emitted;
1726    }
1727
1728    // --- The parameters each segment is sampled at: uniform over its domain at
1729    //     its budget, then refined where the measured deviation says so.
1730    let mut per_segment: Vec<Vec<f64>> = domains
1731        .iter()
1732        .zip(&budget)
1733        .map(|([t0, t1], count)| {
1734            (0..*count)
1735                .map(|sample| t0 + (t1 - t0) * sample as f64 / (count - 1) as f64)
1736                .collect()
1737        })
1738        .collect();
1739    let initial = per_segment.iter().map(Vec::len).sum::<usize>() - shared;
1740    let mut budget = StationBudget {
1741        initial,
1742        stations: initial,
1743        rounds: 0,
1744        at_cap: false,
1745        rounds_exhausted: false,
1746    };
1747    let refine = tolerance.is_finite() && tolerance > 0.0 && super::stations::refinement_enabled();
1748    let mut samples = sample_chain(chain, closed, lane, &domains, &per_segment)?;
1749    if refine {
1750        loop {
1751            let deviations = super::stations::spine_deviations(chain, &samples.params, &samples.points, closed)
1752                .map_err(|error| {
1753                    KernelRefusal::internal(
1754                        KernelStage::Refine,
1755                        "station_deviation",
1756                        format!("sweepSolid: the station deviation could not be read: {error}"),
1757                    )
1758                })?;
1759            if deviations.iter().all(|deviation| *deviation <= tolerance) {
1760                break;
1761            }
1762            if budget.rounds >= SWEEP_REFINEMENT_ROUNDS {
1763                budget.rounds_exhausted = true;
1764                break;
1765            }
1766            let emitted = samples.points.len();
1767            let (inserted, at_cap) = super::stations::refine_parameters(
1768                chain,
1769                &mut per_segment,
1770                &samples.params,
1771                &deviations,
1772                tolerance,
1773                closed,
1774                emitted,
1775            )
1776            .map_err(|error| {
1777                KernelRefusal::internal(
1778                    KernelStage::Refine,
1779                    "station_refinement",
1780                    format!("sweepSolid: the stations could not be refined: {error}"),
1781                )
1782            })?;
1783            budget.at_cap |= at_cap;
1784            if inserted == 0 {
1785                break;
1786            }
1787            budget.rounds += 1;
1788            samples = sample_chain(chain, closed, lane, &domains, &per_segment)?;
1789            if at_cap {
1790                break;
1791            }
1792        }
1793    }
1794    budget.stations = samples.points.len();
1795    Ok((samples, budget))
1796}
1797
1798/// Sample the chain at `per_segment`'s parameters as ONE trajectory: the
1799/// point, unit tangent and curvature vector at every station, the segment it
1800/// arrived on, and where it sits ([`StationParam`]).
1801fn sample_chain(
1802    chain: &[NurbsCurve],
1803    closed: bool,
1804    lane: SamplerLane,
1805    domains: &[[f64; 2]],
1806    per_segment: &[Vec<f64>],
1807) -> Result<StationSamples, KernelRefusal> {
1808    let mut points: Vec<Vec3> = Vec::new();
1809    let mut tangents: Vec<Vec3> = Vec::new();
1810    let mut curvatures: Vec<Vec3> = Vec::new();
1811    let mut segments: Vec<usize> = Vec::new();
1812    let mut params: Vec<StationParam> = Vec::new();
1813    for (index, curve) in chain.iter().enumerate() {
1814        let [t0, _] = domains[index];
1815        let list = &per_segment[index];
1816        let count = list.len();
1817        // Skip the first sample of every segment after the first: that station
1818        // is the joint, already emitted as the previous segment's last. On a
1819        // CLOSED path the LAST segment's last sample is skipped too — it is
1820        // station 0, and a ring that emitted it twice would interpolate a
1821        // zero-length span across its own seam.
1822        let first = usize::from(index > 0);
1823        if first == 1 {
1824            // THE JOINT reads the TIGHTER of the two pieces that meet there. A
1825            // G1 joint is tangent-continuous, not curvature-continuous — a line
1826            // running into a cubic hands over at κ = 0 and the cubic starts at
1827            // its own spike — and the station is emitted once, by the piece that
1828            // ARRIVES. Left as that, a path whose tightest bend sits at the
1829            // START of a curved piece would quote the straight piece's κ = 0 and
1830            // the bend would go unnamed; on the wire harness's own span the two
1831            // ends are mirror images and only ONE of them was being read.
1832            let derivatives = curve.derivatives_small(t0, 2).or_refuse(KernelStage::Collect, "derivatives")?;
1833            let arriving = curvature_vector(derivatives[1], derivatives[2]);
1834            if let Some(departing) = curvatures.last_mut() {
1835                if arriving.length() > departing.length() {
1836                    *departing = arriving;
1837                }
1838            }
1839            // The joint station departs into THIS segment.
1840            if let Some(joint) = params.last_mut() {
1841                *joint = StationParam { segment: index, t: t0 };
1842            }
1843        }
1844        let last = count - usize::from(closed && index + 1 == chain.len());
1845        for (sample, &t) in list.iter().enumerate().take(last).skip(first) {
1846            let derivatives = curve.derivatives_small(t, 2).or_refuse(KernelStage::Collect, "derivatives")?;
1847            let tangent = derivatives[1].normalized().map_err(|_| {
1848                KernelRefusal::input(
1849                    KernelStage::Classify,
1850                    "path_tangent",
1851                    match lane {
1852                        SamplerLane::Chain => format!("sweepSolid: path tangent is degenerate on segment {index}"),
1853                        SamplerLane::SingleCurve => format!("sweepSolid: path tangent is degenerate at station {sample}"),
1854                    },
1855                )
1856            })?;
1857            points.push(derivatives[0]);
1858            tangents.push(tangent);
1859            curvatures.push(curvature_vector(derivatives[1], derivatives[2]));
1860            segments.push(index);
1861            params.push(StationParam { segment: index, t });
1862        }
1863    }
1864    // A CLOSED path's seam is a joint like any other, and station 0 is the only
1865    // one whose two sides are sampled at opposite ends of the loop: the last
1866    // segment's end is station 0, and it was dropped rather than emitted.
1867    if closed {
1868        if let (Some(curve), Some(domain)) = (chain.last(), domains.last()) {
1869            let derivatives = curve.derivatives_small(domain[1], 2).or_refuse(KernelStage::Collect, "derivatives")?;
1870            let arriving = curvature_vector(derivatives[1], derivatives[2]);
1871            if let Some(departing) = curvatures.first_mut() {
1872                if arriving.length() > departing.length() {
1873                    *departing = arriving;
1874                }
1875            }
1876        }
1877    }
1878    Ok(StationSamples {
1879        points,
1880        tangents,
1881        curvatures,
1882        segments,
1883        params,
1884    })
1885}
1886
1887/// The ring frame's fixed reference axis: the path plane's own normal, oriented
1888/// once and reused at every station.
1889///
1890/// A planar path's rotation-minimizing frame IS the planar frame — the transport
1891/// has no component about the tangent, so the axis perpendicular to the plane is
1892/// carried unchanged the whole way round and comes back to itself EXACTLY. That
1893/// is what makes a closed planar sweep need no twist policy: the holonomy is
1894/// zero by construction, not by cancellation. Taking the plane normal as the
1895/// reference axis says so in the construction rather than hoping a
1896/// station-by-station transport returns to where it started.
1897///
1898/// The guard is the one case a fixed axis cannot serve: a tangent parallel to the
1899/// normal, which a planar path cannot have and a mis-fitted plane could.
1900fn ring_normal(normal: Vec3, tangents: &[Vec3]) -> Result<Vec3, KernelRefusal> {
1901    for (index, tangent) in tangents.iter().enumerate() {
1902        if tangent.cross(normal).length() < 0.5 {
1903            return Err(KernelRefusal::internal(
1904                KernelStage::Classify,
1905                "ring_normal",
1906                format!(
1907                "sweepSolid: the closed path's own plane normal is within 30° of its tangent \
1908                 at station {index}, so the path does not lie in that plane after all"
1909                ),
1910            ));
1911        }
1912    }
1913    normal.normalized().map_err(|_| {
1914        KernelRefusal::internal(
1915            KernelStage::Classify,
1916            "ring_normal_degenerate",
1917            "sweepSolid: the closed path's plane normal is degenerate",
1918        )
1919    })
1920}
1921
1922/// The total TURNING of one path segment: the angle its unit tangent sweeps over
1923/// its own domain, summed over 16 uniform steps — or, where a step turns more
1924/// than [`TURNING_ALIAS_STEP`], over 16 steps per knot span.
1925///
1926/// Not the same question as its length, and the one a station budget has to
1927/// answer: a straight segment of any length is carried exactly by two stations,
1928/// while a quarter arc of any radius needs enough stations that the cubic
1929/// interpolant through them does not cut the corner. 16 samples is the density
1930/// every other estimate in this builder uses — and it ALIASES a segment that
1931/// turns more than a few times: on an 8-turn coil each step is half a turn, and
1932/// the angle between two tangents cannot read more than π however far the curve
1933/// turned between them. A step that large is the sign, so only then is the
1934/// segment re-read densely; everything that reads calmly at 16 keeps exactly the
1935/// reading, and so exactly the floor, it always had (a half circle reads a hair
1936/// over π there, and a floor of 33 — the budget the closed lane is pinned at).
1937fn segment_turning(curve: &NurbsCurve, domain: [f64; 2]) -> Result<f64, String> {
1938    let (total, widest) = turning_at(curve, domain, 16)?;
1939    if widest <= TURNING_ALIAS_STEP {
1940        return Ok(total);
1941    }
1942    let spans = curve.knots.windows(2).filter(|pair| pair[1] > pair[0]).count();
1943    Ok(turning_at(curve, domain, (spans * 16).clamp(64, 8192))?.0)
1944}
1945
1946/// The widest tangent step [`segment_turning`] trusts at 16 samples: π/8, twice
1947/// the step of a quarter arc read at that density.
1948const TURNING_ALIAS_STEP: f64 = std::f64::consts::PI / 8.0;
1949
1950/// `(total turning, widest single step)` over `steps` uniform steps.
1951fn turning_at(curve: &NurbsCurve, domain: [f64; 2], steps: usize) -> Result<(f64, f64), String> {
1952    let [t0, t1] = domain;
1953    let mut total = 0.0;
1954    let mut widest: f64 = 0.0;
1955    // A stationary sample — a cusp in the parameterization, which an involute
1956    // flank's Hermite fit carries by construction — still has a direction of
1957    // travel, and the turning is a question about directions.
1958    let mut previous = curve.unit_tangent(t0, t0, t1)?;
1959    for sample in 1..=steps {
1960        let tangent = curve.unit_tangent(t0 + (t1 - t0) * sample as f64 / steps as f64, t0, t1)?;
1961        let step = previous.dot(tangent).clamp(-1.0, 1.0).acos();
1962        total += step;
1963        widest = widest.max(step);
1964        previous = tangent;
1965    }
1966    Ok((total, widest))
1967}
1968
1969/// ONE double-reflection step (Wang et al. 2008) of a rotation-minimizing frame:
1970/// carry the reference axis `r` from a station with tangent `t` to the next with
1971/// tangent `t_next` across the step vector `step`, then re-orthogonalize against
1972/// the new tangent to shed floating drift. `None` when the result degenerates.
1973///
1974/// Extracted so the frame the sections are placed on and the frame the holonomy
1975/// is measured with are the SAME transport rather than two copies of it.
1976fn rmf_step(r: Vec3, t: Vec3, t_next: Vec3, step: Vec3) -> Option<Vec3> {
1977    let c1 = step.dot(step);
1978    let candidate = if c1 <= 1e-18 {
1979        // Coincident stations: carry the reference axis forward unchanged.
1980        r
1981    } else {
1982        // First reflection across the plane bisecting the step vector.
1983        let reflected_r = r.sub(step.scale(2.0 / c1 * step.dot(r)));
1984        let reflected_t = t.sub(step.scale(2.0 / c1 * step.dot(t)));
1985        // Second reflection across the plane bisecting the tangents.
1986        let v2 = t_next.sub(reflected_t);
1987        let c2 = v2.dot(v2);
1988        if c2 <= 1e-18 {
1989            reflected_r
1990        } else {
1991            reflected_r.sub(v2.scale(2.0 / c2 * v2.dot(reflected_r)))
1992        }
1993    };
1994    candidate
1995        .sub(t_next.scale(candidate.dot(t_next)))
1996        .normalized()
1997        .ok()
1998}
1999
2000// ===========================================================================
2001// The TIGHT BEND: a section carried through a bend tighter than its own reach
2002// ===========================================================================
2003
2004/// How many points each profile curve contributes to the section's REACH.
2005///
2006/// The reach has to be a WITNESS — a point of the section that really does turn
2007/// back — so it is read off the curve itself and never off the control hull:
2008/// `make_arc` places a half-circle's middle controls at `r√2`, so a hull bound
2009/// would refuse a round section 41 % early. Sampling under-reads instead, which
2010/// is the safe direction: at 64 samples per curve a circle's support is short by
2011/// `r(1 − cos(π/128))` = 3.0e-4·r, so the guard can only ever refuse LATE, and a
2012/// bend that slips past it still meets the fold acceptance at the loft's exit.
2013const BEND_SECTION_SAMPLES: usize = 64;
2014
2015/// One station's tight-bend reading: what the path does there and how far the
2016/// section reaches into it.
2017///
2018/// The quantity that decides the sweep is [`BendStation::ratio`] — `reach·κ`,
2019/// the same `ρκ` the fillet's canal surface folds at. A section point offset `d`
2020/// towards the centre of the osculating circle advances `(1 − d·κ)` per unit of
2021/// path, so at `d·κ = 1` it stops and past it it goes BACKWARDS: the swept
2022/// envelope has turned back through itself and the solid is the envelope trimmed
2023/// at that self-intersection, not the loft through the crossing sections.
2024#[derive(Debug, Clone, Copy)]
2025pub struct BendStation {
2026    /// The station's index in the sweep's own station list.
2027    pub station: usize,
2028    /// Where it is on the path.
2029    pub point: Vec3,
2030    /// The path's curvature `κ` there (zero on a straight piece).
2031    pub curvature: f64,
2032    /// The path's radius of curvature `ρ = 1/κ`, `f64::INFINITY` where straight.
2033    pub radius: f64,
2034    /// How far the placed section reaches towards the centre of the bend —
2035    /// its support in the curvature-normal direction. Negative when the whole
2036    /// section sits on the OUTSIDE of the bend, zero where the path is straight.
2037    pub reach: f64,
2038    /// `reach·κ`. `< 1` builds; `≥ 1` folds.
2039    pub ratio: f64,
2040}
2041
2042/// The profile's sample points in the placement frame's own 2D coordinates
2043/// `(a, b) = ((x − origin)·pu, (x − origin)·pv)`.
2044///
2045/// Sampled ONCE: `Transplant` places the same 2D shape at every station
2046/// (`world = station + rᵢ·a + sᵢ·b`), so a station's reach is a pair of dot
2047/// products against the precomputed cloud rather than a re-evaluation of the
2048/// placed curves.
2049fn section_offsets(
2050    profile: &[NurbsCurve],
2051    placement: &ProfileAnchor,
2052) -> Result<Vec<(f64, f64)>, KernelRefusal> {
2053    let ProfileAnchor { origin, pu, pv, .. } = *placement;
2054    let mut offsets = Vec::with_capacity(profile.len() * BEND_SECTION_SAMPLES);
2055    for curve in profile {
2056        let [start, end] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
2057        for sample in 0..BEND_SECTION_SAMPLES {
2058            let t = start + (end - start) * sample as f64 / BEND_SECTION_SAMPLES as f64;
2059            let local = curve.evaluate(t).or_refuse(KernelStage::Classify, "evaluate")?.sub(origin);
2060            offsets.push((local.dot(pu), local.dot(pv)));
2061        }
2062    }
2063    Ok(offsets)
2064}
2065
2066/// The `ρκ` profile: one [`BendStation`] per station, in station order.
2067///
2068/// `axes` are the frames the sections are PLACED on (twist included), because
2069/// the reach is the section's support in the curvature-normal direction and a
2070/// non-round section rolled about the path presents a different support there.
2071fn bend_stations(
2072    points: &[Vec3],
2073    curvatures: &[Vec3],
2074    axes: &[(Vec3, Vec3)],
2075    offsets: &[(f64, f64)],
2076) -> Vec<BendStation> {
2077    (0..points.len())
2078        .map(|station| {
2079            let curvature = curvatures[station].length();
2080            if curvature <= 0.0 {
2081                return BendStation {
2082                    station,
2083                    point: points[station],
2084                    curvature: 0.0,
2085                    radius: f64::INFINITY,
2086                    reach: 0.0,
2087                    ratio: 0.0,
2088                };
2089            }
2090            // The curvature vector is perpendicular to the tangent by
2091            // construction, so its components on (r, s) are the whole of it.
2092            let normal = curvatures[station].scale(1.0 / curvature);
2093            let (r_axis, s_axis) = axes[station];
2094            let (nu, nv) = (normal.dot(r_axis), normal.dot(s_axis));
2095            let reach = offsets
2096                .iter()
2097                .map(|(a, b)| a * nu + b * nv)
2098                .fold(f64::NEG_INFINITY, f64::max);
2099            BendStation {
2100                station,
2101                point: points[station],
2102                curvature,
2103                radius: 1.0 / curvature,
2104                reach,
2105                ratio: reach * curvature,
2106            }
2107        })
2108        .collect()
2109}
2110
2111/// The `ρκ` profile a TRANSPLANT sweep of `profile` along `path` would carry at
2112/// `stations` stations — the instrument behind the refusal below, exposed so a
2113/// caller (or a probe) can measure a path BEFORE asking for the solid.
2114///
2115/// Reads the very stations the sweep's tight-bend refusal reads: the FLOOR
2116/// budget, before the error-driven refinement (`chain_stations`) adds any —
2117/// the same sampling, the same rotation-minimizing frame. A bend too tight
2118/// is decided and quoted on the floor stations so that a path which folds
2119/// is refused before stations are spent refining it, and so that the
2120/// refusal's numbers do not move with the tolerance. Untwisted, which is the
2121/// lane every caller of [`sweep_profile_along_chain_with_stations`] is in.
2122pub fn sweep_bend_profile(
2123    profile: &[NurbsCurve],
2124    path: &SweepPath,
2125    stations: usize,
2126) -> Result<Vec<BendStation>, KernelRefusal> {
2127    let placement = resolve_placement(profile, None, SectionPlacement::Transplant)?;
2128    let (samples, _) = chain_stations(
2129        path.curves.as_slice(),
2130        path.closed,
2131        SamplerLane::Chain,
2132        stations.clamp(2, 1024),
2133        0.0,
2134    )?;
2135    floor_bend_stations(profile, &placement, path, &samples)
2136}
2137
2138/// The `ρκ` profile of a TRANSPLANT sweep over `samples`, on the untwisted
2139/// ring or open frame those stations take — what [`sweep_bend_profile`]
2140/// reports and what the chain sweep refuses on before it refines.
2141fn floor_bend_stations(
2142    profile: &[NurbsCurve],
2143    placement: &ProfileAnchor,
2144    path: &SweepPath,
2145    samples: &StationSamples,
2146) -> Result<Vec<BendStation>, KernelRefusal> {
2147    let closure = ring_frame(path, &samples.tangents)?;
2148    let untwisted = ClosingTwist {
2149        twist: 0.0,
2150        shift: 0,
2151    };
2152    let (r_axes, s_axes, _) = station_frames(&samples.points, &samples.tangents, closure, None, untwisted)?;
2153    let axes: Vec<(Vec3, Vec3)> = r_axes.into_iter().zip(s_axes).collect();
2154    let offsets = section_offsets(profile, placement)?;
2155    Ok(bend_stations(&samples.points, &samples.curvatures, &axes, &offsets))
2156}
2157
2158/// A tight-bend refusal with the envelope lane's own measurement of WHICH
2159/// half of its one configuration the sweep missed appended, when there is
2160/// one — so the refusal names the boundary of what is built rather than
2161/// only the bend that is refused.
2162fn with_envelope_gap(refusal: KernelRefusal, envelope_gap: Option<&str>) -> KernelRefusal {
2163    match envelope_gap {
2164        Some(gap) if !gap.is_empty() => refusal.with_message(|refusal| {
2165            format!(
2166            "{refusal}. The swept envelope trimmed at its own self-intersection is built \
2167             for a CIRCLE carried along one circular planar arc, and this sweep is not \
2168             that: {gap}"
2169            )
2170        }),
2171        _ => refusal,
2172    }
2173}
2174
2175/// The prefix every tight-bend refusal starts with, so a caller can CLASSIFY one
2176/// (the wire harness reports it as a bundle status) without matching free text.
2177pub const SWEEP_TIGHT_BEND_REFUSAL: &str = "sweepSolid: the path bends TIGHTER than the section";
2178
2179/// The slug of the tight-bend refusal (`UnsupportedGeometry`), shared by its
2180/// one mint ([`tight_bend_refusal`]) and [`is_sweep_tight_bend`].
2181pub(crate) const SWEEP_TIGHT_BEND_WHAT: &str = "tight_bend";
2182
2183/// Is this the sweep's tight-bend refusal ([`SWEEP_TIGHT_BEND_REFUSAL`])? Read
2184/// off the class and its slug, so a caller that decides on it (the wire
2185/// harness's bundle status) follows the refusal, not its wording.
2186pub(crate) fn is_sweep_tight_bend(refusal: &KernelRefusal) -> bool {
2187    matches!(
2188        &refusal.class,
2189        crate::RefusalClass::UnsupportedGeometry { what } if what == SWEEP_TIGHT_BEND_WHAT
2190    )
2191}
2192
2193/// The refusal for a path that bends tighter than the section reaches, or `None`
2194/// when every station builds.
2195///
2196/// Quotes the WORST station rather than the first one scanned — the tightest
2197/// bend is the one the user has to ease, and a path can cross the bar in several
2198/// places (both ends of one Hermite span, typically).
2199fn tight_bend_refusal(profile: &[BendStation], stations: usize) -> Option<KernelRefusal> {
2200    let folded = profile.iter().filter(|station| station.ratio >= 1.0).count();
2201    if folded == 0 {
2202        return None;
2203    }
2204    let worst = profile
2205        .iter()
2206        .max_by(|a, b| a.ratio.total_cmp(&b.ratio))
2207        .expect("a folded station exists");
2208    // The solid exists — the envelope trimmed at its self-intersection — and
2209    // this lane does not build it: a named deferral.
2210    Some(KernelRefusal::unsupported(
2211        KernelStage::Classify,
2212        SWEEP_TIGHT_BEND_WHAT,
2213        format!(
2214        "{SWEEP_TIGHT_BEND_REFUSAL} at station {} of {stations} ({:.4}, {:.4}, {:.4}): the path's \
2215         radius of curvature there is {:.6} and the section reaches {:.6} into the bend, so \
2216         ρ·κ = {:.3} ≥ 1 ({folded} of {stations} stations do). A section carried through a bend \
2217         tighter than its own reach sweeps an envelope that passes through ITSELF — the solid \
2218         there is that envelope trimmed at its own self-intersection, which this lane does not \
2219         build: it skins the section between stations, and past ρ·κ = 1 the sections CROSS and \
2220         the wall folds. Ease the bend to a radius above {:.6}, or narrow the section until it \
2221         reaches no further than {:.6} (a round section of diameter {:.6})",
2222        worst.station,
2223        worst.point.x,
2224        worst.point.y,
2225        worst.point.z,
2226        worst.radius,
2227        worst.reach,
2228        worst.ratio,
2229        worst.reach,
2230        worst.radius,
2231        2.0 * worst.radius,
2232        ),
2233    ))
2234}
2235
2236/// The part of the sweep that does not care HOW the stations were sampled:
2237/// validate the profile, distribute the twist over the sampled polyline,
2238/// propagate the rotation-minimizing frame, place a profile copy per station
2239/// and loft through them.
2240///
2241/// Split out so a MULTI-SEGMENT path can share it
2242/// ([`sweep_profile_along_chain_stations`]). The single-curve sampler above is
2243/// deliberately left calling this with its OWN sampling rather than being
2244/// re-expressed as a one-element chain: two code paths that agree today are not
2245/// the same thing as one code path, and the untwisted single-curve geometry is
2246/// pinned by volume tests that must not move.
2247///
2248/// The RMF is propagated over the station sequence as a whole, so a chain's
2249/// frame carries across a joint exactly as it carries across any other pair of
2250/// adjacent stations — there is no per-segment restart to reconcile.
2251///
2252/// `closure` turns the run into a RING: anything but [`RingFrame::Open`] says the
2253/// stations come back round to station 0 (which is therefore NOT repeated at the
2254/// end). `Planar(normal)` says the path lies in the plane of that normal, so the
2255/// reference axis is fixed rather than transported — a planar frame, whose
2256/// holonomy round the loop is zero by construction. `Spatial` transports the
2257/// frame and closes it with the counter-twist policy ([`SweepClosure`]). Either
2258/// way the sections skin through a CLOSED loft: one face per section curve, no
2259/// end caps, `V − E + F = 0`. `Open` is the open run: transported frame, two end
2260/// caps, and the refusal below for a trajectory that closes anyway.
2261///
2262/// `chain` is the station-to-segment map and the classified path, from the chain
2263/// sampler; the single-curve sampler has none. Only `Rigid` reads it, to frame a
2264/// HELIX segment's stations off its screw axis ([`screw_reference`]).
2265/// The sampled run's geometry and budget, carried into
2266/// [`sweep_sections_through_samples`] for the report it writes.
2267struct StationRun<'a> {
2268    chain: &'a [NurbsCurve],
2269    params: &'a [StationParam],
2270    budget: StationBudget,
2271    tolerance: f64,
2272}
2273
2274#[allow(clippy::too_many_arguments)]
2275fn sweep_sections_through_samples(
2276    profile: &[NurbsCurve],
2277    points: &[Vec3],
2278    tangents: &[Vec3],
2279    curvatures: &[Vec3],
2280    twist_angle: f64,
2281    placement: ProfileAnchor,
2282    placement_mode: SectionPlacement,
2283    closure: RingFrame,
2284    envelope_gap: Option<&str>,
2285    chain: Option<(&[usize], &SweepPath)>,
2286    run: StationRun<'_>,
2287) -> Result<SweptChain, KernelRefusal> {
2288    let tolerance = 1e-6;
2289    let stations = points.len();
2290    if stations < 2 {
2291        return Err(KernelRefusal::internal(
2292            KernelStage::Collect,
2293            "station_run",
2294            "sweepSolid: need at least 2 stations",
2295        ));
2296    }
2297
2298    let ProfileAnchor { origin, pu, pv, .. } = placement;
2299
2300    // --- 2b. Twist distribution: cumulative ARC-LENGTH fractions over the
2301    //         sampled station polyline (chord sums), so the twist advances
2302    //         uniformly in space even on a non-uniformly parameterized path.
2303    //         Only computed when a twist is actually requested — the
2304    //         `twist_angle == 0.0` path must stay bit-identical to the
2305    //         pre-twist builder — and only on an OPEN run. These fractions stop at
2306    //         the last station, so a RING laid down by them would roll its wrap
2307    //         span at a different rate from every other; a ring rolls its twist
2308    //         in its frames instead, over the whole lap (§3).
2309    let twist_fractions: Option<Vec<f64>> = if twist_angle != 0.0 && !closure.is_ring() {
2310        let mut cumulative = vec![0.0; stations];
2311        let mut total = 0.0;
2312        for index in 1..stations {
2313            total += points[index].sub(points[index - 1]).length();
2314            cumulative[index] = total;
2315        }
2316        if total <= tolerance {
2317            return Err(KernelRefusal::input(
2318                KernelStage::Collect,
2319                "path_length",
2320                "sweepSolid: path has zero length; cannot distribute the twist",
2321            ));
2322        }
2323        for length in &mut cumulative {
2324            *length /= total;
2325        }
2326        Some(cumulative)
2327    } else {
2328        None
2329    };
2330
2331    // --- 3. The station frames.
2332    //
2333    //   OPEN: rotation-minimizing frames via the double-reflection method, seeded
2334    //   on an arbitrary perpendicular to T0 — arbitrary because `Rigid` cancels
2335    //   the seed out (`R_k = F_k·F_0ᵀ`) and `Transplant` has always taken whatever
2336    //   roll `perpendicular()` returned.
2337    //
2338    //   RING: the plane normal is the reference axis AT EVERY STATION. A planar
2339    //   path's RMF is that frame already — the transport has no component about
2340    //   the tangent — so this is not a different frame from the open lane's, it is
2341    //   the same frame written down in closed form instead of accumulated. Which
2342    //   matters for exactly one reason: written down, it returns to itself at the
2343    //   seam EXACTLY, so the ring's last section meets its first with no residual
2344    //   roll to skin away.
2345    //
2346    //   SPATIAL RING: the open lane's transported frame, carried one step further
2347    //   round the wrap to MEASURE the roll it returns with (the holonomy), and
2348    //   counter-twisted by that roll linearly in arc length so the lap's last span
2349    //   rolls at the same rate as every other and the ring meets itself
2350    //   (`ring_closure_frames`).
2351    //
2352    //   A REQUESTED twist on a RING is laid down in those frames too, over the
2353    //   whole lap with the wrap, on top of the counter-twist — but only a twist
2354    //   that closes: after the lap the section comes back rolled by it, so it must
2355    //   carry the section onto itself ([`closing_twist`], refused by name
2356    //   otherwise). A fractional turn on a symmetric section closes onto a
2357    //   DIFFERENT curve than it left, `shift` along, and the loft below is told.
2358    //
2359    //   RIGID on a HELIX segment: the helix's own screw frame (see
2360    //   `screw_reference`), which the RMF rolls away from by the helix's
2361    //   integrated torsion. `Transplant` keeps the RMF everywhere — it squares
2362    //   the section to the path and centres it there, and its callers (SWP, the
2363    //   tube, the harness) are not this contract.
2364    let screw = chain.filter(|_| placement_mode == SectionPlacement::Rigid);
2365    let requested = if closure.is_ring() && twist_angle != 0.0 {
2366        let (section, _) = place_section(profile, placement, placement_mode, points[0], tangents[0])?;
2367        ring_closing_twist(&section, points, tangents, twist_angle)?
2368    } else {
2369        ClosingTwist {
2370            twist: 0.0,
2371            shift: 0,
2372        }
2373    };
2374    let (r_axes, s_axes, _) = station_frames(points, tangents, closure, screw, requested)?;
2375
2376    // --- 3b. An OPEN trajectory that comes back to where it started cannot be
2377    //         capped: the first and last sections land on top of each other, and
2378    //         the loft's own complaint about that ("end sections coincide") says
2379    //         nothing about the path. Name it here instead, with the two things
2380    //         that do work. The check is on the PATH's first and last station
2381    //         POINTS, which is enough: a path that comes back to where it started
2382    //         puts the two caps in the same place whatever direction it arrives
2383    //         from — coincident when it also arrives pointing the same way,
2384    //         interpenetrating when it does not, and neither is a solid worth
2385    //         building.
2386    //
2387    //         TWO CLOSURE NOTIONS COEXIST, and deliberately. A path whose ends
2388    //         meet within the chainer's join band is CLASSIFIED closed and swept
2389    //         as a ring above — that is the shape a user drew as a loop. This band
2390    //         is a thousandth of the distance TRAVELLED, a hundred times looser,
2391    //         and it catches the run that is nearly a loop without being one: a
2392    //         359.7° arc whose caps would interpenetrate rather than coincide. The
2393    //         first is a shape with a construction; the second is an accident, and
2394    //         it is still refused. On a circular arc the band is the last ~0.36°
2395    //         before closure, so a 359° sweep still builds.
2396    if !closure.is_ring() {
2397        let travel: f64 = points
2398            .windows(2)
2399            .map(|pair| pair[1].sub(pair[0]).length())
2400            .sum();
2401        let gap = points[stations - 1].sub(points[0]).length();
2402        if travel > tolerance && gap <= 1e-3 * travel {
2403            // A run that is nearly a loop without being one: the input does not
2404            // say whether it is a ring or an open sweep, so neither is chosen.
2405            return Err(KernelRefusal::ill_posed(
2406                KernelStage::Classify,
2407                "near_closed_path",
2408                format!(
2409                "sweepSolid: the path returns to where it started ({gap:.3e} apart after \
2410                 travelling {travel:.3e}), so the sweep's two end caps would land on top of each \
2411                 other. A closed path swept this way IS a revolution — build it with Revolve \
2412                 about the same axis, or close the path exactly so it sweeps as a capless ring, \
2413                 or sweep the run in two halves and union them"
2414                ),
2415            ));
2416        }
2417    }
2418
2419    // --- 4. Place a transformed copy of the profile at each station, by the mode
2420    //        the caller asked for (see `SectionPlacement`).
2421    //
2422    //   TRANSPLANT maps the profile's own plane frame onto the station frame,
2423    //       world = P_k + r_k·(l·pu) + s_k·(l·pv),   l = x − origin
2424    //   which lands the anchor origin ON the path and the profile square to it.
2425    //   The profile's distance from the path and its angle to the path are both
2426    //   discarded — there is no term along the tangent to carry them.
2427    //
2428    //   RIGID applies the path's own motion to the profile where it stands,
2429    //       world = P_k + a·T_k + b·r_k + c·s_k,     (a,b,c) = (l·T_0, l·r_0, l·s_0)
2430    //                                                l = x − P_0
2431    //   which is `P_k + R_k·(x − P_0)` for `R_k = F_k·F_0ᵀ`, written in the frame
2432    //   basis rather than as a matrix. The tangent term `a·T_k` is exactly what
2433    //   TRANSPLANT drops, and carrying it is what preserves both the profile's
2434    //   offset from the path and its angle to it. At station 0 the frames
2435    //   coincide and the section IS the profile, so the START cap lies in the
2436    //   plane it was drawn in.
2437    let path_start = points[0];
2438    let (t0, r0, s0) = (tangents[0], r_axes[0], s_axes[0]);
2439    let rigid = placement_mode == SectionPlacement::Rigid;
2440    let mut sections: Vec<Vec<NurbsCurve>> = Vec::with_capacity(stations);
2441    // Only the RIGID guard below reads these; TRANSPLANT leaves them empty.
2442    let mut station_points: Vec<Vec<Vec3>> = Vec::with_capacity(if rigid { stations } else { 0 });
2443    let mut section_normals: Vec<Vec3> = Vec::with_capacity(if rigid { stations } else { 0 });
2444    let mut anchor_track: Vec<Vec3> = Vec::with_capacity(if rigid { stations } else { 0 });
2445    // The axes the section is actually PLACED on, twist included — what the
2446    // tight-bend guard below measures the section's reach in.
2447    let mut placed_axes: Vec<(Vec3, Vec3)> = Vec::with_capacity(stations);
2448    // The section's AFFINE placement per station, for the report: the image of
2449    // the anchor origin (the centre track) and the images of `pu` and `pv`.
2450    let mut centres: Vec<Vec3> = Vec::with_capacity(stations);
2451    let mut axes_1: Vec<Vec3> = Vec::with_capacity(stations);
2452    let mut axes_2: Vec<Vec3> = Vec::with_capacity(stations);
2453    for station in 0..stations {
2454        let station_origin = points[station];
2455        // Rotate the RMF axes about the tangent by the station's twist angle
2456        // (Rodrigues on vectors ⟂ the tangent: r' = r·cosφ + s·sinφ,
2457        // s' = s·cosφ − r·sinφ, since s = t × r and t × s = −r).
2458        let (ri, si) = match &twist_fractions {
2459            Some(fractions) => {
2460                let phi = twist_angle * fractions[station];
2461                let (sin_phi, cos_phi) = phi.sin_cos();
2462                let r = r_axes[station];
2463                let s = s_axes[station];
2464                (
2465                    r.scale(cos_phi).add(s.scale(sin_phi)),
2466                    s.scale(cos_phi).sub(r.scale(sin_phi)),
2467                )
2468            }
2469            None => (r_axes[station], s_axes[station]),
2470        };
2471        placed_axes.push((ri, si));
2472        let tk = tangents[station];
2473        let place = |x: Vec3| -> Vec3 {
2474            if rigid {
2475                let local = x.sub(path_start);
2476                station_origin
2477                    .add(tk.scale(local.dot(t0)))
2478                    .add(ri.scale(local.dot(r0)))
2479                    .add(si.scale(local.dot(s0)))
2480            } else {
2481                let local = x.sub(origin);
2482                station_origin
2483                    .add(ri.scale(local.dot(pu)))
2484                    .add(si.scale(local.dot(pv)))
2485            }
2486        };
2487        {
2488            let centre = place(origin);
2489            centres.push(centre);
2490            axes_1.push(place(origin.add(pu)).sub(centre));
2491            axes_2.push(place(origin.add(pv)).sub(centre));
2492        }
2493        if rigid {
2494            // The section's own normal takes the same rotation (a direction, so
2495            // `R_k` without the translation), and the anchor origin's track is
2496            // the profile's bulk motion for the near-parallel guard.
2497            let n0 = placement.normal;
2498            section_normals.push(
2499                tk.scale(n0.dot(t0))
2500                    .add(ri.scale(n0.dot(r0)))
2501                    .add(si.scale(n0.dot(s0))),
2502            );
2503            anchor_track.push(place(origin));
2504            station_points.push(Vec::with_capacity(
2505                profile.iter().map(|c| c.control_points.len()).sum(),
2506            ));
2507        }
2508        let mut section = Vec::with_capacity(profile.len());
2509        for curve in profile {
2510            let control_points = curve
2511                .control_points
2512                .iter()
2513                .map(|point| {
2514                    let weight = point.w;
2515                    let euclidean = Vec3::new(point.x / weight, point.y / weight, point.z / weight);
2516                    let world = place(euclidean);
2517                    if rigid {
2518                        station_points[station].push(world);
2519                    }
2520                    Vec4 {
2521                        x: world.x * weight,
2522                        y: world.y * weight,
2523                        z: world.z * weight,
2524                        w: weight,
2525                    }
2526                })
2527                .collect();
2528            section.push(NurbsCurve::new(
2529                curve.degree,
2530                curve.knots.clone(),
2531                control_points,
2532            ).or_refuse(KernelStage::Fragment, "curve_new")?);
2533        }
2534        sections.push(section);
2535    }
2536
2537    // --- 4b. RIGID only: refuse a sweep whose sections fold through each other.
2538    //
2539    // TRANSPLANT keeps every section square to the path, so it can only fold
2540    // where the path's curvature radius drops below the profile's extent — the
2541    // case this builder has always documented as the caller's to avoid. RIGID
2542    // can fold for a second, much more reachable reason: a turning path carries
2543    // the profile around the TURN'S OWN AXIS, so a profile straddling that axis
2544    // has one half advancing while the other retreats. That is not a tolerance
2545    // question, it is a sign question, so it is answered exactly.
2546    //
2547    // The placement map is AFFINE in `x`, so the advance is affine in `x` too and
2548    // its extremes over the section lie on the control points. Checking the hull
2549    // therefore bounds the advance over the curves AND over the region they
2550    // enclose — this is a proof, not a sampling.
2551    //
2552    // ON A RING the guard walks one step FURTHER: the wrap from the last station
2553    // back to station 0 is a step the sections take like any other, and it is the
2554    // one step an open run does not have. A ring whose wrap step folded while
2555    // every interior step advanced would otherwise pass. On a ring whose twist
2556    // lands each curve `shift` along, the wrap step's control points arrive on
2557    // that curve's: the flat control-point list of station 0, turned left by the
2558    // points of the `shift` curves before it (curves `j` and `j + shift` carry the
2559    // same number, which is what makes the turn a relabelling).
2560    let step_count = if closure.is_ring() {
2561        stations
2562    } else {
2563        stations - 1
2564    };
2565    let next_station = |station: usize| (station + 1) % stations;
2566    if rigid {
2567        let landing_offset: usize = profile[..requested.shift]
2568            .iter()
2569            .map(|curve| curve.control_points.len())
2570            .sum();
2571        let mut most_positive = 0.0f64;
2572        let mut most_negative = 0.0f64;
2573        let mut longest_step = 0.0f64;
2574        for station in 0..step_count {
2575            let normal = section_normals[station];
2576            let arriving = &station_points[next_station(station)];
2577            let turn = if next_station(station) == 0 { landing_offset } else { 0 };
2578            for (before, after) in station_points[station]
2579                .iter()
2580                .zip(arriving[turn..].iter().chain(&arriving[..turn]))
2581            {
2582                let step = after.sub(*before);
2583                longest_step = longest_step.max(step.length());
2584                let advance = step.dot(normal);
2585                most_positive = most_positive.max(advance);
2586                most_negative = most_negative.min(advance);
2587            }
2588        }
2589        // Scale-relative, and far below any geometric tolerance: this band only
2590        // has to separate a sign from floating noise, never a small motion from
2591        // a large one.
2592        let noise = 1e-9 * longest_step.max(tolerance);
2593        if most_positive > noise && most_negative < -noise {
2594            return Err(KernelRefusal::unsupported(
2595                KernelStage::Classify,
2596                "straddles_axis",
2597                "sweepSolid: the profile sweeps back through itself — part of it advances along \
2598                 the path while part of it retreats. A turning path carries the profile around \
2599                 the turn's own axis, so a profile that STRADDLES that axis folds into itself; \
2600                 move the profile clear of the axis, or sweep the run in pieces",
2601            ));
2602        }
2603        if most_positive <= noise && most_negative >= -noise {
2604            return Err(KernelRefusal::input(
2605                KernelStage::Classify,
2606                "no_advance",
2607                "sweepSolid: the path does not advance through the profile — it runs inside the \
2608                 profile plane, so the sweep encloses no volume",
2609            ));
2610        }
2611        // The near-parallel case, on the anchor origin's own track: the same 0.1
2612        // threshold `extrude_profile_brep` refuses a sliver at, so a STRAIGHT
2613        // path is accepted here exactly when the translational sweep of the same
2614        // profile and vector is. A station whose origin barely moves is skipped —
2615        // an origin sitting on the turn axis means the profile straddles it, and
2616        // the fold-back guard above has already spoken.
2617        for station in 0..step_count {
2618            let step = anchor_track[next_station(station)].sub(anchor_track[station]);
2619            let length = step.length();
2620            if length <= noise {
2621                continue;
2622            }
2623            if step.dot(section_normals[station]).abs() / length < 0.1 {
2624                return Err(KernelRefusal::input(
2625                    KernelStage::Classify,
2626                    "sliver",
2627                    "sweepSolid: the path is nearly parallel to the profile plane, which sweeps a \
2628                     sliver rather than a solid",
2629                ));
2630            }
2631        }
2632    }
2633
2634    // --- 4c. TRANSPLANT: refuse a path that bends TIGHTER than the section
2635    //         reaches, before the loft rather than after it.
2636    //
2637    // A section square to the path, offset `d` towards the centre of the
2638    // osculating circle, advances `(1 − d·κ)` per unit of path: at `d·κ = 1` it
2639    // stands still and past it it RETREATS, so consecutive sections cross and
2640    // the wall the loft skins through them passes through itself. That is the
2641    // same `ρκ > 1` the fillet's canal surface folds at, and the same defect the
2642    // soundness acceptance catches at the loft's exit — but caught THERE it can
2643    // only name a face and two parameters, where here it can name the station,
2644    // the bend and the section that does not fit through it.
2645    //
2646    // RIGID is not measured here: it does not keep the section square to the
2647    // path, so `ρκ` is not its criterion, and §4b above is its guard.
2648    //
2649    // The reach is a WITNESS and the curvature is the PATH's own, so this refuses
2650    // only where a real section point really does turn back. What it does not see
2651    // is a bend that peaks BETWEEN two stations — the loft interpolates those,
2652    // and the acceptance at the exit remains the backstop.
2653    if !rigid && std::env::var("BREP_SWEEP_BEND_GUARD").as_deref() != Ok("0") {
2654        let offsets = section_offsets(profile, &placement)?;
2655        let profile_stations = bend_stations(points, curvatures, &placed_axes, &offsets);
2656        if let Some(refusal) = tight_bend_refusal(&profile_stations, stations) {
2657            // The ENVELOPE lane builds this shape exactly for ONE configuration
2658            // (a circle on one circular planar arc), and a caller that lands here
2659            // has missed it (`with_envelope_gap`). An untwisted chain sweep was
2660            // already asked this on its floor stations; this is the backstop
2661            // for the twisted and single-curve runs, and for a bend that peaks
2662            // between floor stations and shows on the refined ones.
2663            return Err(with_envelope_gap(refusal, envelope_gap));
2664        }
2665    }
2666
2667    // --- 5. Loft through the swept sections.
2668    //
2669    //   OPEN: side walls plus two planar end caps.
2670    //
2671    //   RING: the CLOSED loft — the sections form a cycle, the last flowing back
2672    //   into the first through the same C² cyclic interpolation every interior
2673    //   span gets, so the seam is not a weld. One face per section curve and NO
2674    //   CAPS, which is the whole point: a ring has no ends to cap, and capping it
2675    //   would be two faces inside the material. The topology it emits is
2676    //   `c` corner vertices, `c` corner rings, `c` seam edges and `c` faces, so
2677    //   `V − E + F = c − 2c + c = 0` — the Euler characteristic of a torus, which
2678    //   is what a section carried once round a loop encloses.
2679    //   A RING whose requested twist lands each curve `shift` along skins each
2680    //   wall from its own curve into that one (`loft_profile_brep_closed_shifted`),
2681    //   so there is still one wall per section curve.
2682    //   The loft mints its own refusals; the wrap below keeps that class and
2683    //   prefixes the text.
2684    let solid = match closure {
2685        RingFrame::Planar(_) | RingFrame::Spatial => {
2686            // The loft mints its own refusals; its class rides through the
2687            // sweep's wrap (a station cap stays a deferral, the acceptance's
2688            // fold stays an UnsoundResult).
2689            crate::loft_profile_brep_closed_shifted(&sections, requested.shift).map_err(|error| {
2690                error.with_message(|error| {
2691                    format!("sweepSolid: closed loft through swept sections failed: {error}")
2692                })
2693            })?
2694        }
2695        RingFrame::Open => loft_profile_brep(&sections).map_err(|error| {
2696            error.with_message(|error| {
2697                format!("sweepSolid: loft through swept sections failed: {error}")
2698            })
2699        })?,
2700    };
2701
2702    // --- 6. The MEASURED BOUND of what was just built
2703    //        (`sweep_topology/stations.rs`): the loft's own interpolants of the
2704    //        centre track and the section axes against the true path and the
2705    //        transported frame, and the built volume by quadrature against the
2706    //        kinematic sweep's. Read off the very sections the loft skinned.
2707    let moments = super::stations::section_moments(profile, origin, pu, pv).map_err(|error| {
2708        KernelRefusal::internal(
2709            KernelStage::Refine,
2710            "section_moments",
2711            format!("sweepSolid: the section's area could not be read: {error}"),
2712        )
2713    })?;
2714    let (pu_in_frame, pv_in_frame) = if rigid {
2715        ([pu.dot(t0), pu.dot(r0), pu.dot(s0)], [pv.dot(t0), pv.dot(r0), pv.dot(s0)])
2716    } else {
2717        ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0])
2718    };
2719    let report = super::stations::station_report(&super::stations::PlacedRun {
2720        chain: run.chain,
2721        params: run.params,
2722        points,
2723        tangents,
2724        axes: &placed_axes,
2725        centres: &centres,
2726        e1: &axes_1,
2727        e2: &axes_2,
2728        pu_in_frame,
2729        pv_in_frame,
2730        closed: closure.is_ring(),
2731        sections: &sections,
2732        moments,
2733        reach: super::stations::section_reach(profile, origin),
2734        shift: requested.shift,
2735        budget: run.budget,
2736        tolerance: run.tolerance,
2737    })?;
2738    Ok(SweptChain {
2739        solid,
2740        report: Some(report),
2741    })
2742}
2743
2744/// Helical sweep (§5.7): sweep a CLOSED PLANAR profile loop along a helix of
2745/// `helix_radius` about the axis through `axis_origin` with direction
2746/// `axis_direction`, rising `pitch` per revolution for `turns` revolutions.
2747///
2748/// Sample a helix — `turns` revolutions about `axis_direction` from
2749/// `axis_origin`, starting at angle `start_angle` (radians, measured from the
2750/// axis frame's `u`) and rising `pitch` per turn, the radius running linearly
2751/// from `start_radius` to `end_radius` — uniformly in angle: 64 stations per
2752/// turn (at least 9, at most 4097 in total, so beyond 64 turns the per-turn
2753/// density thins). Returns the points and their chord parameters `s ∈ [0,1]`
2754/// (uniform-in-angle IS chord-length for a constant-radius helix, which is
2755/// what the averaged-knot interpolation assumes). `left_handed` winds the
2756/// angle the other way. The axis frame is `w = axis`, `u` = the component of
2757/// `reference` perpendicular to the axis (so angle zero points AT the
2758/// reference — the helix feature's local +X, or its start point), falling
2759/// back to `w.perpendicular()` when there is no usable reference, and
2760/// `v = w × u`. Shared by [`sweep_profile_helix`] and the HX feature, so the
2761/// coil a sweep builds and the edge a helix feature publishes agree exactly.
2762///
2763/// Errors on a degenerate axis, non-finite inputs, `turns ≤ 0`, more than 256
2764/// turns, a negative radius or pitch, or a helix that is a single point (both
2765/// radii AND the pitch zero).
2766#[allow(clippy::too_many_arguments)]
2767pub fn helix_sample_points(
2768    axis_origin: Vec3,
2769    axis_direction: Vec3,
2770    reference: Option<Vec3>,
2771    start_radius: f64,
2772    end_radius: f64,
2773    pitch: f64,
2774    turns: f64,
2775    start_angle: f64,
2776    left_handed: bool,
2777) -> Result<(Vec<Vec3>, Vec<f64>), KernelRefusal> {
2778    use std::f64::consts::TAU;
2779    let w = axis_direction.normalized().map_err(|_| {
2780        KernelRefusal::input(
2781            KernelStage::Collect,
2782            "helix_axis",
2783            "helix: axis direction is degenerate",
2784        )
2785    })?;
2786    for (name, value) in [
2787        ("radius", start_radius),
2788        ("end radius", end_radius),
2789        ("pitch", pitch),
2790        ("turns", turns),
2791        ("start angle", start_angle),
2792    ] {
2793        if !value.is_finite() {
2794            return Err(KernelRefusal::input(
2795                KernelStage::Collect,
2796                "helix_finite",
2797                format!("helix: {name} must be a finite number"),
2798            ));
2799        }
2800    }
2801    if start_radius < 0.0 || end_radius < 0.0 {
2802        return Err(KernelRefusal::input(
2803            KernelStage::Collect,
2804            "helix_radius",
2805            "helix: radius must not be negative",
2806        ));
2807    }
2808    if pitch < 0.0 {
2809        return Err(KernelRefusal::input(
2810            KernelStage::Collect,
2811            "helix_pitch",
2812            "helix: pitch must not be negative",
2813        ));
2814    }
2815    if turns <= 0.0 {
2816        return Err(KernelRefusal::input(
2817            KernelStage::Collect,
2818            "helix_turns",
2819            "helix: turns must be positive",
2820        ));
2821    }
2822    if turns > 256.0 {
2823        return Err(KernelRefusal::input(
2824            KernelStage::Collect,
2825            "helix_turns_limit",
2826            "helix: turns must be at most 256",
2827        ));
2828    }
2829    if start_radius == 0.0 && end_radius == 0.0 && pitch == 0.0 {
2830        return Err(KernelRefusal::input(
2831            KernelStage::Collect,
2832            "helix_point",
2833            "helix: zero radius and zero pitch describe a single point",
2834        ));
2835    }
2836    let u = match reference {
2837        Some(reference) => {
2838            let radial = reference.sub(w.scale(reference.dot(w)));
2839            radial
2840                .normalized()
2841                .or_else(|_| w.perpendicular())
2842                .or_refuse(KernelStage::Collect, "perpendicular")?
2843        }
2844        None => w.perpendicular().or_refuse(KernelStage::Collect, "perpendicular")?,
2845    };
2846    let v = w.cross(u).normalized().or_refuse(KernelStage::Collect, "normalized")?;
2847    let total_angle = turns * TAU;
2848    let height = pitch * turns;
2849    let sign = if left_handed { -1.0 } else { 1.0 };
2850    let count = ((turns * 64.0).ceil() as usize + 1).clamp(9, 4097);
2851    let mut points = Vec::with_capacity(count);
2852    let mut parameters = Vec::with_capacity(count);
2853    for index in 0..count {
2854        let s = index as f64 / (count - 1) as f64;
2855        let theta = start_angle + sign * total_angle * s;
2856        let radius = start_radius + (end_radius - start_radius) * s;
2857        points.push(
2858            axis_origin
2859                .add(u.scale(radius * theta.cos()))
2860                .add(v.scale(radius * theta.sin()))
2861                .add(w.scale(height * s)),
2862        );
2863        parameters.push(s);
2864    }
2865    Ok((points, parameters))
2866}
2867
2868/// [`helix_sample_points`] fitted as ONE cubic curve (global interpolation —
2869/// `interpolate_curve`, the machinery every fitted path here uses). Cubic
2870/// interpolation error on a circle of radius R with node spacing Δθ is
2871/// ≈ R·Δθ⁴/384: ~2·10⁻⁷·R at 64 stations per turn.
2872#[allow(clippy::too_many_arguments)]
2873pub fn fit_helix_curve(
2874    axis_origin: Vec3,
2875    axis_direction: Vec3,
2876    reference: Option<Vec3>,
2877    start_radius: f64,
2878    end_radius: f64,
2879    pitch: f64,
2880    turns: f64,
2881    start_angle: f64,
2882    left_handed: bool,
2883) -> Result<NurbsCurve, KernelRefusal> {
2884    let (points, parameters) = helix_sample_points(
2885        axis_origin,
2886        axis_direction,
2887        reference,
2888        start_radius,
2889        end_radius,
2890        pitch,
2891        turns,
2892        start_angle,
2893        left_handed,
2894    )?;
2895    interpolate_curve(&points, 3, &parameters).or_refuse(KernelStage::Refine, "interpolate")
2896}
2897
2898/// The helix is transcendental, not exactly NURBS-representable, so the path
2899/// is FIT: points (R·cosθ, R·sinθ, pitch·θ/2π) in the axis frame are sampled
2900/// uniformly in θ and globally interpolated with a cubic (`interpolate_curve`
2901/// — the same machinery every other fitted path here uses).  DENSITY: 64
2902/// samples per turn, capped at 1025 total nodes.  Cubic interpolation error
2903/// on a circle of radius R with node spacing Δθ is ≈ R·Δθ⁴/384: ~2·10⁻⁷·R at
2904/// 64/turn, and still ~6·10⁻⁵·R at the cap's worst case (16/turn at the
2905/// 64-turn limit) — orders below any profile a caller could sweep without
2906/// self-intersecting.  Uniform-in-θ parameters are exact chord-length for a
2907/// helix (constant speed), which is what the averaged-knot interpolation
2908/// assumes.
2909///
2910/// The fitted path then drives the EXISTING path-sweep core with 32 stations
2911/// per turn (min 32, capped at 1024 — the loft's dense interpolation solve is
2912/// O(stations³) per control column, so the cap trades per-turn density, never
2913/// correctness, at high turn counts).
2914///
2915/// GUARDS beyond the path sweep's own: the path sweep documents
2916/// self-intersection as caller responsibility, so the helix variant — which
2917/// knows its curvature analytically — rejects the two garbage modes itself:
2918///   • fold-over: the helix curvature radius (R² + c²)/R (c = pitch/2π) must
2919///     exceed the profile's max extent about its centroid, or the tube folds
2920///     through itself on the inner side (the torus tube-radius > major-radius
2921///     failure, pitch-relaxed);
2922///   • coil collision (turns ≥ 1): the normal gap between consecutive coils,
2923///     pitch·2πR/√((2πR)² + pitch²), must exceed the profile diameter.
2924/// Both use the profile's max sample distance from its centroid — conservative
2925/// for asymmetric profiles (extent in a harmless direction still counts), but
2926/// a false reject beats silent garbage.
2927///
2928/// SHALLOW COILS BUILD. They did not until 2026-09-08: the loft measured its
2929/// advance by the END-TO-END chord, which on a whole-turn helix is purely
2930/// AXIAL while both caps face nearly tangentially, so `|n·chord|` fell under
2931/// the loft's 0.1 sliver band and everything with pitch ≲ 0.63·R — most
2932/// springs — was refused. The loft measures the advance at each END now
2933/// (`loft_topology::basic::advance_from`), which is the direction the tube
2934/// actually grows through the cap it is orienting, so the band only ever
2935/// catches a real sliver.
2936pub fn sweep_profile_helix(
2937    profile: &[NurbsCurve],
2938    axis_origin: Vec3,
2939    axis_direction: Vec3,
2940    helix_radius: f64,
2941    pitch: f64,
2942    turns: f64,
2943    name: Option<&str>,
2944) -> Result<BrepSolid, KernelRefusal> {
2945    use std::f64::consts::TAU;
2946
2947    // --- 1. Validate the helix parameters with honest errors.
2948    let w = axis_direction.normalized().map_err(|_| {
2949        KernelRefusal::input(
2950            KernelStage::Collect,
2951            "helix_axis",
2952            "sweep_profile_helix: axis direction is degenerate",
2953        )
2954    })?;
2955    if !(helix_radius.is_finite() && helix_radius > 0.0) {
2956        return Err(KernelRefusal::input(
2957            KernelStage::Collect,
2958            "helix_radius",
2959            "sweep_profile_helix: helix radius must be positive",
2960        ));
2961    }
2962    if !(pitch.is_finite() && pitch > 0.0) {
2963        return Err(KernelRefusal::input(
2964            KernelStage::Collect,
2965            "helix_pitch",
2966            "sweep_profile_helix: pitch must be positive",
2967        ));
2968    }
2969    if !(turns.is_finite() && turns > 0.0) {
2970        return Err(KernelRefusal::input(
2971            KernelStage::Collect,
2972            "helix_turns",
2973            "sweep_profile_helix: turns must be positive",
2974        ));
2975    }
2976    // 64 turns bounds the loft's O(stations³) interpolation solve; beyond it
2977    // the station cap would silently degrade per-turn density anyway.
2978    if turns > 64.0 {
2979        return Err(KernelRefusal::unsupported(
2980            KernelStage::Collect,
2981            "helix_turns_cap",
2982            "sweep_profile_helix: turns must be at most 64",
2983        ));
2984    }
2985
2986    // --- 2. Profile extent about its centroid, sampled exactly like the path
2987    //        sweep derives its placement origin (boundary-sample mean), so the
2988    //        extent is measured about the point that actually rides the path.
2989    let mut samples = Vec::new();
2990    for curve in profile {
2991        let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
2992        for sample in 0..16 {
2993            samples.push(curve.evaluate(start + (end - start) * sample as f64 / 16.0).or_refuse(KernelStage::Collect, "evaluate")?);
2994        }
2995    }
2996    if !samples.is_empty() {
2997        let mut centroid = Vec3::default();
2998        for point in &samples {
2999            centroid = centroid.add(*point);
3000        }
3001        let origin = centroid.scale(1.0 / samples.len() as f64);
3002        let extent = samples
3003            .iter()
3004            .map(|point| point.sub(origin).length())
3005            .fold(0.0, f64::max);
3006        let c = pitch / TAU; // axial rise per radian
3007                             // Fold-over: profile reaches past the helix's center of curvature.
3008        let curvature_radius = (helix_radius * helix_radius + c * c) / helix_radius;
3009        if extent >= curvature_radius {
3010            return Err(KernelRefusal::unsupported(
3011                KernelStage::Classify,
3012                "helix_fold",
3013                format!(
3014                "sweep_profile_helix: profile extent {extent:.6} reaches the helix \
3015                 curvature radius {curvature_radius:.6}; the tube would fold through \
3016                 itself — increase the helix radius or pitch, or shrink the profile"
3017                ),
3018            ));
3019        }
3020        // Coil collision: only possible once the sweep spans a full revolution.
3021        if turns >= 1.0 {
3022            let circumference = TAU * helix_radius;
3023            let turn_length = (circumference * circumference + pitch * pitch).sqrt();
3024            let coil_gap = pitch * circumference / turn_length;
3025            if coil_gap <= 2.0 * extent {
3026                return Err(KernelRefusal::unsupported(
3027                    KernelStage::Classify,
3028                    "coil_collision",
3029                    format!(
3030                    "sweep_profile_helix: consecutive turns would self-intersect — \
3031                     coil gap {coil_gap:.6} does not clear the profile diameter {:.6}; \
3032                     increase the pitch or shrink the profile",
3033                    2.0 * extent
3034                    ),
3035                ));
3036            }
3037        }
3038    }
3039
3040    // --- 3. Fit the helical path (see the density rationale in the fn docs) —
3041    //        the SAME sampler + fit the HX feature publishes as its edge.
3042    let path = fit_helix_curve(
3043        axis_origin,
3044        w,
3045        None,
3046        helix_radius,
3047        helix_radius,
3048        pitch,
3049        turns,
3050        0.0,
3051        false,
3052    )
3053    .map_err(|error| {
3054        error.with_message(|error| format!("sweep_profile_helix: helix path fit failed: {error}"))
3055    })?;
3056
3057    // --- 4. Drive the existing sweep core; its (or the loft's) failures
3058    //        propagate with helix context prepended.
3059    let stations = ((turns * 32.0).ceil() as usize).clamp(32, 1024);
3060    // The helix builder places the profile ON the fitted helix (the coil's
3061    // section is drawn once and carried round), which is `Transplant` by
3062    // construction — the radius comes from the helix argument, not the profile's
3063    // own position.
3064    sweep_profile_along_path_stations(
3065        profile,
3066        &path,
3067        name,
3068        stations,
3069        0.0,
3070        None,
3071        SectionPlacement::Transplant,
3072        SWEEP_DEFAULT_TOLERANCE,
3073    )
3074    .map(|swept| swept.solid)
3075    .map_err(|error| error.with_message(|error| format!("sweep_profile_helix: {error}")))
3076}