Skip to main content

brep_blend/blending/blend/edge/
open.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4// BREP_FILLET_ROLLOVER_BUILD: an open convex edge whose planar strip is consumed whole.
5#[path = "open_consumed.rs"]
6mod consumed;
7pub(crate) use consumed::blend_consumed_open_strip;
8
9/// General OPEN-edge rolling-ball fillet or chamfer: §4.9 march +
10/// §6.9 surgery with transverse edges on the two end faces.
11pub fn blend_open_edge(
12    solid: &BrepSolid,
13    edge_id: u64,
14    radius: f64,
15    chamfer: bool,
16    name: Option<&str>,
17) -> Result<BrepSolid, KernelRefusal> {
18    // One blend operation: the reports of an earlier one, never consumed, are
19    // dropped as it starts (nested calls keep this operation's).
20    let _operation = crate::blend::BlendOperation::enter();
21    if !(radius > 0.0) || !radius.is_finite() {
22        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
23    }
24    blend_open_edge_impl(solid, edge_id, &|_| radius, Some(radius), chamfer, name)
25}
26
27/// `constant`: the radius when the blend came in through a CONSTANT-radius
28/// entry point (`blend_open_edge`), `None` for a variable profile — the only
29/// provenance on which the wall is judged against one rolling ball.
30pub(super) fn blend_open_edge_impl(
31    solid: &BrepSolid,
32    edge_id: u64,
33    radius_at: &dyn Fn(f64) -> f64,
34    constant: Option<f64>,
35    chamfer: bool,
36    name: Option<&str>,
37) -> Result<BrepSolid, KernelRefusal> {
38    let edge = solid
39        .edges
40        .iter()
41        .find(|edge| edge.id == edge_id)
42        .ok_or_else(|| format!("blend: edge {edge_id} not found")).or_refuse(KernelStage::Refine, "ok_or_else")?;
43    if edge.start_vertex_id == edge.end_vertex_id {
44        return Err(KernelRefusal::input(KernelStage::Collect, "open_edge", "blend: blend_open_edge requires an open edge"));
45    }
46    let (first_face, first_loop, first_coedge) = locate_mate(solid, edge_id, None)?;
47    let (second_face, second_loop, second_coedge) =
48        locate_mate(solid, edge_id, Some((first_face.id, first_loop)))?;
49    let mid_radius = radius_at(edge.t0 + (edge.t1 - edge.t0) * 0.5);
50    let (rho1, rho2) = signed_radii(
51        edge,
52        first_face,
53        first_coedge,
54        second_face,
55        second_coedge,
56        mid_radius,
57    )?;
58    let first_mate = BlendMate {
59        face: first_face,
60        coedge: first_coedge,
61        loop_index: first_loop,
62        rho: rho1,
63    };
64    let second_mate = BlendMate {
65        face: second_face,
66        coedge: second_coedge,
67        loop_index: second_loop,
68        rho: rho2,
69    };
70    blend_open_edge_mated(solid, edge, &first_mate, &second_mate, radius_at, constant, chamfer, name)
71}
72
73/// [`blend_open_edge_impl`] from its two mates, located and signed: the march,
74/// the ladder and the surgery.
75#[allow(clippy::too_many_arguments)]
76pub(super) fn blend_open_edge_mated(
77    solid: &BrepSolid,
78    edge: &EdgeRecord,
79    first_mate: &BlendMate,
80    second_mate: &BlendMate,
81    radius_at: &dyn Fn(f64) -> f64,
82    constant: Option<f64>,
83    chamfer: bool,
84    name: Option<&str>,
85) -> Result<BrepSolid, KernelRefusal> {
86    let edge_id = edge.id;
87    let (first_face, second_face) = (first_mate.face, second_mate.face);
88    let (rho1, rho2) = (first_mate.rho, second_mate.rho);
89    // End topology: boundary edges of both mates at each end vertex, the
90    // single face across the corner, and the support crossings.  When a
91    // prior fillet has already consumed one of the end corners, the support
92    // crossing can land at the very rim of the marched rows (the prior
93    // blend's transverse arc meets our contact line right at its base).
94    // March with a growing overshoot until every crossing lands strictly
95    // inside the fitted-row domain so the surgery can trim cleanly.
96    let debug = std::env::var("BREP_DEBUG_BLEND_MARCH").is_ok();
97    if debug {
98        let sp = edge.curve.evaluate(edge.t0);
99        let ep = edge.curve.evaluate(edge.t1);
100        eprintln!(
101            "OPEN edge {} v{}->v{} first_face {} second_face {} p0={:?} p1={:?}",
102            edge.id,
103            edge.start_vertex_id,
104            edge.end_vertex_id,
105            first_face.id,
106            second_face.id,
107            sp,
108            ep
109        );
110    }
111    // The rung's MEASUREMENT (before anything is built on it), over what it
112    // ships: each rail against its carrier's extension over its own crossing
113    // window (`rails_on_shipped_windows`, at the network lane's rail bar, half
114    // `intersection_fit`), and a constant-radius FILLET's wall over those
115    // windows' envelope against the rolling ball's own sweep (the declared
116    // reader the chains use, at `intersection_fit`).
117    let rail_bar = 0.5 * crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
118    let wall_bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
119    let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
120    // Constant-radius PROVENANCE (the entry point), never sampled constancy:
121    // a variable profile can agree at any finite set of samples.
122    let wall_radius = constant.filter(|radius| radius.is_finite() && *radius > 0.0);
123    let wall_check = !chamfer && wall_radius.is_some() && crate::blend::station_refinement_on();
124    let compute = |overshoot_fraction: f64, station_count: usize| -> Result<(FittedRows, Vec<EndSurgery>, bool, OpenRungReading), KernelRefusal> {
125        // The open-edge surgery locates its ends by support crossings, not by
126        // the marched vertex stations; the snapped indices only break the fit
127        // where the carriers' extension starts (`fit_open_rows`).
128        let law = crate::blend::setback::active();
129        let (stations, vertex_indices, refinement, dense) = if let Some(law) = law {
130            // An asymmetric chamfer's stations: the setback law's sections at
131            // the march's own parameters, refined by doubling to its bar.
132            let parameters = |count: usize| {
133                open_station_parameters(edge, overshoot_fraction, [edge.t0, edge.t1], count, [false, false])
134            };
135            let (stations, vertex_indices) = crate::blend::setback::march_open(
136                solid, edge, first_mate, second_mate, &law, station_count, &parameters, rail_bar,
137            )?;
138            let refinement = StationRefinement { exit: StationRefineExit::Converged, ..Default::default() };
139            (stations, vertex_indices, refinement, OpenDenseCentres::default())
140        } else { march_open_stations_core(
141            edge,
142            first_mate,
143            second_mate,
144            radius_at,
145            overshoot_fraction,
146            [edge.t0, edge.t1],
147            station_count,
148            [false, false],
149            [false, false],
150            crate::blend::station_refinement_on().then_some(rail_bar),
151            if wall_check { OPEN_WALL_CENTRES } else { 0 },
152            true,
153        )? };
154        let parameters = station_parameters(&stations);
155        let rows = fit_open_rows(
156            &stations,
157            &parameters,
158            chamfer,
159            Some(vertex_indices),
160            extrusion_direction(edge, first_mate, second_mate),
161        )?;
162        // The fitted wall itself must not double back along a row
163        // (`fold::check_rows_loop`); terminal, as the march's fold verdicts.
164        crate::blend::fold::check_rows_loop(
165            &rows, &stations, &parameters, Some(vertex_indices), radius_at(0.5 * (edge.t0 + edge.t1)), vec![first_mate.face.id, second_mate.face.id], crate::solid_scale(solid),
166        )?;
167        let mut ends = Vec::with_capacity(2);
168        let mut in_range = true;
169        for (vertex, at_start) in [(edge.start_vertex_id, true), (edge.end_vertex_id, false)] {
170            let (end, side_in_range) = resolve_free_end(
171                solid,
172                edge_id,
173                first_mate,
174                second_mate,
175                &rows,
176                vertex,
177                at_start,
178            )?;
179            if debug {
180                eprintln!(
181                    "  [os {overshoot_fraction:.2}] end v{vertex} at_start={at_start} end_face={} first_boundary={}(t={:.4}) second_boundary={}(t={:.4}) cr={:.4} cs={:.4} in_range={side_in_range}",
182                    end.end_face_id,
183                    end.first_edge_id,
184                    end.first_edge_parameter,
185                    end.second_edge_id,
186                    end.second_edge_parameter,
187                    end.cr_parameter,
188                    end.cs_parameter,
189                );
190            }
191            in_range &= side_in_range;
192            ends.push(end);
193        }
194        // The measurement covers what SHIPS: each rail over its own crossing
195        // window (the `cr`/`cs` parameters `build_open_surgery` trims it to,
196        // any retained overshoot included), and the wall over the envelope of
197        // both windows -- not merely between the vertex stations.
198        let windows = [
199            shipped_window(&parameters, ends[0].cr_parameter, ends[1].cr_parameter),
200            shipped_window(&parameters, ends[0].cs_parameter, ends[1].cs_parameter),
201        ];
202        let (rails, rail_samples) =
203            rails_on_shipped_windows(&rows, &parameters, &stations, [&first_mate.face.surface, &second_mate.face.surface], windows);
204        let walls = match (wall_check, windows) {
205            (false, _) => Vec::new(),
206            (true, [Some(first), Some(second)]) => open_wall_readings_why(
207                &rows,
208                &parameters,
209                &stations,
210                [first[0].min(second[0]), first[1].max(second[1])],
211                &dense,
212                wall_radius.unwrap_or(f64::NAN),
213            ),
214            // No shipped window to read: no wall coverage, never acceptance.
215            (true, _) => vec![Err("no shipped window to read".to_string())],
216        };
217        let first_unread = walls.iter().find_map(|wall| wall.as_ref().err().cloned());
218        let walls: Vec<Option<f64>> = if wall_check && windows.iter().any(|window| window.is_none()) {
219            Vec::new()
220        } else {
221            walls.into_iter().map(|wall| wall.ok()).collect()
222        };
223        let reading = OpenRungReading {
224            station_count,
225            stations: stations.len(),
226            rails,
227            rail_samples,
228            walls,
229            first_unread,
230            refine_exit: refinement.exit,
231            inserted: refinement.inserted,
232        };
233        Ok((rows, ends, in_range, reading))
234    };
235
236    // Radius-aware seeded first attempt (occt-filleting-system-study §6(b)
237    // lesson 7): OCCT floors corner extensions at 1.5·max_radius
238    // (`ExtentTwoCorner`) instead of probing blindly.  Convert that floor to
239    // an overshoot fraction of THIS edge: the contact rails sit r·tan(α/2)
240    // from the edge (α = sign-adjusted angle between the mates' raw normals
241    // at mid-edge — the march's own `cos_alpha`), so seed with 1.5× the
242    // widest end radius's rail offset over the edge arc length, clamped to
243    // the ladder's proven [0.08, 0.45] envelope.  Deterministic; `None` when
244    // it degenerates or merely reproduces the ladder's first rung.
245    let seeded_fraction: Option<f64> = (|| {
246        let span = edge.t1 - edge.t0;
247        let mut length = 0.0f64;
248        let mut previous = edge.curve.evaluate(edge.t0).ok()?;
249        for index in 1..=16 {
250            let t = edge.t0 + span * index as f64 / 16.0;
251            let point = edge.curve.evaluate(t).ok()?;
252            length += point.sub(previous).length();
253            previous = point;
254        }
255        if !(length > 0.0) || !length.is_finite() {
256            return None;
257        }
258        let mid_t = edge.t0 + span * 0.5;
259        let uv1 = edge_uv_on_face(first_mate.coedge, edge, mid_t).ok()?;
260        let uv2 = edge_uv_on_face(second_mate.coedge, edge, mid_t).ok()?;
261        let n1 = raw_normal(&first_mate.face.surface, uv1[0], uv1[1]).ok()?;
262        let n2 = raw_normal(&second_mate.face.surface, uv2[0], uv2[1]).ok()?;
263        let cos_alpha =
264            (rho1.signum() * rho2.signum() * n1.dot(n2)).clamp(-1.0, 1.0);
265        // tan(α/2) = √((1−cosα)/(1+cosα)); the tangent-offset factor from
266        // the edge to each rail (box: α = π/2 → offset = r).
267        let tan_half = ((1.0 - cos_alpha).max(0.0) / (1.0 + cos_alpha).max(1e-9)).sqrt();
268        let end_radius = radius_at(edge.t0).abs().max(radius_at(edge.t1).abs());
269        let fraction = (1.5 * end_radius * tan_half / length).clamp(0.08, 0.45);
270        if !fraction.is_finite() || (fraction - 0.08).abs() < 1e-12 {
271            return None;
272        }
273        Some(fraction)
274    })();
275
276    // Retry with a growing overshoot; keep the first attempt whose crossings
277    // are all in range, else fall back to the widest march tried.  The seeded
278    // attempt is accepted ONLY when its crossings land in range — otherwise
279    // the blind ladder below runs exactly as before (including its
280    // fallback-to-first-Ok semantics), so the seed can improve the first
281    // landing but never change the fallback behaviour.
282    let choose = |station_count: usize| -> Result<(FittedRows, Vec<EndSurgery>, OpenRungReading), KernelRefusal> {
283    let mut chosen: Option<(FittedRows, Vec<EndSurgery>, OpenRungReading)> = None;
284    let mut last_error: Option<KernelRefusal> = None;
285    // A wall that FOLDS is the shape's answer, not this rung's: every wider
286    // overshoot marches the same centre curve through the same bend, so the
287    // ladder is left at the first fold rather than re-proving it four times.
288    if let Some(fraction) = seeded_fraction {
289        match compute(fraction, station_count) {
290            Ok((rows, ends, true, reading)) => chosen = Some((rows, ends, reading)),
291            Ok(_) => {}
292            Err(error) if crate::blend::is_wall_fold(&error) => return Err(error),
293            Err(error) => last_error = Some(error),
294        }
295    }
296    if chosen.is_none() {
297        for &overshoot_fraction in &[0.08f64, 0.16, 0.28, 0.45] {
298            match compute(overshoot_fraction, station_count) {
299                Ok((rows, ends, in_range, reading)) => {
300                    let fallback = chosen.is_none();
301                    if in_range {
302                        chosen = Some((rows, ends, reading));
303                        break;
304                    } else if fallback {
305                        chosen = Some((rows, ends, reading));
306                    }
307                }
308                Err(error) if crate::blend::is_wall_fold(&error) => return Err(error),
309                Err(error) => last_error = Some(error),
310            }
311        }
312    }
313    chosen.ok_or_else(|| {
314        last_error.unwrap_or_else(|| {
315            KernelRefusal::internal(
316                KernelStage::Refine,
317                "open_march",
318                "blend: open march failed at every overshoot",
319            )
320        })
321    })
322    };
323    // The LADDER: the open march's existing budget — STATIONS doubling to
324    // MAX_OPEN_STATIONS, each rung with its local refinement (REFINE_ROUNDS,
325    // REFINE_STATION_FACTOR) against the rail bar — climbed until a rung is
326    // ACCEPTED (rails and wall inside their bars), then, for a plain fillet,
327    // further toward `model` on the wall. A rung the request climbs to that
328    // fails acceptance is not taken: the accepted rung ships and says so,
329    // typed. A ladder that never accepts ships its top rung with a named note,
330    // as the network lane's open march does (a body that built before is not
331    // turned into a refusal here) -- but it is NOT an accepted rung: it ships
332    // with a typed `blend.wall_acceptance` report of its measured deficit.
333    // Acceptance is stated positively: every reading present, finite and
334    // inside its bar (a NaN or an empty coverage never passes).
335    let accepts = |reading: &OpenRungReading| {
336        reading.rails_read()
337            && reading.rails <= rail_bar
338            && (!wall_check || reading.worst_wall().is_some_and(|wall| wall <= wall_bar))
339    };
340    let meets_model = |reading: &OpenRungReading| reading.worst_wall().is_some_and(|wall| wall <= model);
341    let mut station_count = STATIONS;
342    let mut accepted: Option<(FittedRows, Vec<EndSurgery>, OpenRungReading)> = None;
343    // The top rung of a ladder that NEVER accepted: shipped as built, kept
344    // apart from `accepted` so it is never reported as an accepted parent.
345    let mut unaccepted: Option<(FittedRows, Vec<EndSurgery>, OpenRungReading)> = None;
346    let mut request_rungs = 0usize;
347    let mut unmet: Option<crate::BudgetReason> = None;
348    loop {
349        // A rung climbed to after acceptance is a request rung ATTEMPTED,
350        // whatever it returns.
351        if accepted.is_some() {
352            request_rungs += 1;
353        }
354        let chosen = choose(station_count);
355        let (rows, ends, reading) = match chosen {
356            Ok(chosen) => chosen,
357            // A request rung that cannot be built: the accepted rung stands.
358            Err(_) if accepted.is_some() => {
359                unmet = Some(crate::BudgetReason::Incoherent);
360                break;
361            }
362            Err(error) => return Err(error),
363        };
364        #[cfg(not(test))]
365        let reject_request = false;
366        crate::blend::carve::carve_trace(format_args!(
367            "blend open edge {}: {} stations a rung ({} in all), rails {:.3e} (bar {rail_bar:.3e}), wall {:.3e} (bar {wall_bar:.3e}){}",
368            edge.id, reading.station_count, reading.stations, reading.rails,
369            reading.worst_wall().unwrap_or(f64::INFINITY),
370            if accepted.is_some() { ", a request rung" } else { "" }
371        ));
372        let accepted_now = accepts(&reading) && !reject_request;
373        if accepted.is_none() {
374            if accepted_now {
375                let met = !wall_check || meets_model(&reading);
376                accepted = Some((rows, ends, reading));
377                if met {
378                    break;
379                }
380            } else if station_count < MAX_OPEN_STATIONS {
381                station_count *= 2;
382                continue;
383            } else {
384                crate::blend::record_blend_note(format!(
385                    "blend: open edge {} at {} stations a rung ({} in all) — the top of the open march's \
386                     ladder — still leaves its rails {:.3e} from their carriers (bar {rail_bar:.3e}) or its \
387                     wall off the rolling ball (bar {wall_bar:.3e}); the wall ships as built, unaccepted",
388                    edge.id, reading.station_count, reading.stations, reading.rails
389                ));
390                unaccepted = Some((rows, ends, reading));
391                break;
392            }
393        } else {
394            if !accepted_now {
395                unmet = Some(crate::BudgetReason::Rejected);
396                break;
397            }
398            let met = meets_model(&reading);
399            accepted = Some((rows, ends, reading));
400            if met {
401                unmet = None;
402                break;
403            }
404        }
405        // Accepted, short of `model`: one more rung if the budget allows.
406        if station_count < MAX_OPEN_STATIONS {
407            station_count *= 2;
408        } else {
409            unmet = Some(crate::BudgetReason::StationCeiling);
410            break;
411        }
412    }
413    let (shipped_accepted, (rows, ends, reading)) = match (accepted, unaccepted) {
414        (Some(rung), _) => (true, rung),
415        (None, Some(rung)) => (false, rung),
416        (None, None) => {
417            return Err(KernelRefusal::internal(KernelStage::Refine, "open_ladder", "blend: the open ladder ended without a rung"));
418        }
419    };
420    // What the shipped wall owes, typed: an UNACCEPTED rung its measured
421    // acceptance deficit (or that a reading could not be taken); an accepted
422    // fillet short of `model` its construction request.
423    let report: Option<(crate::BudgetReason, f64, f64, String)> = if !shipped_accepted {
424        Some(acceptance_deficit(&reading, rail_bar, wall_bar, wall_check, reading.rails_read(), "no rung of the open ladder was accepted"))
425    } else if wall_check && !meets_model(&reading) {
426        let reason = unmet.unwrap_or(crate::BudgetReason::StationCeiling);
427        // An accepted rung's every wall interval was read (acceptance needs it).
428        let declared = reading.worst_wall().unwrap_or(f64::INFINITY);
429        Some((reason, model, declared, String::new()))
430    } else {
431        None
432    };
433
434    let [start_end, finish_end] = match <[EndSurgery; 2]>::try_from(ends) {
435        Ok(pair) => pair,
436        Err(_) => return Err(KernelRefusal::internal(KernelStage::Sew, "open_surgery_ends", "blend: open surgery needs exactly two ends")),
437    };
438    // A crossing that only resolved on a looser rung of the tolerance ladder
439    // builds something master refused outright, so it must earn its answer
440    // (see [`SpokeCrossings`]).
441    let mut crossings = SpokeCrossings::default();
442    crossings.note(start_end.escalated || finish_end.escalated);
443    let mut result = solid.clone();
444    let mut take_id = fresh_id_source(solid);
445    let sewn = build_open_surgery(
446        solid,
447        &mut result,
448        &mut take_id,
449        edge,
450        first_mate,
451        second_mate,
452        rows,
453        [EndPlan::Free(start_end), EndPlan::Free(finish_end)],
454        name,
455    )?;
456    prune_orphan_vertices(&mut result);
457    // Extended end boundaries can leave a finite planar chart. Rebuild those
458    // charts before validating the surgery, rather than rejecting a correct
459    // edge because its projected pcurve was clamped to the old rectangle.
460    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
461    check_snap_closure(solid, &result, sewn.snap)?;
462    let built = crossings.gate(result)?;
463    // The wall AS SEWN: the surgery may transpose the face (an exact
464    // extrusion), and a report is matched to its face by exact surface.
465    let sewn_surface = built
466        .shells
467        .iter()
468        .flat_map(|shell| &shell.faces)
469        .find(|face| face.id == sewn.blend_face_id)
470        .map(|face| face.surface.clone())
471        .ok_or(KernelRefusal::internal(KernelStage::Sew, "open_blend_face", "blend: the sewn open blend face is not in the built body"))?;
472    // A wall that SHIPS unaccepted, or short of its construction request,
473    // says so, typed, on the built body's wall (exact name and sewn surface).
474    if let Some((reason, bar, measured, deficit)) = report {
475        // The budget is the open march's GLOBAL station ladder (STATIONS
476        // doubling to MAX_OPEN_STATIONS), not local rounds: for a request,
477        // the rungs ATTEMPTED past the accepted one (a refused one included);
478        // for an unaccepted rung, the rungs climbed past the first. Each rung
479        // also ran its own local rail refinement, named in the detail.
480        let rungs_used = if shipped_accepted { request_rungs } else { (reading.station_count / STATIONS).trailing_zeros() as usize };
481        let mut detail = format!(
482            "the shipped rung's local rail refinement ended {:?} with {} stations inserted",
483            reading.refine_exit, reading.inserted
484        );
485        if !deficit.is_empty() {
486            detail = format!("{deficit}; {detail}");
487        }
488        crate::blend::record_wall_model_report(crate::blend::WallModelReport {
489            name: name.map(str::to_string),
490            surface: sewn_surface,
491            request: bar,
492            residual: measured,
493            detail: Some(detail),
494            budget: crate::ApproximationBudget {
495                reason,
496                rounds_used: rungs_used,
497                rounds_limit: OPEN_REQUEST_RUNGS,
498                stations: reading.stations,
499                station_limit: REFINE_STATION_FACTOR * (MAX_OPEN_STATIONS + 1),
500                mechanism: crate::BudgetMechanism::StationRungs,
501                measured_component: crate::MeasuredComponent::Wall,
502                unread: 0,
503            },
504        });
505    }
506    Ok(built)
507}
508
509/// An UNACCEPTED shipped rung's deficit, typed: `Unread` when any reading
510/// acceptance needs could not be taken (a non-finite rail, an empty shipped
511/// window, an unread or missing wall interval), else `Unaccepted`; the
512/// measured value and its bar are the readable component worst against its
513/// bar (rails against `rail_bar`, the wall against `wall_bar`; 0 against
514/// `rail_bar` when nothing could be read), always finite. The text names both
515/// readings against their bars, after `what` (what failed acceptance: the
516/// open ladder's every rung, or a network stripe's shipped windows).
517/// `rails_read` is the caller's verdict on whether the rails were READ (the
518/// open lane: [`OpenRungReading::rails_read`]; a network stripe also counts a
519/// validated collapsed rail as read with no samples).
520pub fn acceptance_deficit(
521    reading: &OpenRungReading,
522    rail_bar: f64,
523    wall_bar: f64,
524    wall_check: bool,
525    rails_read: bool,
526    what: &str,
527) -> (crate::BudgetReason, f64, f64, String) {
528    let rails = (rails_read && reading.rails.is_finite() && reading.rails >= 0.0).then_some(reading.rails);
529    let wall = if wall_check { reading.worst_wall() } else { None };
530    let unread = rails.is_none() || (wall_check && wall.is_none());
531    let mut worst = (0.0_f64, rail_bar);
532    for (value, bar) in [(rails, rail_bar), (wall, wall_bar)] {
533        if let Some(value) = value {
534            if value / bar > worst.0 / worst.1 {
535                worst = (value, bar);
536            }
537        }
538    }
539    let rail_text = match rails {
540        Some(value) => format!("rails {value:.3e} from their carriers (bar {rail_bar:.3e})"),
541        None => format!(
542            "rails UNREAD ({:?} over {} + {} samples) against bar {rail_bar:.3e}",
543            reading.rails, reading.rail_samples[0], reading.rail_samples[1]
544        ),
545    };
546    let wall_text = match (wall_check, wall) {
547        (false, _) => "the wall not judged (no constant-radius fillet provenance)".to_string(),
548        (true, Some(value)) => format!("wall {value:.3e} off the rolling ball (bar {wall_bar:.3e})"),
549        (true, None) => format!(
550            "wall UNREAD on {} of {} intervals against bar {wall_bar:.3e}{}",
551            reading.walls.iter().filter(|wall| !matches!(wall, Some(value) if value.is_finite())).count(),
552            reading.walls.len(),
553            reading.first_unread.as_deref().map(|why| format!(" (first: {why})")).unwrap_or_default()
554        ),
555    };
556    let reason = if unread { crate::BudgetReason::Unread } else { crate::BudgetReason::Unaccepted };
557    (reason, worst.1, worst.0, format!("{what}: {rail_text}, {wall_text}"))
558}
559
560/// Section probes per open wall interval (k/8 of the section), and centres
561/// per interval (probes at the even ones), as the chains read their walls.
562const OPEN_WALL_SECTIONS: usize = 8;
563pub const OPEN_WALL_CENTRES: usize = 32;
564/// The rungs the construction request may climb past the first accepted one:
565/// the open march's own ladder, STATIONS doubling to MAX_OPEN_STATIONS.
566pub const OPEN_REQUEST_RUNGS: usize = (MAX_OPEN_STATIONS / STATIONS).trailing_zeros() as usize;
567
568/// One open rung's measurement over what it SHIPS: its rung, its station
569/// count (refinement included), the rails' worst distance from their
570/// carriers over each rail's own crossing window and the samples read on
571/// each (0: no window), each wall interval's declared reading (`None`:
572/// unreadable) over the windows' envelope, and how the rung's own LOCAL rail
573/// refinement ended (its exit and the stations it inserted).
574#[derive(Clone, Debug)]
575pub struct OpenRungReading {
576    pub(in crate::blend) station_count: usize,
577    pub(in crate::blend) stations: usize,
578    pub(in crate::blend) rails: f64,
579    pub(in crate::blend) rail_samples: [usize; 2],
580    pub(in crate::blend) walls: Vec<Option<f64>>,
581    /// The first unread wall interval and why (diagnostic; `None` when every
582    /// interval read or the wall was not judged).
583    pub(in crate::blend) first_unread: Option<String>,
584    pub(in crate::blend) refine_exit: crate::blend::stations::StationRefineExit,
585    pub(in crate::blend) inserted: usize,
586}
587
588impl OpenRungReading {
589    /// Every rail READ: a finite, nonnegative worst distance from samples on
590    /// both rails' shipped windows. A NaN, an infinity (an unreadable foot)
591    /// or an empty window is never a reading.
592    pub(in crate::blend) fn rails_read(&self) -> bool {
593        self.rails.is_finite() && self.rails >= 0.0 && self.rail_samples.iter().all(|&samples| samples > 0)
594    }
595
596    /// Every wall interval READ (and at least one): `None` when any is not.
597    pub(in crate::blend) fn worst_wall(&self) -> Option<f64> {
598        if self.walls.is_empty() {
599            return None;
600        }
601        self.walls.iter().try_fold(0.0_f64, |worst, wall| match wall {
602            Some(declared) if declared.is_finite() && *declared >= 0.0 => Some(worst.max(*declared)),
603            _ => None,
604        })
605    }
606}
607
608/// The shipped window `[low, high]` of one rail between its two crossing
609/// parameters, within the rows' parameters (the surgery refuses a crossing
610/// outside them; the reading only never indexes past them). `None` when the
611/// window is empty or not finite: nothing ships there that could be read.
612pub fn shipped_window(parameters: &[f64], a: f64, b: f64) -> Option<[f64; 2]> {
613    let (&first, &last) = (parameters.first()?, parameters.last()?);
614    let (low, high) = (a.min(b).max(first), a.max(b).min(last));
615    (low.is_finite() && high.is_finite() && low < high).then_some([low, high])
616}
617
618/// The station interval holding `u` and `u`'s fraction of it.
619fn interval_at(parameters: &[f64], u: f64) -> Option<(usize, f64)> {
620    let last = parameters.len().checked_sub(2)?;
621    let interval = parameters.partition_point(|&parameter| parameter <= u).saturating_sub(1).min(last);
622    let (from, to) = (parameters[interval], parameters[interval + 1]);
623    (to > from).then(|| (interval, ((u - from) / (to - from)).clamp(0.0, 1.0)))
624}
625
626/// A point of `surface` and its unit normal when the surface is AFFINE in
627/// (u, v), its extension included: a plane (`analytic`) of degree 1 × 1 whose
628/// 2 × 2 net is a parallelogram with equal weights, to `1e-12·(1 + scale)`.
629/// Every point of such a surface, and of its linear extension, lies on the one
630/// plane through the corner with that normal.
631fn affine_plane(surface: &NurbsSurface) -> Option<(Vec3, Vec3)> {
632    let (origin, _, _) = affine_plane_frame(surface)?;
633    // The normal off the net's own corner differences.
634    let net = &surface.control_points;
635    let [p00, p01, p10] = [net[0][0].point().ok()?, net[0][1].point().ok()?, net[1][0].point().ok()?];
636    Some((origin, p10.sub(p00).cross(p01.sub(p00)).normalized().ok()?))
637}
638
639/// [`affine_plane`]'s surface as `S(u, v) = origin + (u − u₀)·s_u + (v − v₀)·s_v`:
640/// the net's corner and the two constant partial derivatives.
641pub(in crate::blend) fn affine_plane_frame(surface: &NurbsSurface) -> Option<(Vec3, Vec3, Vec3)> {
642    if !matches!(surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) || surface.degree_u != 1 || surface.degree_v != 1 {
643        return None;
644    }
645    let net = &surface.control_points;
646    if net.len() != 2 || net.iter().any(|row| row.len() != 2) {
647        return None;
648    }
649    let weight = net[0][0].w;
650    if !(weight > 0.0) || net.iter().flatten().any(|point| point.w != weight) {
651        return None;
652    }
653    let [p00, p01, p10, p11] = [net[0][0].point().ok()?, net[0][1].point().ok()?, net[1][0].point().ok()?, net[1][1].point().ok()?];
654    let scale = [p00, p01, p10, p11].iter().fold(0.0f64, |worst, point| worst.max(point.length()));
655    if p11.sub(p10).sub(p01.sub(p00)).length() > 1e-12 * (1.0 + scale) {
656        return None;
657    }
658    let [u0, u1] = surface.domain_u().ok()?;
659    let [v0, v1] = surface.domain_v().ok()?;
660    if !(u1 > u0 && v1 > v0) {
661        return None;
662    }
663    Some((p00, p10.sub(p00).scale(1.0 / (u1 - u0)), p01.sub(p00).scale(1.0 / (v1 - v0))))
664}
665
666/// Whether `curve` is AFFINE in its parameter: degree 1, two control points of
667/// equal weight (a `make_line`).
668fn affine_curve(curve: &NurbsCurve) -> bool {
669    curve.degree == 1
670        && curve.control_points.len() == 2
671        && curve.control_points[0].w > 0.0
672        && curve.control_points[0].w == curve.control_points[1].w
673}
674
675/// The worst distance of an affine rail from an affine carrier over `window`,
676/// read at the window's two ends: the signed distance is affine in the rail
677/// parameter, so its magnitude is convex and its maximum is at an end. `None`
678/// when either is not affine (the sampled reader's), or an end will not
679/// evaluate.
680pub fn affine_rail_standoff(rail: &NurbsCurve, carrier: &NurbsSurface, window: [f64; 2]) -> Option<f64> {
681    if !affine_curve(rail) {
682        return None;
683    }
684    let (origin, normal) = affine_plane(carrier)?;
685    let mut worst = 0.0f64;
686    for u in window {
687        let point = rail.evaluate(u).ok()?;
688        let off = point.sub(origin).dot(normal).abs();
689        if !off.is_finite() {
690            return None;
691        }
692        worst = worst.max(off);
693    }
694    Some(worst)
695}
696
697/// Lane N row 4 (2026-10-28): the exact revolution rows' reads in closed
698/// form. `BREP_EXACT_REVOLUTION_READS=1`/`on` turns them on, `=0`/`off`
699/// off; ON by default since lane N's promotion (2026-10-28).
700const EXACT_REVOLUTION_READS_DEFAULT: bool = true;
701
702pub(in crate::blend) fn exact_revolution_reads_on() -> bool {
703    switch!(live "BREP_EXACT_REVOLUTION_READS", EXACT_REVOLUTION_READS_DEFAULT)
704}
705
706
707/// A bound on `|S(pcurve(s)) − rail(s)|` over the whole parameter range when
708/// the shipped pair is an exact revolution row's (`exact_revolution_rows`):
709///
710/// * on the REVOLUTION carrier the pcurve is a uv line along one coordinate
711///   and the rail is the carrier's parallel circle at the held coordinate,
712///   continued to the line's range along its own conic pieces
713///   (`extend_conic_ends`) and re-parameterised to `[0, 1]`; that curve is
714///   rebuilt here from the pcurve's two ends and compared with the rail net
715///   for net — identical bases, so the homogeneous control differences
716///   bound the curves everywhere (`net_bound`);
717/// * on an AFFINE plane the pcurve carries the rail's own knots and the
718///   chart images of the rail's control points; the plane's image of the
719///   pcurve net is compared with the rail net the same way.
720///
721/// `None` when the pair is neither (the sampled read runs). The rail's
722/// standoff from the carrier and the pcurve's miss are each at most the
723/// bound (a point's distance to a surface is at most its distance to any
724/// point of it; the miss adds the standoff once more), so a bound within a
725/// third of the pcurve floor stands the trim by the march trim's own rule.
726pub(in crate::blend) fn exact_revolution_read_bound(rail: &NurbsCurve, carrier: &NurbsSurface, pcurve: &NurbsCurve) -> Option<f64> {
727    if let Some((origin, s_u, s_v)) = affine_plane_frame(carrier) {
728        // The plane's image of the pcurve net, weight for weight.
729        if pcurve.degree != rail.degree || pcurve.knots != rail.knots || pcurve.control_points.len() != rail.control_points.len() {
730            return None;
731        }
732        let ([u0, _], [v0, _]) = (carrier.domain_u().ok()?, carrier.domain_v().ok()?);
733        let image: Vec<Vec4> = pcurve
734            .control_points
735            .iter()
736            .map(|control| {
737                let (u, v) = (control.x / control.w, control.y / control.w);
738                let point = origin.add(s_u.scale(u - u0)).add(s_v.scale(v - v0));
739                Vec4 { x: point.x * control.w, y: point.y * control.w, z: point.z * control.w, w: control.w }
740            })
741            .collect();
742        return crate::blend::stations::net_bound(&rail.control_points, &image);
743    }
744    if !matches!(carrier.analytic(), Some(crate::AnalyticSurface::RuledRevolution { .. } | crate::AnalyticSurface::Revolution { .. } | crate::AnalyticSurface::Torus { .. } | crate::AnalyticSurface::Sphere { .. })) {
745        return None;
746    }
747    if !affine_curve(pcurve) {
748        return None;
749    }
750    let [q0, q1] = pcurve.domain().ok()?;
751    let (a, b) = (pcurve.evaluate(q0).ok()?, pcurve.evaluate(q1).ok()?);
752    let ([u0, u1], [v0, v1]) = (carrier.domain_u().ok()?, carrier.domain_v().ok()?);
753    let (circle, from, to) = if a.y.to_bits() == b.y.to_bits() && a.x != b.x && a.y >= v0 && a.y <= v1 {
754        (carrier.iso_curve_v(a.y).ok()?, a.x, b.x)
755    } else if a.x.to_bits() == b.x.to_bits() && a.y != b.y && a.x >= u0 && a.x <= u1 {
756        (carrier.iso_curve_u(a.x).ok()?, a.y, b.y)
757    } else {
758        return None;
759    };
760    let [c0, c1] = circle.domain().ok()?;
761    let reversed = to < from;
762    let circle = if reversed { circle.reversed().ok()? } else { circle };
763    let on_curve = |along: f64| if reversed { c0 + c1 - along } else { along };
764    let (lo, hi) = (on_curve(from), on_curve(to));
765    if !(hi > lo) {
766        return None;
767    }
768    let segment = super::support::extend_conic_ends(&circle, lo, hi).ok()?;
769    let [r0, r1] = segment.domain().ok()?;
770    let degree = segment.degree;
771    let mut knots = segment.knots.clone();
772    for knot in knots.iter_mut() {
773        *knot = ((*knot - r0) / (r1 - r0)).clamp(0.0, 1.0);
774    }
775    for knot in knots.iter_mut().take(degree + 1) {
776        *knot = 0.0;
777    }
778    let count = knots.len();
779    for knot in knots.iter_mut().skip(count - degree - 1) {
780        *knot = 1.0;
781    }
782    if rail.degree != degree || rail.knots != knots || rail.control_points.len() != segment.control_points.len() {
783        return None;
784    }
785    crate::blend::stations::net_bound(&rail.control_points, &segment.control_points)
786}
787
788/// Each shipped rail's worst distance from its carrier over ITS OWN window
789/// ([`shipped_window`]): both window ends exactly and the quarter points of
790/// every station span inside it, each against the carrier's EXTENSION
791/// (`extended_foot_distance`, seeded by the stations' own contact uv) --
792/// a finite planar chart clamps its projection, so retained overshoot past a
793/// vertex would read a miss that is not there. `(worst, samples per rail)`;
794/// any unreadable sample (a failed evaluation, an infinite foot) makes the
795/// worst NaN, which [`OpenRungReading::rails_read`] never admits.
796pub fn rails_on_shipped_windows(
797    rows: &FittedRows,
798    parameters: &[f64],
799    stations: &[Station],
800    carriers: [&NurbsSurface; 2],
801    windows: [Option<[f64; 2]>; 2],
802) -> (f64, [usize; 2]) {
803    read_rail_windows([&rows.cr, &rows.cs], parameters, stations, carriers, windows,
804        rows.exact_extrusion, certified_rail_bounds(rows, carriers), None)
805}
806
807/// An exact revolution row's rails, bounded in closed form
808/// (`exact_revolution_read_bound`) when the reads lane is on: the standoff
809/// over any window is at most the bound.
810fn certified_rail_bounds(rows: &FittedRows, carriers: [&NurbsSurface; 2]) -> [Option<f64>; 2] {
811    if rows.revolution_axis.is_none() || !exact_revolution_reads_on() {
812        return [None, None];
813    }
814    [
815        exact_revolution_read_bound(&rows.cr, carriers[0], &rows.cr_pcurve),
816        exact_revolution_read_bound(&rows.cs, carriers[1], &rows.cs_pcurve),
817    ]
818}
819
820fn read_rail_windows(
821    rails: [&NurbsCurve; 2], parameters: &[f64], stations: &[Station],
822    carriers: [&NurbsSurface; 2], windows: [Option<[f64; 2]>; 2], affine: bool,
823    certified: [Option<f64>; 2],
824    mut memo: Option<&mut RailFeet>,
825) -> (f64, [usize; 2]) {
826    let mut worst = 0.0_f64;
827    let mut samples = [0usize; 2];
828    for (side, (rail, carrier)) in [(rails[0], carriers[0]), (rails[1], carriers[1])].into_iter().enumerate() {
829        let Some([low, high]) = windows[side] else { continue };
830        // An exact extrusion's straight rail on a plane: the ends carry the
831        // worst (`affine_rail_standoff`), the samples between them cannot.
832        if let Some(off) = affine.then(|| affine_rail_standoff(rail, carrier, [low, high])).flatten() {
833            crate::blend::record_count("count.read.affine_rails", 1);
834            samples[side] += 2;
835            if !worst.is_nan() && off > worst {
836                worst = off;
837            }
838            continue;
839        }
840        // An exact revolution row's rail: its net bound against the carrier's
841        // own circle (or the plane's image of its pcurve) is its standoff's
842        // bound over every window.
843        if let Some(bound) = certified[side] {
844            crate::blend::record_count("count.read.revolution_rails", 1);
845            samples[side] += 1;
846            if !worst.is_nan() && bound > worst {
847                worst = bound;
848            }
849            continue;
850        }
851        let mut at = vec![low, high];
852        for pair in parameters.windows(2) {
853            for fraction in [0.25, 0.5, 0.75] {
854                let u = pair[0] + (pair[1] - pair[0]) * fraction;
855                if u > low && u < high {
856                    at.push(u);
857                }
858            }
859        }
860        for u in at {
861            let cached = memo.as_ref().and_then(|memo| memo.values[side].get(&u.to_bits()).copied());
862            let off = if let Some(off) = cached {
863                if let Some(memo) = memo.as_mut() { memo.hits += 1; }
864                crate::blend::record_count("count.read.rail_foot_reused", 1);
865                off
866            } else {
867            if let Some(memo) = memo.as_mut() {
868                memo.reads += 1;
869                crate::blend::record_count("count.read.rail_foot_fresh", 1);
870            }
871            let off = interval_at(parameters, u)
872                .and_then(|(interval, fraction)| {
873                    let (left, right) = (&stations[interval], &stations[interval + 1]);
874                    let (a, b) = if side == 0 { (left.uv1, right.uv1) } else { (left.uv2, right.uv2) };
875                    let seed = [a[0] + fraction * (b[0] - a[0]), a[1] + fraction * (b[1] - a[1])];
876                    let point = rail.evaluate(u).ok()?;
877                    crate::blend::stations::extended_foot_distance(carrier, point, seed).ok()
878                })
879                .filter(|off| off.is_finite())
880                .unwrap_or(f64::NAN);
881            if off.is_finite() {
882                if let Some(memo) = memo.as_mut() { memo.values[side].insert(u.to_bits(), off); }
883            }
884            off
885            };
886            samples[side] += 1;
887            if !worst.is_nan() && (off.is_nan() || off > worst) {
888                worst = off;
889            }
890        }
891    }
892    (worst, samples)
893}
894
895/// A construction-local rail reader. It owns an immutable snapshot of every
896/// input to a foot reading; only the requested windows can change. Native
897/// parameter bits identify a sample, so nearby endpoints never share a foot.
898/// The network keeps this reader from its chosen rung through shipped-window
899/// acceptance, then drops it. Failed/nonfinite feet are never reused.
900pub(in crate::blend) struct RailWindowReader {
901    rails: [NurbsCurve; 2],
902    carriers: [NurbsSurface; 2],
903    parameters: Vec<f64>,
904    stations: Vec<Station>,
905    affine: bool,
906    certified: [Option<f64>; 2],
907    feet: RailFeet,
908}
909
910#[derive(Default)]
911struct RailFeet {
912    values: [rustc_hash::FxHashMap<u64, f64>; 2],
913    reads: u64,
914    hits: u64,
915}
916
917impl RailWindowReader {
918    pub(in crate::blend) fn new(rows: &FittedRows, parameters: &[f64], stations: &[Station], carriers: [&NurbsSurface; 2]) -> Self {
919        Self {
920            rails: [rows.cr.clone(), rows.cs.clone()],
921            carriers: [carriers[0].clone(), carriers[1].clone()],
922            parameters: parameters.to_vec(), stations: stations.to_vec(),
923            affine: rows.exact_extrusion, certified: certified_rail_bounds(rows, carriers), feet: RailFeet::default(),
924        }
925    }
926
927    pub(in crate::blend) fn read(&mut self, windows: [Option<[f64; 2]>; 2]) -> (f64, [usize; 2]) {
928        read_rail_windows([&self.rails[0], &self.rails[1]], &self.parameters, &self.stations,
929            [&self.carriers[0], &self.carriers[1]], windows, self.affine, self.certified, Some(&mut self.feet))
930    }
931}
932
933pub(in crate::blend) fn network_rail_reuse_on() -> bool {
934    // The private halving diagnostic compares every requested foot against
935    // its reference algorithm, including repeats. Preserve that coverage.
936    std::env::var("BREP_NETWORK_RAIL_REUSE").map_or(true, |value| value != "0" && value != "off")
937}
938
939/// The JUNCTION stencil across the station between interval `left` and
940/// `left + 1`: `left_nodes` (33 exact centres of `left`) from node 16 to 32,
941/// then `right_nodes` (33 of `left + 1`) from node 1 to 16, the shared
942/// station at node 16. Its native abscissae come from `station_ts` (the
943/// edge parameters the centres were solved at): `None` when the two native
944/// widths are bitwise equal -- uniform nodes, read by the ordinary reader --
945/// else each node's t, interior nodes by the dense solves' own arithmetic
946/// t_i + (t_{i+1} − t_i)·j/32 and the shared station at its STORED t. Err
947/// when a station t is not finite or a width is not strictly positive.
948pub fn junction_stencil(
949    left_nodes: &[Vec3],
950    right_nodes: &[Vec3],
951    station_ts: &[f64],
952    left: usize,
953) -> Result<(Vec<Vec3>, Option<Vec<f64>>), String> {
954    let half = OPEN_WALL_CENTRES / 2;
955    if left_nodes.len() != OPEN_WALL_CENTRES + 1 || right_nodes.len() != OPEN_WALL_CENTRES + 1 || left + 2 >= station_ts.len() {
956        return Err(format!("interval {left}: junction needs two {}-node intervals and their three station parameters", OPEN_WALL_CENTRES + 1));
957    }
958    let (t0, t1, t2) = (station_ts[left], station_ts[left + 1], station_ts[left + 2]);
959    let (w_left, w_right) = (t1 - t0, t2 - t1);
960    if !(t0.is_finite() && t1.is_finite() && t2.is_finite() && w_left > 0.0 && w_right > 0.0 && w_left.is_finite() && w_right.is_finite()) {
961        return Err(format!("interval {left}: junction station parameters {t0}, {t1}, {t2} are not finite and strictly increasing"));
962    }
963    let nodes: Vec<Vec3> = left_nodes[half..].iter().chain(&right_nodes[1..=half]).copied().collect();
964    if w_left.to_bits() == w_right.to_bits() {
965        return Ok((nodes, None));
966    }
967    let abscissae: Vec<f64> = (half..=OPEN_WALL_CENTRES)
968        .map(|j| if j == OPEN_WALL_CENTRES { t1 } else { t0 + w_left * j as f64 / OPEN_WALL_CENTRES as f64 })
969        .chain((1..=half).map(|j| t1 + w_right * j as f64 / OPEN_WALL_CENTRES as f64))
970        .collect();
971    Ok((nodes, Some(abscissae)))
972}
973
974/// One wall probe on a stencil: the ordinary uniform reader when it has no
975/// native abscissae (an interval's own nodes, or a junction of equal native
976/// widths), the native-abscissa reader when it has them.
977pub fn read_on_stencil(point: Vec3, nodes: &[Vec3], abscissae: Option<&[f64]>, step: usize, radius: f64) -> Result<(f64, f64), String> {
978    match abscissae {
979        None => crate::blend::chain::declared_wall_probe_why(point, nodes, step, radius),
980        Some(ts) => crate::blend::chain::declared_wall_probe_at_why(point, nodes, ts, step, radius),
981    }
982}
983
984/// Every interval's largest DECLARED wall reading (`chain::declared_wall_probe`,
985/// reading + uncertainty) on the open fillet `rows`, against the exact ball
986/// centres the march solved at j/32 of each interval ([`OpenDenseCentres`]),
987/// or, for each unread interval, WHY: its station
988/// interval and which component failed (no dense row, a dense row of the
989/// wrong size, an exact centre the march did not solve, a wall point the
990/// surface would not evaluate, a probe the declared reader declined, no probe
991/// in the shipped part, or a non-finite reading). The cause is diagnostic.
992///
993/// Read on the DECLARED SHIPPED REGION `window` only: an interval it overlaps
994/// is probed at its even stencil fractions that lie inside the window and at
995/// each window end inside the interval; a probe outside the window is not on
996/// the shipped wall and is not read. A window END whose nearest even stencil
997/// node falls outside 2..=30 -- an end within a node of the interval's own
998/// station, as the original bore's shipped spans were, 1e-16 from their
999/// vertex stations -- has its foot at the interval's end node, where
1000/// `crate::blend::chain::closed::declared_wall_probe` cannot read (the stencil
1001/// cannot follow a foot out of its own interval). It is read on a JUNCTION
1002/// stencil instead: the neighbouring interval's last half and this one's
1003/// first half (or this one's last half and the next one's first), the same
1004/// exact centres meeting at the shared station, with the probe at its
1005/// middle node. Two intervals of unequal native width (local insertions)
1006/// give the junction unequal node spacing, so it is then read by the
1007/// native-abscissa reader (`chain::declared_wall_probe_at_why`) on the
1008/// edge parameters the centres were solved at; of equal width, by the
1009/// ordinary reader. With no neighbour it is read as before.
1010/// The wall reading of an EXACT extrusion's rows, read directly: the wall is
1011/// the ball's sweep along the centre line, so every point of the shipped
1012/// surface stands exactly the radius off that line, and the reading is how
1013/// far it does not. One entry per interval overlapping `window`, probes at
1014/// the interval's quarters inside the window and at the window's ends, over
1015/// the section at k/8 (the ball-resolve reader's sections). Never for fitted
1016/// rows: those are read against the exact centres between their stations
1017/// ([`open_wall_readings_why`]).
1018pub fn exact_extrusion_wall_readings(
1019    rows: &FittedRows,
1020    parameters: &[f64],
1021    window: [f64; 2],
1022    radius: f64,
1023) -> Vec<Result<f64, String>> {
1024    let intervals = parameters.len().saturating_sub(1);
1025    let overlapped: Vec<usize> =
1026        (0..intervals).filter(|&interval| parameters[interval + 1] > window[0] && parameters[interval] < window[1]).collect();
1027    let line = match (rows.exact_extrusion, rows.center.as_ref()) {
1028        (true, Some(center)) => center.domain().and_then(|[a, b]| Ok((center.evaluate(a)?, center.evaluate(b)?))),
1029        (false, _) => Err("the rows are not an exact extrusion".to_string()),
1030        (true, None) => Err("the exact rows carry no centre line".to_string()),
1031    };
1032    let (anchor, direction) = match line.and_then(|(a, b)| b.sub(a).normalized().map(|d| (a, d))) {
1033        Ok(line) => line,
1034        Err(error) => return overlapped.iter().map(|interval| Err(format!("interval {interval}: {error}"))).collect(),
1035    };
1036    let Ok([v_low, v_high]) = rows.surface.domain_v() else {
1037        return overlapped.iter().map(|interval| Err(format!("interval {interval}: wall surface v domain unreadable"))).collect();
1038    };
1039    overlapped
1040        .into_iter()
1041        .map(|interval| -> Result<f64, String> {
1042            let (from, to) = (parameters[interval], parameters[interval + 1]);
1043            let inside = |u: f64| u >= window[0] && u <= window[1];
1044            let mut probes: Vec<f64> =
1045                (1..4).map(|step| from + (to - from) * step as f64 / 4.0).filter(|u| inside(*u)).collect();
1046            probes.extend(window.into_iter().filter(|end| *end > from && *end < to));
1047            if probes.is_empty() {
1048                return Err(format!("interval {interval}: no probe in its shipped part of [{:.17}, {:.17}]", window[0], window[1]));
1049            }
1050            let mut worst = 0.0_f64;
1051            for u in probes {
1052                for k in 1..OPEN_WALL_SECTIONS {
1053                    let v = v_low + (v_high - v_low) * k as f64 / OPEN_WALL_SECTIONS as f64;
1054                    let point = rows.surface.evaluate(u, v).map_err(|error| format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) unreadable: {error}"))?;
1055                    let offset = point.sub(anchor);
1056                    let standoff = offset.sub(direction.scale(offset.dot(direction))).length();
1057                    let reading = (standoff - radius).abs();
1058                    if !reading.is_finite() {
1059                        return Err(format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) reads {reading}"));
1060                    }
1061                    worst = worst.max(reading);
1062                }
1063            }
1064            Ok(worst)
1065        })
1066        .collect()
1067}
1068
1069/// The wall reading of a still ball's rows (a blend over a concave round of
1070/// its own radius: every section's centre is one point, the wall a sphere
1071/// patch), read directly: every point of the shipped surface stands exactly
1072/// the radius off that centre, and the reading is how far it does not. The
1073/// slope reader cannot read it (the centre path has no slope). Eight probes an
1074/// interval, one entry per interval overlapping `window`.
1075pub fn exact_ball_wall_readings(
1076    rows: &FittedRows,
1077    parameters: &[f64],
1078    window: [f64; 2],
1079    centre: Vec3,
1080    radius: f64,
1081) -> Vec<Result<f64, String>> {
1082    let intervals = parameters.len().saturating_sub(1);
1083    let overlapped: Vec<usize> =
1084        (0..intervals).filter(|&interval| parameters[interval + 1] > window[0] && parameters[interval] < window[1]).collect();
1085    let Ok([v_low, v_high]) = rows.surface.domain_v() else {
1086        return overlapped.iter().map(|interval| Err(format!("interval {interval}: wall surface v domain unreadable"))).collect();
1087    };
1088    overlapped
1089        .into_iter()
1090        .map(|interval| -> Result<f64, String> {
1091            let (from, to) = (parameters[interval], parameters[interval + 1]);
1092            let inside = |u: f64| u >= window[0] && u <= window[1];
1093            let mut probes: Vec<f64> =
1094                (1..8).map(|step| from + (to - from) * step as f64 / 8.0).filter(|u| inside(*u)).collect();
1095            probes.extend(window.into_iter().filter(|end| *end > from && *end < to));
1096            if probes.is_empty() {
1097                return Err(format!("interval {interval}: no probe in its shipped part of [{:.17}, {:.17}]", window[0], window[1]));
1098            }
1099            let mut worst = 0.0_f64;
1100            for u in probes {
1101                for k in 1..OPEN_WALL_SECTIONS {
1102                    let v = v_low + (v_high - v_low) * k as f64 / OPEN_WALL_SECTIONS as f64;
1103                    let point = rows.surface.evaluate(u, v).map_err(|error| format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) unreadable: {error}"))?;
1104                    let reading = (point.sub(centre).length() - radius).abs();
1105                    if !reading.is_finite() {
1106                        return Err(format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) reads {reading}"));
1107                    }
1108                    worst = worst.max(reading);
1109                }
1110            }
1111            Ok(worst)
1112        })
1113        .collect()
1114}
1115
1116/// The wall reading of an EXACT REVOLUTION's rows
1117/// (`support::exact_revolution_rows`), read directly: the wall is the ball's
1118/// sweep along the centre CIRCLE, so every point of the shipped surface
1119/// stands exactly the radius off that circle, and the reading is how far it
1120/// does not. The distance to the circle is closed-form in the point's
1121/// meridian half-plane: `hypot(ρ − R_c, h − h_c)` for the point's radial
1122/// distance ρ and axial height h about the rows' axis. Same probes as
1123/// [`exact_extrusion_wall_readings`]: one entry per interval overlapping
1124/// `window`, the interval's quarters inside the window and the window's
1125/// ends, over the section at k/8.
1126pub(in crate::blend) fn exact_revolution_wall_readings(
1127    rows: &FittedRows,
1128    parameters: &[f64],
1129    window: [f64; 2],
1130    radius: f64,
1131) -> Vec<Result<f64, String>> {
1132    let intervals = parameters.len().saturating_sub(1);
1133    let overlapped: Vec<usize> =
1134        (0..intervals).filter(|&interval| parameters[interval + 1] > window[0] && parameters[interval] < window[1]).collect();
1135    let circle = match (rows.revolution_axis, rows.center.as_ref()) {
1136        (Some((origin, axis)), Some(center)) => center.domain().and_then(|[a, _]| center.evaluate(a)).map(|point| (origin, axis, point)),
1137        (None, _) => Err("the rows are not an exact revolution".to_string()),
1138        (Some(_), None) => Err("the exact rows carry no centre circle".to_string()),
1139    };
1140    let (origin, axis, centre_radius, centre_height) = match circle {
1141        Ok((origin, axis, point)) => {
1142            let offset = point.sub(origin);
1143            let height = offset.dot(axis);
1144            (origin, axis, offset.sub(axis.scale(height)).length(), height)
1145        }
1146        Err(error) => return overlapped.iter().map(|interval| Err(format!("interval {interval}: {error}"))).collect(),
1147    };
1148    let Ok([v_low, v_high]) = rows.surface.domain_v() else {
1149        return overlapped.iter().map(|interval| Err(format!("interval {interval}: wall surface v domain unreadable"))).collect();
1150    };
1151    overlapped
1152        .into_iter()
1153        .map(|interval| -> Result<f64, String> {
1154            let (from, to) = (parameters[interval], parameters[interval + 1]);
1155            let inside = |u: f64| u >= window[0] && u <= window[1];
1156            let mut probes: Vec<f64> =
1157                (1..4).map(|step| from + (to - from) * step as f64 / 4.0).filter(|u| inside(*u)).collect();
1158            probes.extend(window.into_iter().filter(|end| *end > from && *end < to));
1159            if probes.is_empty() {
1160                return Err(format!("interval {interval}: no probe in its shipped part of [{:.17}, {:.17}]", window[0], window[1]));
1161            }
1162            let mut worst = 0.0_f64;
1163            for u in probes {
1164                for k in 1..OPEN_WALL_SECTIONS {
1165                    let v = v_low + (v_high - v_low) * k as f64 / OPEN_WALL_SECTIONS as f64;
1166                    let point = rows.surface.evaluate(u, v).map_err(|error| format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) unreadable: {error}"))?;
1167                    let offset = point.sub(origin);
1168                    let height = offset.dot(axis);
1169                    let radial = offset.sub(axis.scale(height)).length();
1170                    let standoff = (radial - centre_radius).hypot(height - centre_height);
1171                    let reading = (standoff - radius).abs();
1172                    if !reading.is_finite() {
1173                        return Err(format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) reads {reading}"));
1174                    }
1175                    worst = worst.max(reading);
1176                }
1177            }
1178            Ok(worst)
1179        })
1180        .collect()
1181}
1182
1183pub fn open_wall_readings_why(
1184    rows: &FittedRows,
1185    parameters: &[f64],
1186    stations: &[Station],
1187    window: [f64; 2],
1188    dense: &OpenDenseCentres,
1189    radius: f64,
1190) -> Vec<Result<f64, String>> {
1191    // A still ball (every station's centre the same point, bit for bit: only
1192    // the stationary stations build that) is a sphere patch, read exactly.
1193    if crate::blend::stations::stationary_ball::enabled() && crate::blend::stations::stationary_ball::is_still(stations) {
1194        return exact_ball_wall_readings(rows, parameters, window, stations[0].center, radius);
1195    }
1196    let intervals = parameters.len().saturating_sub(1);
1197    let overlapped: Vec<usize> =
1198        (0..intervals).filter(|&interval| parameters[interval + 1] > window[0] && parameters[interval] < window[1]).collect();
1199    let Ok([v_low, v_high]) = rows.surface.domain_v() else {
1200        return overlapped.iter().map(|interval| Err(format!("interval {interval}: wall surface v domain unreadable"))).collect();
1201    };
1202    // The exact centres of one interval at j/32, its stations at both ends.
1203    let nodes_of = |interval: usize| -> Result<Vec<Vec3>, String> {
1204        let inner = dense.centres.get(interval).ok_or_else(|| format!("interval {interval}: no dense centre row"))?;
1205        if dense.subdivisions != OPEN_WALL_CENTRES || inner.len() + 1 != OPEN_WALL_CENTRES {
1206            return Err(format!("interval {interval}: dense row {} centres at {} subdivisions", inner.len(), dense.subdivisions));
1207        }
1208        let mut centres = Vec::with_capacity(OPEN_WALL_CENTRES + 1);
1209        centres.push(stations[interval].center);
1210        for (j, centre) in inner.iter().enumerate() {
1211            centres.push(centre.ok_or_else(|| format!("interval {interval}: exact centre {} of {OPEN_WALL_CENTRES} unsolved", j + 1))?);
1212        }
1213        centres.push(stations[interval + 1].center);
1214        Ok(centres)
1215    };
1216    let half = OPEN_WALL_CENTRES / 2;
1217    // The junction stencil across the station between `left` and `left + 1`:
1218    // left's nodes half..=32, then right's nodes 1..=half; the station is node
1219    // `half`. With each node's NATIVE abscissa (the edge parameter its exact
1220    // centre was solved at, `OpenDenseCentres::station_ts`), and `None` when
1221    // the two intervals' native widths are bitwise equal: the nodes are then
1222    // uniform and the ordinary reader reads them, bit for bit.
1223    let junction = |left: usize| -> Result<(Vec<Vec3>, Option<Vec<f64>>), String> {
1224        if dense.station_ts.len() != parameters.len() {
1225            return Err(format!("interval {left}: junction without the native station parameters"));
1226        }
1227        junction_stencil(&nodes_of(left)?, &nodes_of(left + 1)?, &dense.station_ts, left)
1228    };
1229    overlapped
1230        .into_iter()
1231        .map(|interval| -> Result<f64, String> {
1232            let centres = nodes_of(interval)?;
1233            let (from, to) = (parameters[interval], parameters[interval + 1]);
1234            let inside = |u: f64| u >= window[0] && u <= window[1];
1235            // (u, stencil node, the stencil: None = this interval's own;
1236            // a junction's nodes with its native abscissae when unequal).
1237            let mut probes: Vec<(f64, usize, Option<(Vec<Vec3>, Option<Vec<f64>>)>)> = (2..OPEN_WALL_CENTRES)
1238                .step_by(2)
1239                .map(|step| (from + (to - from) * step as f64 / OPEN_WALL_CENTRES as f64, step))
1240                .filter(|(u, _)| inside(*u))
1241                .map(|(u, step)| (u, step, None))
1242                .collect();
1243            for end in window {
1244                if end > from && end < to {
1245                    let fraction = (end - from) / (to - from);
1246                    let nearest = 2 * ((fraction * OPEN_WALL_CENTRES as f64 / 2.0).round() as usize);
1247                    #[cfg(not(test))]
1248                    let junction_off = false;
1249                    if junction_off {
1250                        probes.push((end, nearest.clamp(2, OPEN_WALL_CENTRES - 2), None));
1251                    } else if nearest < 2 && interval > 0 {
1252                        probes.push((end, half, Some(junction(interval - 1)?)));
1253                    } else if nearest > OPEN_WALL_CENTRES - 2 && interval + 1 < intervals {
1254                        probes.push((end, half, Some(junction(interval)?)));
1255                    } else {
1256                        probes.push((end, nearest.clamp(2, OPEN_WALL_CENTRES - 2), None));
1257                    }
1258                }
1259            }
1260            if probes.is_empty() {
1261                return Err(format!("interval {interval}: no probe in its shipped part of [{:.17}, {:.17}]", window[0], window[1]));
1262            }
1263            let mut declared = 0.0_f64;
1264            for (u, step, stencil) in probes {
1265                let (nodes, abscissae, what) = match &stencil {
1266                    Some((nodes, None)) => (nodes, None, "junction"),
1267                    Some((nodes, Some(ts))) => (nodes, Some(ts), "native-abscissa junction"),
1268                    None => (&centres, None, "interval"),
1269                };
1270                for k in 1..OPEN_WALL_SECTIONS {
1271                    let v = v_low + (v_high - v_low) * k as f64 / OPEN_WALL_SECTIONS as f64;
1272                    let point = rows.surface.evaluate(u, v).map_err(|error| format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) unreadable: {error}"))?;
1273                    // The interval's own stencil reads from the probe's node,
1274                    // then (declined) from where its fraction reaches along the
1275                    // centre path (a stationary section); a junction keeps its
1276                    // own dispatch.
1277                    let read = if stencil.is_none() {
1278                        crate::blend::chain::declared_wall_probe_located_why(point, nodes, step, (u - from) / (to - from), radius)
1279                    } else {
1280                        read_on_stencil(point, nodes, abscissae.map(|ts| ts.as_slice()), step, radius)
1281                    };
1282                    let (reading, uncertainty) = read.map_err(|why| {
1283                        format!(
1284                            "interval {interval}: declared reader declined probe node {step} of the {what} stencil, section {k}/{OPEN_WALL_SECTIONS} \
1285                             (u {u:.17}): {why}"
1286                        )
1287                    })?;
1288                    declared = declared.max(reading + uncertainty);
1289                }
1290            }
1291            if declared.is_finite() { Ok(declared) } else { Err(format!("interval {interval}: non-finite reading {declared}")) }
1292        })
1293        .collect()
1294}
1295
1296
1297/// A fresh id allocator seeded past the vertex, edge, face, loop and coedge IDs.
1298/// Solid and shell IDs are outside this allocation domain. Shared by
1299/// a whole group of stripes so their vertices, edges and coedges cannot
1300/// collide.
1301pub fn fresh_id_source(solid: &BrepSolid) -> impl FnMut() -> u64 {
1302    let mut next_id = solid
1303        .vertices
1304        .iter()
1305        .map(|vertex| vertex.id)
1306        .chain(solid.edges.iter().map(|edge| edge.id))
1307        .chain(
1308            solid
1309                .shells
1310                .iter()
1311                .flat_map(|shell| &shell.faces)
1312                .flat_map(|face| {
1313                    face.loops
1314                        .iter()
1315                        .map(|loop_record| loop_record.id)
1316                        .chain(face.loops.iter().flat_map(|loop_record| {
1317                            loop_record.coedges.iter().map(|coedge| coedge.id)
1318                        }))
1319                        .chain(std::iter::once(face.id))
1320                }),
1321        )
1322        .max()
1323        .unwrap_or(0)
1324        + 1;
1325    move || {
1326        let id = next_id;
1327        next_id += 1;
1328        id
1329    }
1330}
1331
1332
1333/// May a declined support refit fall back on the march's own trim pcurve?
1334/// Only when that trim, read independently as shipped
1335/// (`read_shipped_pcurve`: miss, rail standoff, samples, worst), meets the
1336/// floor ON its rail's branch: its miss PLUS the rail's standoff from the
1337/// carrier at the trim's foot within `floor`. A trim on another branch of the
1338/// carrier tracks its own foot perfectly (miss 0) while that foot stands far
1339/// off the rail, so a miss alone would ship it; an unreadable trim never
1340/// stands.
1341pub fn march_trim_stands(read: &Result<(f64, f64, usize, f64), KernelRefusal>, floor: f64) -> bool {
1342    matches!(read, Ok((miss, standoff, _, _)) if *miss + *standoff <= floor)
1343}
1344
1345/// Slice 1b of the surgery lane: the support trim of a
1346/// straight rail on a PLANE, exact. The feet of the rail's two ends on the
1347/// plane (the kernel's closed-form projection) joined by a degree-1 pcurve
1348/// on the rail's own parameter range, so the surgery reads it at the rail's
1349/// parameter as it reads every trim; read once as shipped
1350/// (`read_shipped_pcurve`) and kept only when it stands within the pcurve
1351/// floor by the march trim's own rule (`march_trim_stands`: miss plus rail
1352/// standoff). `None` hands the trim to the refit road, as a march trim that
1353/// does not stand would be.
1354fn exact_planar_trim(rail: &NurbsCurve, surface: &NurbsSurface, d0: f64, d1: f64) -> Result<Option<NurbsCurve>, KernelRefusal> {
1355    if !matches!(surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) || !(d1 > d0) {
1356        return Ok(None);
1357    }
1358    let feet_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.feet_ms");
1359    let mut control = Vec::with_capacity(2);
1360    for t in [d0, d1] {
1361        let point = rail.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
1362        let foot = crate::project_point_to_surface(surface, point).or_refuse(KernelStage::Refine, "project")?;
1363        control.push(crate::Vec4::from_point(crate::Vec3::new(foot.u, foot.v, 0.0), 1.0));
1364    }
1365    let line = NurbsCurve::new(1, vec![d0, d0, d1, d1], control).or_refuse(KernelStage::Refine, "new")?;
1366    feet_timing.stop();
1367    let read_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.read_ms");
1368    let read = match affine_trim_read(rail, surface, &line, d0, d1) {
1369        Some(read) => {
1370            crate::blend::record_count("count.read.affine_trims", 1);
1371            Ok(read)
1372        }
1373        None => crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), &line, d0, d1),
1374    };
1375    read_timing.stop();
1376    Ok(march_trim_stands(&read, crate::pcurve::PCURVE_REFINEMENT_TOLERANCE).then_some(line))
1377}
1378
1379/// [`read_shipped_pcurve`](crate::blend::track_fit::read_shipped_pcurve)'s
1380/// `(miss, standoff, samples, worst)` for a degree-1 `pcurve` on an AFFINE
1381/// plane against an affine rail, read at `d0` and `d1` only: the pcurve's
1382/// image, the rail and the rail's foot on the plane are all affine in the
1383/// rail parameter, so the miss (image to foot) and the standoff (rail to foot)
1384/// are norms of affine functions, convex, and largest at an end. `None` when
1385/// any of the three is not affine, or an end will not evaluate.
1386fn affine_trim_read(rail: &NurbsCurve, surface: &NurbsSurface, pcurve: &NurbsCurve, d0: f64, d1: f64) -> Option<(f64, f64, usize, f64)> {
1387    if !affine_curve(rail) || !affine_curve(pcurve) {
1388        return None;
1389    }
1390    let (origin, normal) = affine_plane(surface)?;
1391    let (mut miss, mut standoff, mut worst) = (0.0f64, 0.0f64, d0);
1392    for t in [d0, d1] {
1393        let point = rail.evaluate(t).ok()?;
1394        let foot = point.sub(normal.scale(point.sub(origin).dot(normal)));
1395        let uv = pcurve.evaluate(t).ok()?;
1396        let image = crate::blend::track_fit::carrier_point(surface, uv.x, uv.y).ok()?;
1397        let (residual, off) = (image.sub(foot).length(), point.sub(foot).length());
1398        if !(residual.is_finite() && off.is_finite()) {
1399            return None;
1400        }
1401        if residual > miss {
1402            (miss, worst) = (residual, t);
1403        }
1404        standoff = standoff.max(off);
1405    }
1406    Some((miss, standoff, 2, worst))
1407}
1408
1409/// Sew ONE stripe into `result`.
1410///
1411/// `solid` is the ORIGINAL topology every stripe was marched against (the
1412/// row-coincidence detection reads it); `result` is the shared evolving
1413/// solid, and `take_id` the shared id allocator — a group of stripes meeting
1414/// at a corner must create their rim vertices and cross-section arcs from one
1415/// counter, and must see each other's work.
1416///
1417/// Each end is either free (terminate on the face across the corner) or a
1418/// corner stop; see [`EndPlan`].  Pruning orphaned vertices is the caller's
1419/// job, once, after every stripe of the group is in.
1420pub(in crate::blend) fn build_open_surgery(
1421    solid: &BrepSolid,
1422    result: &mut BrepSolid,
1423    take_id: &mut dyn FnMut() -> u64,
1424    edge: &EdgeRecord,
1425    first: &BlendMate,
1426    second: &BlendMate,
1427    rows: FittedRows,
1428    ends: [EndPlan; 2],
1429    name: Option<&str>,
1430) -> Result<SewnStripe, KernelRefusal> {
1431    build_open_surgery_with_tail(solid, result, take_id, edge, first, second, rows, ends, name, [None, None])
1432}
1433
1434/// [`build_open_surgery`] for a stripe whose finish end rolled onto tangent
1435/// neighbours (`crate::blend::rollover::stopped_end_tail`, switch, default
1436/// off): after the pristine sewing, each rolled side's rail is split at its
1437/// crossing vertex, the part past it and the cap's leg move from the mate's
1438/// loop into the neighbour's — where they replace the run of the crossed
1439/// tangent edge from the crossing to the sharp vertex, which is deleted —
1440/// and the part past it gets its pcurve on the neighbour. The mate keeps the
1441/// rail up to the crossing and the rest of the tangent edge. With no rolled
1442/// side the sewing is exactly [`build_open_surgery`]'s.
1443#[allow(clippy::too_many_arguments)]
1444pub fn build_open_surgery_with_tail(
1445    solid: &BrepSolid,
1446    result: &mut BrepSolid,
1447    take_id: &mut dyn FnMut() -> u64,
1448    edge: &EdgeRecord,
1449    first: &BlendMate,
1450    second: &BlendMate,
1451    rows: FittedRows,
1452    ends: [EndPlan; 2],
1453    name: Option<&str>,
1454    tail: [Option<crate::blend::rollover::TailSplice<'_>>; 2],
1455) -> Result<SewnStripe, KernelRefusal> {
1456    let [start_end, finish_end] = ends;
1457
1458    // Trim the support rows to the crossing window.
1459    // A POLE end stops EXACTLY on the row's own end (the march puts the
1460    // pole's station there and overshoots no further), so there is nothing to
1461    // split off on that side.  Only equality: a stop PAST the row's end — a
1462    // free end's crossing the rows never reached — still fails the split and
1463    // refuses, rather than building a rail out to wherever the rows stop.
1464    //
1465    // `NurbsCurve::split` cuts at a knot lying within `KNOT_IDENTITY_TOL` of
1466    // the stop instead of at the stop. On a long rail that is not a small
1467    // distance: a ten-metre swept bar's support rail runs ~9000 per unit of
1468    // its parameter, and a march station 5e-11 from the free end's crossing
1469    // put the trimmed rail's end 4.4e-7 past the cap it stops on, off its
1470    // carrier, where no support pcurve can reach the 1e-7 floor. Where the
1471    // cut moved the piece's end by more than a tenth of that floor, its end
1472    // control point (a clamped curve's end point) is pinned back onto the row
1473    // at the stop. A smaller move (rows of ordinary size read up to 1.7e-9)
1474    // holds no fit off the floor and is left exactly as cut.
1475    // `pinned`: `None` pins a 3D row's end where its cut moved it past that
1476    // bar and reports which ends it pinned; `Some(ends)` pins exactly those
1477    // ends (the row's uv trim follows its rail).
1478    let pin = |piece: &mut NurbsCurve, at_end: bool, point: Vec3, force: Option<bool>| -> bool {
1479        let index = if at_end { piece.control_points.len() - 1 } else { 0 };
1480        let control = piece.control_points[index];
1481        let cut = Vec3::new(control.x / control.w, control.y / control.w, control.z / control.w);
1482        let moved = force.unwrap_or_else(|| cut.sub(point).length() > 0.1 * crate::pcurve::PCURVE_REFINEMENT_TOLERANCE);
1483        if moved {
1484            piece.control_points[index] = Vec4::from_point(point, control.w);
1485        }
1486        moved
1487    };
1488    let trim_row = |row: &NurbsCurve, a: f64, b: f64, pinned: Option<[bool; 2]>| -> Result<(NurbsCurve, [bool; 2]), KernelRefusal> {
1489        let [low, high] = row.domain().or_refuse(KernelStage::Refine, "domain")?;
1490        let mut ends = [false; 2];
1491        let mut tail = if a == low { row.clone() } else { row.split(a).or_refuse(KernelStage::Refine, "split")?.1 };
1492        if a != low {
1493            ends[0] = pin(&mut tail, false, row.evaluate(a).or_refuse(KernelStage::Refine, "evaluate")?, pinned.map(|ends| ends[0]));
1494        }
1495        if b == high {
1496            return Ok((tail, ends));
1497        }
1498        let (mut middle, _) = tail.split(b).or_refuse(KernelStage::Refine, "split")?;
1499        ends[1] = pin(&mut middle, true, row.evaluate(b).or_refuse(KernelStage::Refine, "evaluate")?, pinned.map(|ends| ends[1]));
1500        Ok((middle, ends))
1501    };
1502    let kind = |plan: &EndPlan| match plan {
1503        EndPlan::Free(_) => "free",
1504        EndPlan::Corner(_) => "corner",
1505        EndPlan::Miter(_) => "miter",
1506        EndPlan::Cap(_) => "cap",
1507    };
1508    let describe_trim = |error: KernelRefusal| {
1509        error.with_message(|error| {
1510            format!(
1511                "{error} (edge {} rows trimmed for a {} start at cr {:.6}/cs {:.6} and a {} finish \
1512                 at cr {:.6}/cs {:.6})",
1513                edge.id,
1514                kind(&start_end),
1515                start_end.cr_parameter(),
1516                start_end.cs_parameter(),
1517                kind(&finish_end),
1518                finish_end.cr_parameter(),
1519                finish_end.cs_parameter()
1520            )
1521        })
1522    };
1523    // A rail whose two stops are one point within `consumed_band` has no strip
1524    // to trim: the blend takes that mate down to a single point along this
1525    // edge.  That is a FULL-WIDTH corner — the shared face of a miter whose
1526    // radius is the side face's width, every face of a star at full width, the
1527    // middle edge of a channel whose two corner setbacks meet.  No rail edge is
1528    // built; the mate loses the blended edge instead of having it replaced, and
1529    // the rail's two rim vertices are one vertex, which the orchestrator
1530    // identifies (`SewnStripe::identified`) once every stripe is in.  A stripe
1531    // free at BOTH ends has no corner to collapse onto, so it refuses.
1532    let band = consumed_band(solid);
1533    let collapses = |row: &NurbsCurve, a: f64, b: f64| -> Result<bool, KernelRefusal> {
1534        let from = row.evaluate(a).or_refuse(KernelStage::Refine, "evaluate")?;
1535        Ok(row.evaluate(b).or_refuse(KernelStage::Refine, "evaluate")?.sub(from).length() <= band
1536            && row.evaluate(0.5 * (a + b)).or_refuse(KernelStage::Refine, "evaluate")?.sub(from).length() <= band)
1537    };
1538    let cr_collapsed = collapses(&rows.cr, start_end.cr_parameter(), finish_end.cr_parameter())?;
1539    let cs_collapsed = collapses(&rows.cs, start_end.cs_parameter(), finish_end.cs_parameter())?;
1540    if cr_collapsed || cs_collapsed {
1541        let unsupported = if start_end.free().is_some() && finish_end.free().is_some() {
1542            Some("neither end is a corner")
1543        } else if first.face.id == second.face.id {
1544            Some("both rails lie on one face")
1545        } else if matches!(start_end, EndPlan::Cap(_)) || matches!(finish_end, EndPlan::Cap(_)) {
1546            Some("a capped end has no corner to share the point with")
1547        } else {
1548            None
1549        };
1550        if let Some(reason) = unsupported {
1551            return Err(KernelRefusal::unsupported(KernelStage::Sew, super::RAIL_COLLAPSE_WHAT, format!(
1552                "{RAIL_COLLAPSE_UNSUPPORTED} edge {}'s rail shrinks to a point and {reason}",
1553                edge.id
1554            )));
1555        }
1556    }
1557    // The support pcurve the rows carry interpolates the stations' (u, v) and
1558    // is read nowhere between them: on the 20-degree crossing's notched open
1559    // exit arc it stood 2.98e-5 off the rail it trims (with the
1560    // section-fit fix, read against the exact cylinders). Inside the crossing
1561    // window — on the face, never on a carrier's extension — it is refitted
1562    // to the trimmed rail's own projected track at the pcurve floor and read
1563    // again as shipped (`refit_closed_support_pcurve`, the closed edge's).
1564    // A rail that overruns a PLANE carrier's chart (the rib-base fin top's
1565    // rails run 0.303 past it) is on the plane's extension, which the chart
1566    // clamps: there the refit and both reads would measure the clamp, and the
1567    // trim is instead rebuilt from its edge on the widened chart and verified
1568    // at the floor by `fit_planar_charts_to_trims`, which every lane that
1569    // sews these stripes runs.
1570    let trim_rail = |collapsed: bool,
1571                     row: &NurbsCurve,
1572                     pcurve: &NurbsCurve,
1573                     surface: &NurbsSurface,
1574                     a: f64,
1575                     b: f64|
1576     -> Result<Option<(NurbsCurve, NurbsCurve)>, KernelRefusal> {
1577        if collapsed {
1578            return Ok(None);
1579        }
1580        let rows_timing = crate::blend::BlendTimer::start("timing.surgery.trim.rows_ms");
1581        let (rail, pinned) = trim_row(row, a, b, None).map_err(describe_trim)?;
1582        let (interpolated, _) = trim_row(pcurve, a, b, Some(pinned))?;
1583        rows_timing.stop();
1584        {
1585            let overrun_timing = crate::blend::BlendTimer::start("timing.surgery.trim.overrun_ms");
1586            let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1587            let overrun = crate::blend::planar_chart_overrun(surface, &|t| rail.evaluate(t), d0, d1)?;
1588            overrun_timing.stop();
1589            if overrun.is_some_and(|excursion| excursion > band) {
1590                return Ok(Some((rail, interpolated)));
1591            }
1592        }
1593        let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1594        // Slice 1b: an exact extrusion row's rail on a
1595        // plane ships the exact line in uv, read once; the refit road below
1596        // is for what it declines.
1597        if rows.exact_extrusion {
1598            if let Some(line) = exact_planar_trim(&rail, surface, d0, d1)? {
1599                crate::blend::record_count("count.surgery.exact_trim", 1);
1600                return Ok(Some((rail, line)));
1601            }
1602        }
1603        // The exact REVOLUTION rows' own trims are exact by construction
1604        // (the carrier's uv line, the plane's affine image of the rail):
1605        // read once as shipped by the march trim's rule (`march_trim_stands`)
1606        // and kept; whatever does not stand takes the refit road below.
1607        if rows.revolution_axis.is_some() {
1608            // Lane N row 4: the pair bounded in closed form stands without a
1609            // sample (`exact_revolution_read_bound` on the UNCUT row and
1610            // pcurve, whose restrictions to [a, b] these are: miss + standoff
1611            // within three bounds).
1612            if exact_revolution_reads_on() {
1613                let cert_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.cert_ms");
1614                let bound = exact_revolution_read_bound(row, surface, pcurve);
1615                cert_timing.stop();
1616                if bound.is_some_and(|bound| 3.0 * bound <= crate::pcurve::PCURVE_REFINEMENT_TOLERANCE) {
1617                    crate::blend::record_count("count.surgery.exact_revolution_trim_certified", 1);
1618                    return Ok(Some((rail, interpolated)));
1619                }
1620            }
1621            let read_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.read_ms");
1622            let read = crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), &interpolated, d0, d1);
1623            read_timing.stop();
1624            if march_trim_stands(&read, crate::pcurve::PCURVE_REFINEMENT_TOLERANCE) {
1625                crate::blend::record_count("count.surgery.exact_revolution_trim", 1);
1626                return Ok(Some((rail, interpolated)));
1627            }
1628            crate::blend::record_count("count.surgery.exact_revolution_trim_declined", 1);
1629        }
1630        // The march's OWN trim pcurve, read independently at the rail's own
1631        // parameter against the same floor (`read_shipped_pcurve`): what a
1632        // declined refit may fall back to, and the standoff a refit on the
1633        // rail's own branch must match.
1634        // The feet of each pcurve against the rail are sought once and
1635        // shared between the reads below (`FootMemo`): the march trim's for
1636        // its own read and the branch comparison, the refit's for the
1637        // refit's own read, the branch comparison and the absolute bound.
1638        let mut march_feet = crate::blend::track_fit::FootMemo::default();
1639        let mut refit_feet = crate::blend::track_fit::FootMemo::default();
1640        let march_read_timing = crate::blend::BlendTimer::start("timing.surgery.trim.read.march_ms");
1641        let march_read = crate::blend::track_fit::read_shipped_pcurve_memo(surface, &|t| rail.evaluate(t), &interpolated, d0, d1, &mut march_feet);
1642        march_read_timing.stop();
1643        let floor = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
1644        let declined = |why: KernelRefusal| -> Result<Option<(NurbsCurve, NurbsCurve)>, KernelRefusal> {
1645            // Kept ONLY when the march's trim stands on its own read
1646            // (`march_trim_stands`); otherwise the refusal stands.
1647            let stands = march_trim_stands(&march_read, floor);
1648            if stands {
1649                Ok(Some((rail.clone(), interpolated.clone())))
1650            } else {
1651                Err(why)
1652            }
1653        };
1654        let refit_timing = crate::blend::BlendTimer::start("timing.surgery.trim.refit_ms");
1655        let refit = super::closed::refit_closed_support_pcurve_read(&rail, &interpolated, surface, &mut refit_feet);
1656        refit_timing.stop();
1657        let _reads_timing = crate::blend::BlendTimer::start("timing.surgery.trim.reads_ms");
1658        match refit {
1659            Ok((fitted, refit_read)) => {
1660                // A refit tracks ITS OWN projected track; a track that took
1661                // another branch of the carrier tracks itself perfectly while
1662                // its foot stands far off the rail (the stationary-start
1663                // prism's coedge read 6.0 off its edge). Its foot standoff
1664                // must be the rail's own standoff on the march trim's branch.
1665                // BOTH reads are required: an unreadable refit read declines
1666                // the refit (the march trim then stands only on its own read
1667                // within the floor), and an unreadable march read cannot
1668                // establish that the refit is on the rail's branch, so it
1669                // refuses. Never shipped on an unknown.
1670                // The two are compared POINTWISE, at the same rail
1671                // parameters (`standoff_excess`), never as two maxima read at
1672                // each curve's own knots.
1673                // The refit's read is the shipped curve's own, handed back by
1674                // the refit (the same `read_shipped_pcurve` on the same
1675                // inputs, once).
1676                let (march_standoff, refit_standoff) = match (&march_read, Ok::<_, KernelRefusal>(refit_read)) {
1677                    (_, Err(error)) => return declined(error),
1678                    (Err(error), Ok(_)) => {
1679                        return Err(KernelRefusal::non_convergence(KernelStage::Refine, "support_refit_branch_unread", format!(
1680                            "blend: a support trim's refit cannot be shown to stand on its rail's branch: the march's own \
1681                             trim is unreadable ({})",
1682                            error.message
1683                        )));
1684                    }
1685                    (Ok((_, march_standoff, _, _)), Ok((_, refit_standoff, _, _))) => (*march_standoff, refit_standoff),
1686                };
1687                let excess_timing = crate::blend::BlendTimer::start("timing.surgery.trim.read.excess_ms");
1688                let excess = crate::blend::track_fit::standoff_excess_memo(
1689                    surface, &|t| rail.evaluate(t), &interpolated, &fitted, d0, d1, &mut march_feet, &mut refit_feet,
1690                );
1691                excess_timing.stop();
1692                let excess = match excess {
1693                    Ok(excess) => excess,
1694                    Err(error) => return declined(error),
1695                };
1696                if !(excess <= floor) {
1697                    return declined(KernelRefusal::non_convergence(KernelStage::Refine, "support_refit_branch", format!(
1698                        "blend: a support trim's refit stands up to {excess:.3e} farther off its rail than the march's own trim \
1699                         at the same rail parameter (largest standoffs {refit_standoff:.3e} and {march_standoff:.3e}): it took \
1700                         another branch of the carrier"
1701                    )));
1702                }
1703                // ABSOLUTE: the comparison above is relative to the march
1704                // trim, so a refit that follows an off-branch march trim
1705                // passes it. The refit's foot must also stand within the floor
1706                // of the rail's own deviation from its carrier, read by the
1707                // nearest-point projector at the same parameters
1708                // (`standoff_over_nearest`) -- the rail's approximation the
1709                // lane reports, never more.
1710                let nearest_timing = crate::blend::BlendTimer::start("timing.surgery.trim.read.nearest_ms");
1711                let absolute = crate::blend::track_fit::standoff_over_nearest_memo(surface, &|t| rail.evaluate(t), &fitted, d0, d1, &mut refit_feet);
1712                nearest_timing.stop();
1713                let absolute = match absolute {
1714                    Ok(absolute) => absolute,
1715                    Err(error) => return declined(error),
1716                };
1717                if !(absolute <= floor) {
1718                    return declined(KernelRefusal::non_convergence(KernelStage::Refine, "support_refit_off_rail", format!(
1719                        "blend: a support trim's refit stands up to {absolute:.3e} farther off its rail than the rail stands \
1720                         off its carrier: its foot is not the rail's nearest point"
1721                    )));
1722                }
1723                Ok(Some((rail, fitted)))
1724            }
1725            Err(error) => declined(error),
1726        }
1727    };
1728    let trim_timing = crate::blend::BlendTimer::start("timing.surgery.trim_rails_ms");
1729    let cr_rail = trim_rail(
1730        cr_collapsed,
1731        &rows.cr,
1732        &rows.cr_pcurve,
1733        &first.face.surface,
1734        start_end.cr_parameter(),
1735        finish_end.cr_parameter(),
1736    )?;
1737    let cs_rail = trim_rail(
1738        cs_collapsed,
1739        &rows.cs,
1740        &rows.cs_pcurve,
1741        &second.face.surface,
1742        start_end.cs_parameter(),
1743        finish_end.cs_parameter(),
1744    )?;
1745    trim_timing.stop();
1746    // A collapsed rail's domain is its two stops, which are one point.
1747    let cr_domain = match &cr_rail {
1748        Some((cr, _)) => cr.domain().or_refuse(KernelStage::Refine, "domain")?,
1749        None => [start_end.cr_parameter(), finish_end.cr_parameter()],
1750    };
1751    let cs_domain = match &cs_rail {
1752        Some((cs, _)) => cs.domain().or_refuse(KernelStage::Refine, "domain")?,
1753        None => [start_end.cs_parameter(), finish_end.cs_parameter()],
1754    };
1755    // A rail's end points, read off the trimmed rail or, collapsed, the row.
1756    let cr_at = |parameter: f64| match &cr_rail {
1757        Some((cr, _)) => cr.evaluate(parameter),
1758        None => rows.cr.evaluate(parameter),
1759    };
1760    let cs_at = |parameter: f64| match &cs_rail {
1761        Some((cs, _)) => cs.evaluate(parameter),
1762        None => rows.cs.evaluate(parameter),
1763    };
1764    let old_start = edge.start_vertex_id;
1765    let old_finish = edge.end_vertex_id;
1766
1767    // Classify each of the four support crossings.  A crossing that lands at
1768    // the FAR endpoint of the boundary edge it meets (the end away from the
1769    // corner) means a prior fillet already consumed that whole boundary: the
1770    // new blend reuses the existing vertex there and the boundary edge is
1771    // deleted (its role is taken over by the new transverse curve on the
1772    // prior blend face).  An interior crossing is the pristine case — a fresh
1773    // vertex with the boundary trimmed to it.
1774    //
1775    // Consumed means within `consumed_band` — the slack `check_support_extent`
1776    // refuses past, so a rail between the two is not possible.
1777    let classify =
1778        |boundary_id: u64, boundary_param: f64, corner: u64| -> Result<RimResolution, KernelRefusal> {
1779            let boundary = result
1780                .edges
1781                .iter()
1782                .find(|candidate| candidate.id == boundary_id)
1783                .ok_or(KernelRefusal::internal(KernelStage::Sew, "end_boundary_edge", "blend: end boundary edge missing during surgery"))?;
1784            let span = (boundary.t1 - boundary.t0).abs().max(1e-12);
1785            let far_vertex = if boundary.start_vertex_id == corner {
1786                Some((boundary.end_vertex_id, boundary.t1, boundary.t0))
1787            } else if boundary.end_vertex_id == corner {
1788                Some((boundary.start_vertex_id, boundary.t0, boundary.t1))
1789            } else {
1790                None
1791            };
1792            if let Some((far_id, far_t, near_t)) = far_vertex {
1793                // A consumed boundary is a COINCIDENCE — a prior fillet's rim
1794                // vertex is exactly where this rail crosses — and the operands
1795                // were healed before the march, so it holds to solver
1796                // precision.  It is not "near the far end": a fillet whose
1797                // radius is 1e-3 short of the face's width crosses 1e-3 from
1798                // the far vertex and must keep that sliver, or the face is
1799                // snapped a full 1e-3 out of true (the oversized-radius limit
1800                // cases and issue 1177 measure exactly that).  Measured in
1801                // model units, never in the boundary's parameter — a unit
1802                // parameter on a 20-long edge would call 2e-3 a coincidence.
1803                let far_point = result
1804                    .vertices
1805                    .iter()
1806                    .find(|candidate| candidate.id == far_id)
1807                    .map(|candidate| candidate.point)
1808                    .ok_or(KernelRefusal::internal(KernelStage::Sew, "far_vertex", "blend: consumed boundary far vertex missing"))?;
1809                let crossing = boundary.curve.evaluate_extended(boundary_param).or_refuse(KernelStage::Refine, "evaluate_extended")?;
1810                let _ = span;
1811                let past_far = crossing.sub(far_point).length();
1812                if past_far <= band {
1813                    // Sanity: the reused vertex must exist.
1814                    if !result
1815                        .vertices
1816                        .iter()
1817                        .any(|candidate| candidate.id == far_id)
1818                    {
1819                        return Err(KernelRefusal::internal(KernelStage::Sew, "far_vertex", "blend: consumed boundary far vertex missing"));
1820                    }
1821                    return Ok(RimResolution::Consumed(far_id));
1822                }
1823                // A crossing BEYOND the far vertex is a rail that runs off
1824                // its face: the blend is wider than the face by more than the
1825                // band a snap may close, and trimming the boundary there would
1826                // extend it into air.  `check_support_extent` refuses this
1827                // before the march on every face the exact tool understands;
1828                // this is the refusal for the rest.  It is not the whole
1829                // answer: a crossing the solve CLAMPS to the far vertex reads
1830                // as consumed here, and `detect_row_coincidence` is what sees
1831                // that row leave the face.  Measured on the census: it fires on
1832                // a wall wider than its closed chain's arc (0.5 past) and on the
1833                // r = 10.001 pinch past an earlier round (2e-3 past), both of
1834                // which refused later in the surgery before.
1835                if (boundary_param - far_t) * (far_t - near_t) > 0.0 {
1836                    return Err(KernelRefusal::unsupported(KernelStage::Sew, "blend_wider_than_face", format!(
1837                        "{BLEND_WIDER_THAN_FACE} its rail crosses edge {boundary_id} {past_far:.3e} \
1838                         past that edge's far vertex, and a rail within {band:.3e} of it is the \
1839                         most this surgery snaps onto the edge"
1840                    )));
1841                }
1842            }
1843            Ok(RimResolution::Fresh)
1844        };
1845    // A CORNER end has no boundary to classify: the ball's tangency vertex is
1846    // the rim, and the boundary edge that used to reach the sharp corner is
1847    // the neighbouring stripe's own blended edge, which that stripe replaces.
1848    let resolve_side = |plan: &EndPlan,
1849                        side_first: bool,
1850                        corner: u64|
1851     -> Result<RimResolution, KernelRefusal> {
1852        if let Some(vertex) = plan.planned_rim(side_first) {
1853            return Ok(RimResolution::Corner(vertex));
1854        }
1855        match plan {
1856            EndPlan::Free(free) => classify(
1857                if side_first {
1858                    free.first_edge_id
1859                } else {
1860                    free.second_edge_id
1861                },
1862                if side_first {
1863                    free.first_edge_parameter
1864                } else {
1865                    free.second_edge_parameter
1866                },
1867                corner,
1868            ),
1869            EndPlan::Corner(_) | EndPlan::Miter(_) | EndPlan::Cap(_) => {
1870                Err(KernelRefusal::internal(KernelStage::Sew, "rim_vertices", "blend: planned end without rim vertices"))
1871            }
1872        }
1873    };
1874    let crossings_timing = crate::blend::BlendTimer::start("timing.surgery.crossings_ms");
1875    let start_first = resolve_side(&start_end, true, old_start)?;
1876    let start_second = resolve_side(&start_end, false, old_start)?;
1877    let finish_first = resolve_side(&finish_end, true, old_finish)?;
1878    let finish_second = resolve_side(&finish_end, false, old_finish)?;
1879    crossings_timing.stop();
1880    let _topology_timing = crate::blend::BlendTimer::start("timing.surgery.topology_ms");
1881
1882    // Manifold pairing: the blend's use of the first support row must oppose
1883    // F1's use of the blended edge (see the blend-loop construction below).
1884    let first_use_forward = first.coedge.forward;
1885    let blend_cr_forward = !first_use_forward;
1886
1887    // Curve-level coincidence (OCCT PR #1449 lesson 3): when BOTH of a mate's
1888    // crossings are endpoint-consumed AND the trimmed support row retraces the
1889    // existing edge joining the two far vertices, that mate face is FULLY
1890    // consumed — the surgery sews the blend face straight onto the existing
1891    // edge and drops the zero-width face, instead of creating a coincident
1892    // fresh support edge that would leave a sliver strip (the r = face-width
1893    // class).  Each side is detected independently; any ambiguity keeps the
1894    // pristine path (fail-safe).  `row_traversed_from_start`: the blend loop
1895    // walks cr in station order iff `blend_cr_forward`, and cs in the
1896    // OPPOSITE order (see the two loop branches below).
1897    // A stripe with a CORNER end has no boundary edges at that end to be
1898    // coincident with, so the detection only runs on stripes that are free at
1899    // both ends.  (Fail-safe: not detecting a coincidence keeps the pristine
1900    // path, which is what a corner stop wants anyway.)
1901    let (sew_first, sew_second) = match (start_end.free(), finish_end.free(), &cr_rail, &cs_rail) {
1902        (Some(start_free), Some(finish_free), Some((cr, _)), Some((cs, _))) => (
1903            detect_row_coincidence(
1904                solid,
1905                first,
1906                edge.id,
1907                start_free.first_edge_id,
1908                finish_free.first_edge_id,
1909                start_first.is_consumed(),
1910                start_first.existing().unwrap_or(0),
1911                finish_first.is_consumed(),
1912                finish_first.existing().unwrap_or(0),
1913                cr,
1914                blend_cr_forward,
1915                band,
1916            )?,
1917            detect_row_coincidence(
1918                solid,
1919                second,
1920                edge.id,
1921                start_free.second_edge_id,
1922                finish_free.second_edge_id,
1923                start_second.is_consumed(),
1924                start_second.existing().unwrap_or(0),
1925                finish_second.is_consumed(),
1926                finish_second.existing().unwrap_or(0),
1927                cs,
1928                !blend_cr_forward,
1929                band,
1930            )?,
1931        ),
1932        _ => (None, None),
1933    };
1934    // One face hosting both sides (the blended edge used twice by one face)
1935    // cannot be dropped for one side while the other still splices into it —
1936    // ambiguous, keep the pristine path for both.
1937    let (sew_first, sew_second): (Option<RowSew>, Option<RowSew>) =
1938        if first.face.id == second.face.id {
1939            (None, None)
1940        } else {
1941            (sew_first, sew_second)
1942        };
1943
1944    // Resolve the four rim vertices: reuse the existing vertex for a consumed
1945    // side, else create a fresh vertex at the support-row endpoint.
1946    let mut resolve = |rim: &RimResolution, point: Result<Vec3, String>| -> Result<u64, KernelRefusal> {
1947        match rim.existing() {
1948            Some(id) => Ok(id),
1949            None => {
1950                let id = take_id();
1951                result.vertices.push(VertexRecord { id, point: point.or_refuse(KernelStage::Refine, "point")? });
1952                Ok(id)
1953            }
1954        }
1955    };
1956    let w1a = resolve(&start_first, cr_at(cr_domain[0]))?;
1957    let w1b = resolve(&finish_first, cr_at(cr_domain[1]))?;
1958    let w2a = resolve(&start_second, cs_at(cs_domain[0]))?;
1959    let w2b = resolve(&finish_second, cs_at(cs_domain[1]))?;
1960    // How far the consumed rims and sewn rows moved a rail onto what already
1961    // existed — what `check_snap_closure` measures the body against.
1962    let mut snap = [&sew_first, &sew_second]
1963        .into_iter()
1964        .flatten()
1965        .fold(0.0f64, |worst, sew| worst.max(sew.deviation));
1966    for (rim, vertex, row_end) in [
1967        (&start_first, w1a, cr_at(cr_domain[0]).or_refuse(KernelStage::Refine, "cr_at")?),
1968        (&finish_first, w1b, cr_at(cr_domain[1]).or_refuse(KernelStage::Refine, "cr_at")?),
1969        (&start_second, w2a, cs_at(cs_domain[0]).or_refuse(KernelStage::Refine, "cs_at")?),
1970        (&finish_second, w2b, cs_at(cs_domain[1]).or_refuse(KernelStage::Refine, "cs_at")?),
1971    ] {
1972        if !rim.is_consumed() {
1973            continue;
1974        }
1975        let point = result
1976            .vertices
1977            .iter()
1978            .find(|candidate| candidate.id == vertex)
1979            .ok_or(KernelRefusal::internal(KernelStage::Sew, "rim_vertex", "blend: consumed rim vertex missing"))?
1980            .point;
1981        snap = snap.max(row_end.sub(point).length());
1982    }
1983
1984    // Support edges: a sewn side reuses the EXISTING coincident edge (no
1985    // fresh edge — OCCT's `SetExistingEdge` move); a pristine side gets the
1986    // fitted row as a fresh edge.
1987    // A collapsed side builds no edge at all.
1988    let cr_edge_id = match (&sew_first, &cr_rail) {
1989        (Some(sew), _) => Some(sew.edge_id),
1990        (None, None) => None,
1991        (None, Some((cr, _))) => {
1992            let id = take_id();
1993            result.edges.push(EdgeRecord {
1994                id,
1995                curve: cr.clone(),
1996                t0: cr_domain[0],
1997                t1: cr_domain[1],
1998                start_vertex_id: w1a,
1999                end_vertex_id: w1b,
2000                degenerate: false,
2001                name: None,
2002            });
2003            Some(id)
2004        }
2005    };
2006    let cs_edge_id = match (&sew_second, &cs_rail) {
2007        (Some(sew), _) => Some(sew.edge_id),
2008        (None, None) => None,
2009        (None, Some((cs, _))) => {
2010            let id = take_id();
2011            result.edges.push(EdgeRecord {
2012                id,
2013                curve: cs.clone(),
2014                t0: cs_domain[0],
2015                t1: cs_domain[1],
2016                start_vertex_id: w2a,
2017                end_vertex_id: w2b,
2018                degenerate: false,
2019                name: None,
2020            });
2021            Some(id)
2022        }
2023    };
2024    // The edge closing each end of the blend face: the §6.9 transverse curve
2025    // on the end face for a free end, or — at a corner — the end
2026    // cross-section arc the corner patch was already given, committed by the
2027    // caller and merely referenced here.
2028    let mut commit_split = |plan: &EndPlan, second_rim: u64, corner: u64| -> Result<Option<super::split_floor::SplitCommit>, KernelRefusal> {
2029        match plan.free().and_then(|free| free.split.as_ref()) {
2030            Some(split) => super::split_floor::commit_split_end(result, &mut *take_id, split, second_rim, corner).map(Some),
2031            None => Ok(None),
2032        }
2033    };
2034    let start_split = commit_split(&start_end, w2a, old_start)?;
2035    let finish_split = commit_split(&finish_end, w2b, old_finish)?;
2036    let mut commit_end_edge = |plan: &EndPlan,
2037                               first_rim: u64,
2038                               second_rim: u64|
2039     -> Result<Option<u64>, KernelRefusal> {
2040        match plan {
2041            EndPlan::Corner(_) | EndPlan::Miter(_) | EndPlan::Cap(_) => Ok(None),
2042            EndPlan::Free(free) => {
2043                let id = take_id();
2044                let domain = free.transverse_curve.domain().or_refuse(KernelStage::Refine, "domain")?;
2045                result.edges.push(EdgeRecord {
2046                    id,
2047                    curve: free.transverse_curve.clone(),
2048                    t0: domain[0],
2049                    t1: domain[1],
2050                    start_vertex_id: first_rim,
2051                    end_vertex_id: second_rim,
2052                    degenerate: false,
2053                    name: None,
2054                });
2055                Ok(Some(id))
2056            }
2057        }
2058    };
2059    let transverse_a_id = commit_end_edge(&start_end, w1a, start_split.as_ref().map_or(w2a, |split| split.q1_vertex))?;
2060    let transverse_b_id = commit_end_edge(&finish_end, w1b, finish_split.as_ref().map_or(w2b, |split| split.q1_vertex))?;
2061
2062    // Replace the blended edge in each PRISTINE mate's loop — the blend
2063    // face's loop direction is forced by manifold pairing with F1's use of
2064    // the blended edge (`first_use_forward`, captured above).  A sewn mate is
2065    // dropped whole below; nothing to splice.  A COLLAPSED side has no rail to
2066    // put there: the mate simply loses the blended edge, and its loop closes
2067    // through the rim vertices the orchestrator identifies.
2068    for (mate, rail, sewn) in [
2069        (first, cr_edge_id.zip(cr_rail.as_ref()), sew_first.is_some()),
2070        (second, cs_edge_id.zip(cs_rail.as_ref()), sew_second.is_some()),
2071    ] {
2072        if sewn {
2073            continue;
2074        }
2075        let face = result
2076            .shells
2077            .iter_mut()
2078            .flat_map(|shell| &mut shell.faces)
2079            .find(|face| face.id == mate.face.id)
2080            .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during surgery"))?;
2081        let loop_record = &mut face.loops[mate.loop_index];
2082        let position = loop_record
2083            .coedges
2084            .iter()
2085            .position(|coedge| coedge.edge_id == edge.id)
2086            .ok_or(KernelRefusal::internal(KernelStage::Sew, "edge_coedge", "blend: edge coedge lost during surgery"))?;
2087        let Some((new_edge_id, (_, pcurve_forward))) = rail else {
2088            loop_record.coedges.remove(position);
2089            continue;
2090        };
2091        let old_forward = loop_record.coedges[position].forward;
2092        loop_record.coedges[position] = CoedgeRecord {
2093            id: loop_record.coedges[position].id,
2094            edge_id: new_edge_id,
2095            forward: old_forward,
2096            pcurve: if old_forward {
2097                pcurve_forward.clone()
2098            } else {
2099                pcurve_forward.reversed().or_refuse(KernelStage::Refine, "reversed")?
2100            },
2101        };
2102    }
2103
2104    // A capped end's legs: on each mate, the leg runs from the rail's rim
2105    // vertex to the sharp vertex, where the continuing edge still starts.
2106    // It goes between the rail coedge and that continuing coedge, with the
2107    // sense that walks rim -> vertex when the rail ends at the rim.
2108    for (plan, at_start) in [(&start_end, true), (&finish_end, false)] {
2109        let EndPlan::Cap(cap) = plan else {
2110            continue;
2111        };
2112        for (mate, rail_edge_id, leg, rim) in [
2113            (first, cr_edge_id, &cap.first_leg, if at_start { w1a } else { w1b }),
2114            (second, cs_edge_id, &cap.second_leg, if at_start { w2a } else { w2b }),
2115        ] {
2116            // Refused above: a capped end never meets a collapsed rail.
2117            let rail_edge_id = rail_edge_id.ok_or(KernelRefusal::internal(KernelStage::Sew, "end_rail", "blend: a capped end lost its rail"))?;
2118            let face = result
2119                .shells
2120                .iter_mut()
2121                .flat_map(|shell| &mut shell.faces)
2122                .find(|face| face.id == mate.face.id)
2123                .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during cap splice"))?;
2124            let loop_record = &mut face.loops[mate.loop_index];
2125            let count = loop_record.coedges.len();
2126            let rail_at = loop_record
2127                .coedges
2128                .iter()
2129                .position(|coedge| coedge.edge_id == rail_edge_id)
2130                .ok_or(KernelRefusal::internal(KernelStage::Sew, "rail_coedge", "blend: rail coedge lost during cap splice"))?;
2131            // Which side of the rail coedge is this end?  The rail coedge
2132            // traverses rim-to-rim; the capped end is at its traversal END
2133            // when walking forward means station order and this is the
2134            // finish end, etc.  Decide by geometry: the neighbour whose
2135            // traversal touches the sharp vertex.
2136            let rail_forward = loop_record.coedges[rail_at].forward;
2137            let end_is_traversal_end = if rail_forward { !at_start } else { at_start };
2138            let (insert_at, forward, pcurve) = if end_is_traversal_end {
2139                // rail ... rim -> [leg rim->vertex] -> continuing edge
2140                (rail_at + 1, true, leg.1.clone())
2141            } else {
2142                // continuing edge -> [leg vertex->rim] -> rim ... rail
2143                (rail_at, false, leg.1.reversed().or_refuse(KernelStage::Refine, "reversed")?)
2144            };
2145            let _ = (count, rim);
2146            loop_record.coedges.insert(
2147                insert_at,
2148                CoedgeRecord {
2149                    id: take_id(),
2150                    edge_id: leg.0,
2151                    forward,
2152                    pcurve,
2153                },
2154            );
2155        }
2156    }
2157
2158    // Drop consumed boundary edges from the mate loop they share with the
2159    // blended edge: the fresh support coedge already begins at the reused far
2160    // vertex, so removing the fully-covered boundary keeps the loop closed.
2161    // A SEWN mate's whole loop collapses (the face is dropped below), so its
2162    // consumed boundaries are only recorded for deletion, never spliced.
2163    let mut consumed_edges: Vec<u64> = Vec::new();
2164    let start_free = start_end.free();
2165    let finish_free = finish_end.free();
2166    for (mate, sewn, sides) in [
2167        (
2168            first,
2169            sew_first.is_some(),
2170            [
2171                (&start_first, start_free.map(|free| free.first_edge_id)),
2172                (&finish_first, finish_free.map(|free| free.first_edge_id)),
2173            ],
2174        ),
2175        (
2176            second,
2177            sew_second.is_some(),
2178            [
2179                (&start_second, start_free.map(|free| free.second_edge_id)),
2180                (&finish_second, finish_free.map(|free| free.second_edge_id)),
2181            ],
2182        ),
2183    ] {
2184        for (cross, boundary_id) in sides {
2185            if !cross.is_consumed() {
2186                continue;
2187            }
2188            let Some(boundary_id) = boundary_id else {
2189                continue;
2190            };
2191            if !sewn {
2192                let face = result
2193                    .shells
2194                    .iter_mut()
2195                    .flat_map(|shell| &mut shell.faces)
2196                    .find(|face| face.id == mate.face.id)
2197                    .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during surgery"))?;
2198                face.loops[mate.loop_index]
2199                    .coedges
2200                    .retain(|coedge| coedge.edge_id != boundary_id);
2201            }
2202            if !consumed_edges.contains(&boundary_id) {
2203                consumed_edges.push(boundary_id);
2204            }
2205        }
2206    }
2207    // Lesson 7: zero-span leftovers of a collapsing loop go with their face.
2208    for sew in [&sew_first, &sew_second].into_iter().flatten() {
2209        for id in &sew.collapsed_edges {
2210            if !consumed_edges.contains(id) {
2211                consumed_edges.push(*id);
2212            }
2213        }
2214    }
2215
2216    // Locate the corner junction on each end face BEFORE trimming (the two
2217    // boundary coedges that meet at the old corner vertex, stepping over the
2218    // pole between them where the end face's apex IS that vertex) — edge ids
2219    // alone are ambiguous on two-coedge cap loops, so the meeting must be at
2220    // the corner.
2221    // (end, transverse_id, corner, first_consumed, second_consumed) -> plan.
2222    // Only FREE ends appear here: a corner stop rebuilds nothing on a third
2223    // face, because the corner patch is what closes it.
2224    let mut end_plans = Vec::with_capacity(2);
2225    for (end, transverse_id, corner, first_consumed, second_consumed) in [
2226        (
2227            start_end.free(),
2228            transverse_a_id,
2229            old_start,
2230            start_first.is_consumed(),
2231            start_second.is_consumed(),
2232        ),
2233        (
2234            finish_end.free(),
2235            transverse_b_id,
2236            old_finish,
2237            finish_first.is_consumed(),
2238            finish_second.is_consumed(),
2239        ),
2240    ] {
2241        let (Some(end), Some(transverse_id)) = (end, transverse_id) else {
2242            continue;
2243        };
2244        if end.split.is_some() {
2245            continue;
2246        }
2247        let face = result
2248            .shells
2249            .iter()
2250            .flat_map(|shell| &shell.faces)
2251            .find(|face| face.id == end.end_face_id)
2252            .ok_or(KernelRefusal::internal(KernelStage::Sew, "end_face", "blend: end face lost during surgery"))?;
2253        // Key on stable coedge ids (not indices) so processing one end can't
2254        // invalidate another that shares this face.
2255        let Some(located) = locate_end_corner(
2256            &result,
2257            face,
2258            corner,
2259            end.first_edge_id,
2260            end.second_edge_id,
2261        ) else {
2262            return Err(KernelRefusal::internal(KernelStage::Sew, "end_face_corner", "blend: end-face corner (adjacent boundary coedges) not found"));
2263        };
2264        // The apex the transverse curve cuts off goes with the boundaries the
2265        // blend consumes.
2266        for pole in &located.pole_edge_ids {
2267            if !consumed_edges.contains(pole) {
2268                consumed_edges.push(*pole);
2269            }
2270        }
2271        end_plans.push((
2272            end.end_face_id,
2273            transverse_id,
2274            end.transverse_end_pcurve.clone(),
2275            located,
2276            first_consumed,
2277            second_consumed,
2278        ));
2279    }
2280
2281    let split_corners = |end: Option<&EndSurgery>, corner: u64, result: &BrepSolid| -> Result<Option<[super::support::EndCorner; 2]>, KernelRefusal> {
2282        match end.and_then(|end| end.split.as_ref().map(|split| (end, split))) {
2283            Some((end, split)) => super::split_floor::locate_split_corners(result, end, split, corner).map(Some),
2284            None => Ok(None),
2285        }
2286    };
2287    let start_split_corners = split_corners(start_free, old_start, result)?;
2288    let finish_split_corners = split_corners(finish_free, old_finish, result)?;
2289    if (start_split_corners.is_some() && (start_first.is_consumed() || start_second.is_consumed()))
2290        || (finish_split_corners.is_some() && (finish_first.is_consumed() || finish_second.is_consumed()))
2291    {
2292        return Err(KernelRefusal::unsupported(KernelStage::Sew, "split_floor_consumed", "blend: a two-face end whose rail consumes its boundary"));
2293    }
2294
2295    // Trim the boundary edges at their support crossings.  A consumed side is
2296    // deleted instead of trimmed; a CORNER side touches no boundary at all.
2297    for (rim_resolution, boundary, corner, rim) in [
2298        (
2299            &start_first,
2300            start_free.map(|free| (free.first_edge_id, free.first_edge_parameter)),
2301            old_start,
2302            w1a,
2303        ),
2304        (
2305            &start_second,
2306            start_free.map(|free| (free.second_edge_id, free.second_edge_parameter)),
2307            old_start,
2308            w2a,
2309        ),
2310        (
2311            &finish_first,
2312            finish_free.map(|free| (free.first_edge_id, free.first_edge_parameter)),
2313            old_finish,
2314            w1b,
2315        ),
2316        (
2317            &finish_second,
2318            finish_free.map(|free| (free.second_edge_id, free.second_edge_parameter)),
2319            old_finish,
2320            w2b,
2321        ),
2322    ] {
2323        if !rim_resolution.trims_boundary() {
2324            continue;
2325        }
2326        let Some((boundary_id, boundary_param)) = boundary else {
2327            continue;
2328        };
2329        trim_edge_at(result, boundary_id, boundary_param, corner, rim)?;
2330    }
2331
2332    // Rebuild each end face's corner: drop the consumed boundary coedge(s) and
2333    // splice in the transverse coedge between the (trimmed) boundaries.
2334    for (end_face, transverse_id, transverse_end_pcurve, located, first_consumed, second_consumed) in
2335        end_plans
2336    {
2337        let forward = located.x_is_first;
2338        let pcurve = if forward {
2339            transverse_end_pcurve
2340        } else {
2341            transverse_end_pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?
2342        };
2343        let (x_consumed, y_consumed) = if located.x_is_first {
2344            (first_consumed, second_consumed)
2345        } else {
2346            (second_consumed, first_consumed)
2347        };
2348        let transverse_coedge = CoedgeRecord {
2349            id: take_id(),
2350            edge_id: transverse_id,
2351            forward,
2352            pcurve,
2353        };
2354        splice_end_corner(
2355            result,
2356            end_face,
2357            &located,
2358            transverse_coedge,
2359            x_consumed,
2360            y_consumed,
2361        )?;
2362    }
2363
2364    // Blend face: cr fwd -> TB -> cs rev -> TA rev in (t, z) space.  Both rows
2365    // share one parameterisation, so a collapsed cr reads its sense across the
2366    // strip the cs rail still spans (a stripe with BOTH rails collapsed has no
2367    // area; the orchestrator drops it with the edges that bound it).
2368    let (mid_u, station_uv) = match (&cr_rail, &cs_rail) {
2369        (Some((_, cr_pcurve)), _) => {
2370            let mid_u = (cr_domain[0] + cr_domain[1]) * 0.5;
2371            (mid_u, cr_pcurve.evaluate(mid_u).or_refuse(KernelStage::Refine, "evaluate")?)
2372        }
2373        (None, Some(_)) => {
2374            let mid_u = (cs_domain[0] + cs_domain[1]) * 0.5;
2375            (mid_u, rows.cr_pcurve.evaluate(mid_u).or_refuse(KernelStage::Refine, "evaluate")?)
2376        }
2377        (None, None) => (cr_domain[0], rows.cr_pcurve.evaluate(cr_domain[0]).or_refuse(KernelStage::Refine, "evaluate")?),
2378    };
2379    let blend_normal = raw_normal(&rows.surface, mid_u, 0.0)?;
2380    let n1 = raw_normal(&first.face.surface, station_uv.x, station_uv.y)?;
2381    let out1 = if first.face.same_sense {
2382        n1
2383    } else {
2384        n1.scale(-1.0)
2385    };
2386    let same_sense = blend_normal.dot(out1) >= 0.0;
2387    let loop_id = take_id();
2388    // Traversal senses of the blend's support coedges.  A fresh support edge
2389    // is parameterized in station order, so the sense is the loop's walking
2390    // direction (`blend_cr_forward` for cr, its opposite for cs); a SEWN
2391    // side's sense comes from the detection (the existing edge's own
2392    // parameter direction relative to that same walk — equal to the dropped
2393    // face's old sense, preserving manifold pairing with the survivor).  The
2394    // pcurves always follow the LOOP's walking direction and are unchanged.
2395    let cr_forward = sew_first
2396        .as_ref()
2397        .map_or(blend_cr_forward, |sew| sew.forward);
2398    let cs_forward = sew_second
2399        .as_ref()
2400        .map_or(!blend_cr_forward, |sew| sew.forward);
2401    // The two end slots of the blend loop.  `natural_forward` is the sense the
2402    // loop walks a transverse edge stored first-rim -> second-rim; a CORNER
2403    // arc was already committed in the walk direction (so the corner patch can
2404    // take it the other way round), so it is always used forward.
2405    // A slot is one coedge for a free end (the transverse curve) or a corner
2406    // end (the section arc), and one or two for a miter end (the seam, then
2407    // the sibling's section when the seam left the sibling first).  A corner
2408    // arc was committed in the walk direction; a miter edge records its own
2409    // sense along the walk.
2410    let mut end_slot = |plan: &EndPlan,
2411                        free_edge_id: Option<u64>,
2412                        natural_forward: bool|
2413     -> Result<Vec<CoedgeRecord>, KernelRefusal> {
2414        match plan {
2415            EndPlan::Corner(end) => Ok(vec![CoedgeRecord {
2416                id: take_id(),
2417                edge_id: end.arc_edge_id,
2418                forward: true,
2419                pcurve: end.arc_blend_pcurve.clone(),
2420            }]),
2421            EndPlan::Cap(end) => Ok(vec![CoedgeRecord {
2422                id: take_id(),
2423                edge_id: end.arc_edge_id,
2424                forward: true,
2425                pcurve: end.arc_blend_pcurve.clone(),
2426            }]),
2427            EndPlan::Miter(end) => end
2428                .edges
2429                .iter()
2430                .map(|(edge_id, forward, pcurve)| {
2431                    Ok(CoedgeRecord {
2432                        id: take_id(),
2433                        edge_id: *edge_id,
2434                        forward: *forward,
2435                        pcurve: pcurve.clone(),
2436                    })
2437                })
2438                .collect(),
2439            EndPlan::Free(free) => {
2440                let edge_id =
2441                    free_edge_id.ok_or(KernelRefusal::internal(KernelStage::Sew, "transverse_edge", "blend: free end without its transverse edge"))?;
2442                Ok(vec![if natural_forward {
2443                    CoedgeRecord {
2444                        id: take_id(),
2445                        edge_id,
2446                        forward: true,
2447                        pcurve: free.transverse_blend_pcurve.clone(),
2448                    }
2449                } else {
2450                    CoedgeRecord {
2451                        id: take_id(),
2452                        edge_id,
2453                        forward: false,
2454                        pcurve: free.transverse_blend_pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?,
2455                    }
2456                }])
2457            }
2458        }
2459    };
2460    let start_slot = end_slot(&start_end, transverse_a_id, !blend_cr_forward)?;
2461    let finish_slot = end_slot(&finish_end, transverse_b_id, blend_cr_forward)?;
2462    let start_slot = match (start_free, &start_split, transverse_a_id) {
2463        (Some(end), Some(commit), Some(id)) => super::split_floor::split_slot(end, end.split.as_ref().expect("planned"), commit, id, !blend_cr_forward, &mut *take_id)?,
2464        _ => start_slot,
2465    };
2466    let finish_slot = match (finish_free, &finish_split, transverse_b_id) {
2467        (Some(end), Some(commit), Some(id)) => super::split_floor::split_slot(end, end.split.as_ref().expect("planned"), commit, id, blend_cr_forward, &mut *take_id)?,
2468        _ => finish_slot,
2469    };
2470    for (end, commit, id, corners, corner, forward) in [
2471        (start_free, &start_split, transverse_a_id, &start_split_corners, old_start, !blend_cr_forward),
2472        (finish_free, &finish_split, transverse_b_id, &finish_split_corners, old_finish, blend_cr_forward),
2473    ] {
2474        if let (Some(end), Some(commit), Some(id), Some(corners)) = (end, commit, id, corners) {
2475            super::split_floor::finish_split_end(result, &mut *take_id, end, end.split.as_ref().expect("planned"), commit, id, corners, corner, forward, name)?;
2476        }
2477    }
2478    // A collapsed rail has no coedge: the end slots on either side of it meet
2479    // at its one rim point.
2480    let coedges = if blend_cr_forward {
2481        let mut coedges = Vec::new();
2482        if let Some(cr_edge_id) = cr_edge_id {
2483            coedges.push(CoedgeRecord {
2484                id: take_id(),
2485                edge_id: cr_edge_id,
2486                forward: cr_forward,
2487                pcurve: crate::sweep_topology::parameter_line(
2488                    cr_domain[0],
2489                    0.0,
2490                    cr_domain[1],
2491                    0.0,
2492                ).or_refuse(KernelStage::Refine, "parameter_line")?,
2493            });
2494        }
2495        coedges.extend(finish_slot);
2496        if let Some(cs_edge_id) = cs_edge_id {
2497            coedges.push(CoedgeRecord {
2498                id: take_id(),
2499                edge_id: cs_edge_id,
2500                forward: cs_forward,
2501                pcurve: cs_blend_pcurve_reversed(&cs_domain)?,
2502            });
2503        }
2504        coedges.extend(start_slot);
2505        coedges
2506    } else {
2507        let mut coedges = Vec::new();
2508        if let Some(cr_edge_id) = cr_edge_id {
2509            coedges.push(CoedgeRecord {
2510                id: take_id(),
2511                edge_id: cr_edge_id,
2512                forward: cr_forward,
2513                pcurve: crate::sweep_topology::parameter_line(
2514                    cr_domain[1],
2515                    0.0,
2516                    cr_domain[0],
2517                    0.0,
2518                ).or_refuse(KernelStage::Refine, "parameter_line")?,
2519            });
2520        }
2521        coedges.extend(start_slot);
2522        if let Some(cs_edge_id) = cs_edge_id {
2523            coedges.push(CoedgeRecord {
2524                id: take_id(),
2525                edge_id: cs_edge_id,
2526                forward: cs_forward,
2527                pcurve: crate::sweep_topology::parameter_line(
2528                    cs_domain[0],
2529                    1.0,
2530                    cs_domain[1],
2531                    1.0,
2532                ).or_refuse(KernelStage::Refine, "parameter_line")?,
2533            });
2534        }
2535        coedges.extend(finish_slot);
2536        coedges
2537    };
2538    let blend_face_id = take_id();
2539    let mut blend_face = FaceRecord {
2540        id: blend_face_id,
2541        surface: rows.surface,
2542        same_sense,
2543        loops: vec![LoopRecord {
2544            id: loop_id,
2545            coedges,
2546        }],
2547        name: name.map(|value| value.to_string()),
2548    };
2549    if rows.exact_extrusion {
2550        transpose_face(&mut blend_face)?;
2551    }
2552    let shell_index = result
2553        .shells
2554        .iter()
2555        .position(|shell| shell.faces.iter().any(|face| face.id == first.face.id))
2556        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_shell", "blend: mate shell lost during surgery"))?;
2557    // Drop the fully-consumed mate faces (lesson 3): their loops collapsed
2558    // between the sewn edge and the blend; the consumed boundaries and
2559    // lesson-7 leftovers are deleted below, the sewn edge lives on shared by
2560    // the blend face and the surviving neighbour.
2561    for (mate, sew) in [(first, &sew_first), (second, &sew_second)] {
2562        if sew.is_some() {
2563            for shell in &mut result.shells {
2564                shell.faces.retain(|face| face.id != mate.face.id);
2565            }
2566        }
2567    }
2568    result.shells[shell_index].faces.push(blend_face);
2569
2570    result.edges.retain(|candidate| candidate.id != edge.id);
2571    // Delete the boundary edges a prior fillet's corner had left behind that
2572    // this blend fully consumed.
2573    result
2574        .edges
2575        .retain(|candidate| !consumed_edges.contains(&candidate.id));
2576    // Each collapsed rail's two rims are one vertex.
2577    let mut identified = Vec::new();
2578    for (collapsed, from, to) in [(cr_collapsed, w1a, w1b), (cs_collapsed, w2a, w2b)] {
2579        if collapsed && from != to {
2580            identified.push((from, to));
2581        }
2582    }
2583    // The stopped-end rollover's sides: the rail past the crossing and the
2584    // cap's leg chain move onto the neighbours, and the end footprint is
2585    // re-traced on every face it touches.
2586    let mut cr_edge_id = cr_edge_id;
2587    let mut cs_edge_id = cs_edge_id;
2588    if tail.iter().any(Option::is_some) {
2589        let EndPlan::Cap(cap) = &finish_end else {
2590            return Err(KernelRefusal::unsupported(KernelStage::Sew, "stopped_end_rollover", "blend stopped-end rollover: the rolled stripe's finish end is not a cap, which is the only end this lane closes on the neighbours"));
2591        };
2592        let mut footprint = StoppedEndFootprint::default();
2593        // The cap plane at the finish vertex: through the sharp vertex, normal
2594        // the edge's tangent there; the fillet lies on the -tangent side.
2595        {
2596            let sharp = result.vertices.iter().find(|vertex| vertex.id == cap.sharp_vertex).map(|vertex| vertex.point)
2597                .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, "stopped_end_rollover", "blend stopped-end rollover: the sharp vertex vanished"))?;
2598            let d = edge.curve.derivatives(edge.t1, 1).or_refuse(KernelStage::Refine, "derivatives")?;
2599            footprint.plane = (sharp, d[1].normalized().or_refuse(KernelStage::Refine, "normalized")?);
2600            footprint.sharp_vertex = cap.sharp_vertex;
2601        }
2602        for (side, splice) in tail.into_iter().enumerate() {
2603            let Some(splice) = splice else { continue };
2604            let (mate, rail_edge_id, rim, sewn) = if side == 0 {
2605                (first, cr_edge_id, w1b, sew_first.is_some())
2606            } else {
2607                (second, cs_edge_id, w2b, sew_second.is_some())
2608            };
2609            let Some(rail_edge_id) = rail_edge_id.filter(|_| !sewn) else {
2610                return Err(KernelRefusal::unsupported(KernelStage::Sew, "stopped_end_rollover", "blend stopped-end rollover: a rolled side's rail collapsed or sewed onto an existing edge, which this lane does not split"));
2611            };
2612            let part_on_mate = roll_side_footprint(result, take_id, mate, &splice, rail_edge_id, rim, cap.sharp_vertex, &mut footprint)?;
2613            if side == 0 { cr_edge_id = Some(part_on_mate); } else { cs_edge_id = Some(part_on_mate); }
2614        }
2615        retrace_stopped_end_footprint(result, take_id, footprint)?;
2616    }
2617    Ok(SewnStripe {
2618        cr_edge_id,
2619        cs_edge_id,
2620        blend_face_id,
2621        consumed: [sew_first.is_some(), sew_second.is_some()],
2622        snap,
2623        identified,
2624    })
2625}
2626
2627/// A stopped-end rollover's footprint on the solid, gathered side by side
2628/// and re-traced once ([`retrace_stopped_end_footprint`]).
2629#[derive(Default)]
2630struct StoppedEndFootprint {
2631    /// The new boundary of the footprint, per face: (face, edge, from, to,
2632    /// pcurve from -> to on that face).
2633    pieces: Vec<(u64, u64, u64, u64, NurbsCurve)>,
2634    /// The faces whose loops change: the mates and every face a piece lies on.
2635    faces: Vec<u64>,
2636    /// The cap plane: (sharp point, unit edge tangent at the vertex). The
2637    /// fillet lies on the side opposite the tangent.
2638    plane: (Vec3, Vec3),
2639    sharp_vertex: u64,
2640}
2641
2642/// One rolled side, after the pristine sewing: the rail is split at the
2643/// crossing vertex (on the crossed tangent edge) and the tangent edge there;
2644/// the pristine splice's rail far part and first leg piece leave the mate's
2645/// loop (they belong to the neighbours), and the footprint's new boundary on
2646/// the neighbours — the far part with its pcurve on the neighbour by
2647/// projection, and the cap's leg chain — is recorded for the re-trace.
2648/// Returns the rail part left on the mate.
2649#[allow(clippy::too_many_arguments)]
2650fn roll_side_footprint(
2651    result: &mut BrepSolid,
2652    take_id: &mut dyn FnMut() -> u64,
2653    mate: &BlendMate,
2654    splice: &crate::blend::rollover::TailSplice<'_>,
2655    rail_edge_id: u64,
2656    rim_vertex: u64,
2657    sharp_vertex: u64,
2658    footprint: &mut StoppedEndFootprint,
2659) -> Result<u64, KernelRefusal> {
2660    let what = "stopped_end_rollover";
2661    let not_built = |message: String| KernelRefusal::unsupported(KernelStage::Sew, what, format!("blend stopped-end rollover: {message}"));
2662    let _ = sharp_vertex;
2663    let rolled = splice.rolled;
2664    let crossing_vertex = take_id();
2665    result.vertices.push(VertexRecord { id: crossing_vertex, point: rolled.point });
2666    let rail_parts = crate::blend::rollover_surgery::split_edge_at_vertices(result, rail_edge_id, &[(crossing_vertex, rolled.point)], take_id)?;
2667    let [rail_near, rail_far] = [rail_parts[0], rail_parts[1]];
2668    let rail_far_edge = result.edges.iter().find(|edge| edge.id == rail_far).cloned()
2669        .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: the rail's far part vanished"))?;
2670    if rail_far_edge.end_vertex_id != rim_vertex {
2671        return Err(not_built(format!("the rail's far part ends at vertex {} rather than the finish rim {rim_vertex}", rail_far_edge.end_vertex_id)));
2672    }
2673    // The crossed tangent edge, or the part of it the cap's leg chain left
2674    // holding the crossing (the chain may have split it already).
2675    let holds_crossing = |result: &BrepSolid, id: u64| -> Result<bool, KernelRefusal> {
2676        let Some(edge) = result.edges.iter().find(|edge| edge.id == id) else { return Ok(false) };
2677        let foot = crate::project_point_to_curve(&edge.curve, rolled.point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
2678        Ok(foot.distance <= 1e-6 && foot.u > edge.t0.min(edge.t1) && foot.u < edge.t0.max(edge.t1))
2679    };
2680    let crossed = if result.edges.iter().any(|edge| edge.id == rolled.edge_id) {
2681        rolled.edge_id
2682    } else {
2683        let candidates: Vec<u64> = result.edges.iter().map(|edge| edge.id).collect();
2684        let mut found = None;
2685        for id in candidates {
2686            if holds_crossing(result, id)? {
2687                found = Some(id);
2688                break;
2689            }
2690        }
2691        found.ok_or_else(|| not_built(format!("no part of tangent edge {} holds the crossing any more", rolled.edge_id)))?
2692    };
2693    crate::blend::rollover_surgery::split_edge_at_vertices(result, crossed, &[(crossing_vertex, rolled.point)], take_id)?;
2694    // The neighbour's pcurve of the rail's far part, by projection.
2695    let neighbour_surface = result
2696        .shells
2697        .iter()
2698        .flat_map(|shell| &shell.faces)
2699        .find(|face| face.id == rolled.neighbour_face_id)
2700        .map(|face| face.surface.clone())
2701        .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: the neighbour face vanished"))?;
2702    let far_pcurve = {
2703        const SAMPLES: usize = 24;
2704        let [t0, t1] = [rail_far_edge.t0, rail_far_edge.t1];
2705        let mut uvs = Vec::with_capacity(SAMPLES + 1);
2706        let mut ts = Vec::with_capacity(SAMPLES + 1);
2707        for k in 0..=SAMPLES {
2708            let t = t0 + (t1 - t0) * k as f64 / SAMPLES as f64;
2709            let point = rail_far_edge.curve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
2710            let projection = crate::project_point_to_surface(&neighbour_surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
2711            uvs.push(Vec3::new(projection.u, projection.v, 0.0));
2712            ts.push(t);
2713        }
2714        // Clamped over the rail part's own parameter interval (the edge's).
2715        crate::fit::interpolate_curve(&uvs, 3, &ts).or_refuse(KernelStage::Refine, "interpolate_curve")?
2716    };
2717    // The pristine splice's artefacts leave the mate's loop.
2718    let leg_edge_id = splice.legs.first().map(|piece| piece.edge_id)
2719        .ok_or_else(|| not_built("a rolled side has no cap leg".to_string()))?;
2720    let mate_face = result
2721        .shells
2722        .iter_mut()
2723        .flat_map(|shell| shell.faces.iter_mut())
2724        .find(|face| face.id == mate.face.id)
2725        .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: the mate face vanished"))?;
2726    mate_face.loops[mate.loop_index].coedges.retain(|coedge| coedge.edge_id != rail_far && coedge.edge_id != leg_edge_id);
2727    footprint.pieces.push((rolled.neighbour_face_id, rail_far, crossing_vertex, rim_vertex, far_pcurve));
2728    for piece in &splice.legs {
2729        footprint.pieces.push((piece.face_id, piece.edge_id, piece.from, piece.to, piece.pcurve.clone()));
2730    }
2731    for face_id in [mate.face.id, rolled.neighbour_face_id].into_iter().chain(splice.legs.iter().map(|piece| piece.face_id)) {
2732        if !footprint.faces.contains(&face_id) {
2733            footprint.faces.push(face_id);
2734        }
2735    }
2736    Ok(rail_near)
2737}
2738
2739/// Re-trace the footprint: an existing edge of an affected face whose both
2740/// ends lie on the footprint's new boundary and whose midpoint lies on the
2741/// fillet's side of the cap plane is INTERIOR to the footprint and deleted
2742/// (F10: edge 46 between the crossing and the cap leg's exit, edge 68
2743/// between its crossing and vertex 34); then every affected loop is traced
2744/// afresh through its remaining coedges and the new pieces — each vertex
2745/// of the new boundary has exactly one way on — the first closed trace
2746/// keeping the loop, every further one its own face on the same carrier
2747/// (F10: face 13's triangle beyond the cap plane).
2748fn retrace_stopped_end_footprint(
2749    result: &mut BrepSolid,
2750    take_id: &mut dyn FnMut() -> u64,
2751    footprint: StoppedEndFootprint,
2752) -> Result<(), KernelRefusal> {
2753    let what = "stopped_end_rollover";
2754    let not_built = |message: String| KernelRefusal::unsupported(KernelStage::Sew, what, format!("blend stopped-end rollover: {message}"));
2755    let (sharp_point, tangent) = footprint.plane;
2756    let mut boundary_vertices: Vec<u64> = vec![footprint.sharp_vertex];
2757    for (_, _, from, to, _) in &footprint.pieces {
2758        for vertex in [*from, *to] {
2759            if !boundary_vertices.contains(&vertex) {
2760                boundary_vertices.push(vertex);
2761            }
2762        }
2763    }
2764    let piece_edges: Vec<u64> = footprint.pieces.iter().map(|piece| piece.1).collect();
2765    // Interior edges, among those on the affected faces.
2766    let mut interior: Vec<u64> = Vec::new();
2767    for face in result.shells.iter().flat_map(|shell| &shell.faces).filter(|face| footprint.faces.contains(&face.id)) {
2768        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
2769            let Some(edge) = result.edges.iter().find(|edge| edge.id == coedge.edge_id) else { continue };
2770            if piece_edges.contains(&edge.id) || interior.contains(&edge.id) {
2771                continue;
2772            }
2773            if !(boundary_vertices.contains(&edge.start_vertex_id) && boundary_vertices.contains(&edge.end_vertex_id)) {
2774                continue;
2775            }
2776            let mid = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(KernelStage::Refine, "evaluate")?;
2777            if mid.sub(sharp_point).dot(tangent) < 0.0 {
2778                interior.push(edge.id);
2779            }
2780        }
2781    }
2782    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
2783        eprintln!("stopped-end rollover: footprint faces {:?}, interior edges {:?}, boundary vertices {:?}", footprint.faces, interior, boundary_vertices);
2784    }
2785    let edge_ends: std::collections::HashMap<u64, (u64, u64)> = result.edges.iter().map(|edge| (edge.id, (edge.start_vertex_id, edge.end_vertex_id))).collect();
2786    let mut new_faces: Vec<FaceRecord> = Vec::new();
2787    // Face names the result uses (the app keys faces by name; this model
2788    // already carries `_1` splits of its own): a remnant takes a free suffix.
2789    let mut taken: Vec<String> = result.shells.iter().flat_map(|shell| &shell.faces).filter_map(|face| face.name.clone()).collect();
2790    for face_id in footprint.faces.clone() {
2791        let face = result
2792            .shells
2793            .iter_mut()
2794            .flat_map(|shell| shell.faces.iter_mut())
2795            .find(|face| face.id == face_id)
2796            .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, format!("blend stopped-end rollover: face {face_id} vanished")))?;
2797        let pieces: Vec<&(u64, u64, u64, u64, NurbsCurve)> = footprint.pieces.iter().filter(|piece| piece.0 == face_id).collect();
2798        let mut rebuilt_loops: Vec<LoopRecord> = Vec::new();
2799        for loop_record in &face.loops {
2800            let touched = loop_record.coedges.iter().any(|coedge| interior.contains(&coedge.edge_id))
2801                || loop_record.coedges.iter().any(|coedge| {
2802                    edge_ends.get(&coedge.edge_id).is_some_and(|(a, b)| boundary_vertices.contains(a) || boundary_vertices.contains(b))
2803                });
2804            if !touched {
2805                rebuilt_loops.push(loop_record.clone());
2806                continue;
2807            }
2808            // Directed remaining coedges (direction fixed, with their place in
2809            // the old loop) and undirected pieces.
2810            let n = loop_record.coedges.len();
2811            let mut remaining: Vec<(CoedgeRecord, u64, u64, usize)> = Vec::new();
2812            for (index, coedge) in loop_record.coedges.iter().enumerate() {
2813                if interior.contains(&coedge.edge_id) {
2814                    continue;
2815                }
2816                let (start, end) = edge_ends.get(&coedge.edge_id).copied()
2817                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, format!("blend stopped-end rollover: coedge {} names a missing edge {}", coedge.id, coedge.edge_id)))?;
2818                let (from, to) = if coedge.forward { (start, end) } else { (end, start) };
2819                remaining.push((coedge.clone(), from, to, index));
2820            }
2821            let mut loose: Vec<&(u64, u64, u64, u64, NurbsCurve)> = pieces.clone();
2822            // Trace closed walks: start at a remaining coedge, follow the
2823            // continuation at each vertex — the old loop's own successor when
2824            // it is there (a periodic face's loop passes its seam vertex
2825            // twice), else the unique way on.
2826            while !remaining.is_empty() {
2827                // Start on a coedge that is not a degenerate self-loop (a
2828                // periodic face's pole edge runs from a vertex to itself).
2829                let start_at = remaining.iter().position(|(_, from, to, _)| from != to).unwrap_or(0);
2830                let (first, from0, to0, index0) = remaining.remove(start_at);
2831                let mut walk: Vec<CoedgeRecord> = vec![first];
2832                let mut at = to0;
2833                let mut previous = index0;
2834                let mut guard = 0usize;
2835                loop {
2836                    guard += 1;
2837                    if guard > 4096 {
2838                        return Err(not_built(format!("face {face_id}: the re-trace does not close")));
2839                    }
2840                    let mut next_remaining: Vec<usize> = remaining.iter().enumerate().filter(|(_, (_, from, _, _))| *from == at).map(|(k, _)| k).collect();
2841                    let successor_is_start = (previous + 1) % n == index0;
2842                    if at == from0 && (successor_is_start || next_remaining.is_empty()) {
2843                        // Back at the start along the old loop's own order (a
2844                        // seam vertex passed twice does not close it early).
2845                        if at == from0 && successor_is_start {
2846                            break;
2847                        }
2848                        if loose.iter().all(|piece| piece.2 != at && piece.3 != at) {
2849                            break;
2850                        }
2851                    }
2852                    if next_remaining.len() > 1 {
2853                        if let Some(k) = next_remaining.iter().copied().find(|k| remaining[*k].3 == (previous + 1) % n) {
2854                            next_remaining = vec![k];
2855                        }
2856                    }
2857                    let next_pieces: Vec<usize> = loose.iter().enumerate().filter(|(_, piece)| piece.2 == at || piece.3 == at).map(|(k, _)| k).collect();
2858                    match (next_remaining.len(), next_pieces.len()) {
2859                        (1, 0) => {
2860                            let (coedge, _, to, index) = remaining.remove(next_remaining[0]);
2861                            walk.push(coedge);
2862                            at = to;
2863                            previous = index;
2864                        }
2865                        (0, 1) => {
2866                            let piece = loose.remove(next_pieces[0]);
2867                            let (edge_id, from, to, pcurve) = (piece.1, piece.2, piece.3, &piece.4);
2868                            let (start, _) = edge_ends.get(&edge_id).copied()
2869                                .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, format!("blend stopped-end rollover: footprint edge {edge_id} missing")))?;
2870                            let along = from == at;
2871                            let coedge_forward = if along { start == from } else { start == to };
2872                            walk.push(CoedgeRecord {
2873                                id: take_id(),
2874                                edge_id,
2875                                forward: coedge_forward,
2876                                pcurve: if along { pcurve.clone() } else { pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2877                            });
2878                            at = if along { to } else { from };
2879                        }
2880                        (r, p) => {
2881                            return Err(not_built(format!("face {face_id}: vertex {at} has {} ways on ({r} boundary, {p} new), not one", r + p)));
2882                        }
2883                    }
2884                }
2885                rebuilt_loops.push(LoopRecord { id: if rebuilt_loops.is_empty() { loop_record.id } else { take_id() }, coedges: walk });
2886            }
2887            if !loose.is_empty() {
2888                return Err(not_built(format!("face {face_id}: {} new boundary piece(s) joined no loop", loose.len())));
2889            }
2890        }
2891        // The first loop keeps the face; every further closed trace of a
2892        // touched loop is a face of its own on the same carrier.
2893        let kept = rebuilt_loops.remove(0);
2894        face.loops = vec![kept];
2895        let surface = face.surface.clone();
2896        let same_sense = face.same_sense;
2897        let base_name = face.name.clone();
2898        for extra in rebuilt_loops {
2899            let name = base_name.as_ref().map(|base| {
2900                (1..).map(|k| format!("{base}_{k}")).find(|candidate| !taken.contains(candidate)).expect("a free name")
2901            });
2902            if let Some(name) = &name {
2903                taken.push(name.clone());
2904            }
2905            new_faces.push(FaceRecord { id: take_id(), surface: surface.clone(), same_sense, loops: vec![extra], name });
2906        }
2907    }
2908    if !new_faces.is_empty() {
2909        let shell_index = result.shells.iter().position(|shell| !shell.faces.is_empty())
2910            .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: no shell"))?;
2911        result.shells[shell_index].faces.extend(new_faces);
2912    }
2913    result.edges.retain(|edge| !interior.contains(&edge.id));
2914    Ok(())
2915}
2916
2917/// Swap the two parameters of a face: the surface's control net, every
2918/// coedge pcurve, and the sense (S_u × S_v changes sign).  The face's
2919/// geometry is untouched; only its chart is.  Used to hand an exact
2920/// cylinder patch built with its section along v to the analytic recogniser,
2921/// which wants the circle along u.
2922pub(in crate::blend) fn transpose_face(face: &mut FaceRecord) -> Result<(), KernelRefusal> {
2923    let surface = &face.surface;
2924    let rows_u = surface.control_points.len();
2925    let rows_v = surface.control_points.first().map(|row| row.len()).unwrap_or(0);
2926    let mut transposed = vec![Vec::with_capacity(rows_u); rows_v];
2927    for row in &surface.control_points {
2928        for (j, point) in row.iter().enumerate() {
2929            transposed[j].push(*point);
2930        }
2931    }
2932    face.surface = NurbsSurface::new(
2933        surface.degree_v,
2934        surface.degree_u,
2935        surface.knots_v.clone(),
2936        surface.knots_u.clone(),
2937        transposed,
2938    ).or_refuse(KernelStage::Refine, "new")?;
2939    for loop_record in &mut face.loops {
2940        for coedge in &mut loop_record.coedges {
2941            for control in &mut coedge.pcurve.control_points {
2942                std::mem::swap(&mut control.x, &mut control.y);
2943            }
2944        }
2945    }
2946    face.same_sense = !face.same_sense;
2947    Ok(())
2948}
2949
2950/// Drop every vertex no longer referenced by an edge — the sharp corners the
2951/// blends replaced, and anything freed by a consumed boundary.  Run ONCE after
2952/// a whole group of stripes is in: a corner vertex is still referenced by the
2953/// selected edges that have not been sewn yet.
2954pub fn prune_orphan_vertices(result: &mut BrepSolid) {
2955    let used: rustc_hash::FxHashSet<u64> = result
2956        .edges
2957        .iter()
2958        .flat_map(|candidate| [candidate.start_vertex_id, candidate.end_vertex_id])
2959        .collect();
2960    result
2961        .vertices
2962        .retain(|candidate| used.contains(&candidate.id));
2963}
2964
2965fn cs_blend_pcurve_reversed(cs_domain: &[f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
2966    crate::sweep_topology::parameter_line(cs_domain[1], 1.0, cs_domain[0], 1.0).or_refuse(KernelStage::Refine, "parameter_line")
2967}
2968
2969
2970