Skip to main content

brep_blend/blending/fillet/
edges.rs

1use super::*;
2
3/// Constant-radius rolling-ball fillet of one edge (Golovanov §4.9 march,
4/// §6.9 surgery; the cutter only where the march refuses).
5pub fn fillet_edge(
6    solid: &BrepSolid,
7    edge_id: u64,
8    radius: f64,
9    name: Option<&str>,
10) -> Result<BrepSolid, KernelRefusal> {
11    // One blend operation: the reports of an earlier one, never consumed, are
12    // dropped as it starts (nested calls keep this operation's).
13    let _operation = crate::blend::BlendOperation::enter();
14    check_mixed_concavity(solid, edge_id, "fillet_edge")?;
15    check_support_extent_clipping(solid, edge_id, radius, "fillet_edge")?;
16    fillet_or_chamfer(solid, edge_id, radius, false, name, ToolEnds::default(), Lane::GeneralFirst)
17        .map_err(|refusal| size_refusal(solid, edge_id, radius, false, name, "fillet_edge", refusal))
18}
19
20/// A blend refused because the rolling ball's contact system has no solution
21/// (`Newton is singular`) says so by name, with the size that does build.
22///
23/// A ball that does not fit beside the edge has no contact points to solve
24/// for: on the rim of a bore through a fillet (a wall 1.5 thick between the
25/// bore and the fillet's torus) no ball wider than the wall rolls, and every
26/// lane's solver stops singular, which was reported as an internal error of
27/// three lanes. A chamfer's distance is its ball's radius, so the same holds
28/// for it. This runs only after such a refusal: the same blend is tried at
29/// half, a quarter and an eighth of the size, and where one builds the
30/// largest size that does is bracketed in five more tries and named. Where
31/// none builds, the refusal is returned as it came.
32fn size_refusal(
33    solid: &BrepSolid,
34    edge_id: u64,
35    size: f64,
36    chamfer: bool,
37    name: Option<&str>,
38    entry: &str,
39    refusal: KernelRefusal,
40) -> KernelRefusal {
41    if !refusal.message.contains("Newton is singular") {
42        return refusal;
43    }
44    let builds = |size: f64| fillet_or_chamfer(solid, edge_id, size, chamfer, name, ToolEnds::default(), Lane::GeneralFirst).is_ok();
45    let mut too_large = size;
46    let mut fits = None;
47    for fraction in [0.5, 0.25, 0.125] {
48        if builds(size * fraction) {
49            fits = Some(size * fraction);
50            break;
51        }
52        too_large = size * fraction;
53    }
54    let Some(mut fits) = fits else {
55        return refusal;
56    };
57    for _ in 0..5 {
58        let middle = 0.5 * (fits + too_large);
59        if builds(middle) {
60            fits = middle;
61        } else {
62            too_large = middle;
63        }
64    }
65    KernelRefusal::input(
66        KernelStage::Refine,
67        "blend_size",
68        format!(
69            "{entry}: no rolling ball of radius {size} was found along this edge (a {kind}'s size is its ball's radius); \
70             a size up to about {fits:.3} builds. The solver's own words: {message}",
71            kind = if chamfer { "chamfer" } else { "fillet" },
72            message = refusal.message
73        ),
74    )
75}
76
77
78/// Equal-leg chamfer of one edge (Golovanov §6.11: the same construction
79/// with the arc's chord).
80pub fn chamfer_edge(
81    solid: &BrepSolid,
82    edge_id: u64,
83    distance: f64,
84    name: Option<&str>,
85) -> Result<BrepSolid, KernelRefusal> {
86    // One blend operation: the reports of an earlier one, never consumed, are
87    // dropped as it starts (nested calls keep this operation's).
88    let _operation = crate::blend::BlendOperation::enter();
89    check_mixed_concavity(solid, edge_id, "chamfer_edge")?;
90    check_support_extent(solid, edge_id, distance, "chamfer_edge")?;
91    fillet_or_chamfer(solid, edge_id, distance, true, name, ToolEnds::default(), Lane::GeneralFirst)
92        .map_err(|refusal| size_refusal(solid, edge_id, distance, true, name, "chamfer_edge", refusal))
93}
94
95/// Build and apply the chamfer tool for one straight edge from an already-built
96/// cross-section profile (curve index 1 is the chamfer chord / blend wall).
97/// Shared by the two-distance and distance-angle asymmetric entries.
98fn apply_chamfer_offsets_profile(
99    solid: &BrepSolid,
100    cross: &EdgeCross,
101    profile: &[NurbsCurve],
102    name: Option<&str>,
103    edge_id: u64,
104) -> Result<BrepSolid, KernelRefusal> {
105    // Run through to the faces the edge's ends meet where the rails go on past
106    // them (`BREP_CHAMFER_THROUGH_END_FACES`, default on; `=0` restores); the flush cutter
107    // below answers everything else.
108    if let Some(result) = super::tool::chamfer_through_end_faces(solid, edge_id, cross, profile, name) {
109        return Ok(settle_cutter_scaffold(result));
110    }
111    let mut tool = match &cross.path {
112        EdgePath::Straight { direction, length } => {
113            extrude_profile_brep(profile, *direction, *length)?
114        }
115        // A circular edge between carriers rotationally symmetric about its
116        // axis with straight meridians (`analyze_edge` admits nothing else):
117        // the legs lie on the meridians, so the chordal setbacks are also the
118        // distances along the faces, and the same section revolved about the
119        // axis is the exact tool (`BREP_CHAMFER_ASYM_CURVED`, default on).
120        EdgePath::Circular { .. } if chamfer_asym_curved_on() => {
121            super::tool::build_exact_tool(cross, profile, 0.0, ToolEnds::default(), name)?
122        }
123        EdgePath::Circular { .. } => {
124            return Err(KernelRefusal::unsupported(
125                KernelStage::Classify,
126                "asymmetric_curved_edge",
127                "chamfer_edge_asymmetric: only straight edges on planar faces are supported \
128                 in this slice (asymmetric chamfer on general/curved edges is out of scope)",
129            ));
130        }
131    };
132    // Side faces are emitted in input-curve order; the chamfer wall is the
133    // second profile curve (index 1). Every other face is the cutter's
134    // scaffold, tagged and settled exactly as the symmetric cutter's is.
135    let mut side_index = 0usize;
136    for shell in &mut tool.shells {
137        for face in &mut shell.faces {
138            if side_index == 1 {
139                if face.name.is_none() {
140                    face.name = name.map(str::to_string);
141                }
142            } else {
143                face.name = Some(scaffold_tag(name));
144            }
145            side_index += 1;
146        }
147    }
148    apply_tool(solid, &tool, cross.convex).map(settle_cutter_scaffold)
149}
150
151/// Asymmetric chamfers on curved edges (two-distance and distance-angle):
152/// on by default; `BREP_CHAMFER_ASYM_CURVED=0` restores the refusal
153/// `asymmetric_curved_edge`.
154pub fn chamfer_asym_curved_on() -> bool {
155    switch!("BREP_CHAMFER_ASYM_CURVED", true)
156}
157
158/// Asymmetric (two-distance) chamfer of one STRAIGHT edge between two planar
159/// faces (Golovanov §6.11): setback `d1` along face 1 and `d2` along face 2 —
160/// the standard CAD "d1 × d2" bevel.  General/curved edges are out of scope for
161/// this slice and return a clear error.
162pub fn chamfer_edge_asymmetric(
163    solid: &BrepSolid,
164    edge_id: u64,
165    d1: f64,
166    d2: f64,
167    name: Option<&str>,
168) -> Result<BrepSolid, KernelRefusal> {
169    // One blend operation: the reports of an earlier one, never consumed, are
170    // dropped as it starts (nested calls keep this operation's).
171    let _operation = crate::blend::BlendOperation::enter();
172    if !(d1 > 0.0) || !(d2 > 0.0) || !d1.is_finite() || !d2.is_finite() {
173        return Err(KernelRefusal::input(
174            KernelStage::Collect,
175            "setback_distances",
176            "chamfer_edge_asymmetric: both setback distances must be positive",
177        ));
178    }
179    // `analyze_edge` only uses the radius to size the orientation probe step;
180    // the smaller setback keeps that probe inside both faces.
181    let cross = match analyze_edge(solid, edge_id, d1.min(d2)) {
182        Ok(cross) => cross,
183        Err(refusal) if chamfer_asym_curved_on() => {
184            let faces = setback_faces(solid, edge_id).map_err(|_| refusal)?;
185            let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
186            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_asymmetric", false);
187        }
188        Err(refusal) => return Err(refusal),
189    };
190    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
191    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
192}
193
194/// Conic-section blend of one edge: the rolling ball's two contacts joined by
195/// a conic instead of the ball's arc.
196///
197/// `radius` places the contacts exactly where `fillet_edge` places them, the
198/// distance `radius / tan(θ/2)` from the edge on each face (θ the angle
199/// between the faces; `radius` itself at a right angle). The section is the
200/// rational quadratic through those contacts whose middle pole is the point
201/// where the two faces' section lines meet (a point of the edge), with weights
202/// `1, rho / (1 − rho), 1`. It is tangent to both faces at the contacts. `rho`
203/// in `(0, 1)` is the fraction of the way from the contacts' chord to the edge
204/// that the section's middle reaches: `0.5` is a parabola, below it an ellipse,
205/// above it a hyperbola, and `sin(θ/2) / (1 + sin(θ/2))` (`√2 − 1` at a right
206/// angle) is the ball's own arc.
207///
208/// Built here for a straight edge between two planes, and for a circular edge
209/// between surfaces of revolution about its axis whose meridians are straight
210/// (a plane, a cylinder, a cone); any other edge is refused `conic_edge` by
211/// name. An edge that runs on into its neighbours is cut through to them, as
212/// a chamfer's is.
213pub fn fillet_edge_conic(
214    solid: &BrepSolid,
215    edge_id: u64,
216    radius: f64,
217    rho: f64,
218    name: Option<&str>,
219) -> Result<BrepSolid, KernelRefusal> {
220    let _operation = crate::blend::BlendOperation::enter();
221    if !(radius > 0.0) || !radius.is_finite() {
222        return Err(KernelRefusal::input(
223            KernelStage::Collect,
224            "conic_radius",
225            "fillet_edge_conic: the radius must be positive",
226        ));
227    }
228    if !(rho > 0.0 && rho < 1.0) {
229        return Err(KernelRefusal::input(
230            KernelStage::Collect,
231            "conic_rho",
232            "fillet_edge_conic: rho must lie strictly between 0 and 1",
233        ));
234    }
235    let cross = analyze_edge(solid, edge_id, radius).map_err(|refusal| {
236        KernelRefusal::unsupported(
237            KernelStage::Classify,
238            "conic_edge",
239            format!(
240                "fillet_edge_conic: a conic blend is built only on a straight edge between planes or a \
241                 circular edge between straight-sided surfaces about its axis ({})",
242                refusal.message
243            ),
244        )
245    })?;
246    if matches!(cross.path, EdgePath::Circular { .. }) && !chamfer_asym_curved_on() {
247        return Err(KernelRefusal::unsupported(
248            KernelStage::Classify,
249            "conic_edge",
250            "fillet_edge_conic: circular edges are switched off (BREP_CHAMFER_ASYM_CURVED=0)",
251        ));
252    }
253    let profile = super::tool::conic_cross_section(&cross, radius, rho)?;
254    let result = apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)?;
255    refuse_invalid_result(&result, "fillet_edge_conic")?;
256    Ok(result)
257}
258
259/// `fillet_edge_conic` for edges picked by a point on each. The edges are
260/// blended one after another and independently: where two of them meet, the
261/// vertex stays sharp between the two blends (no corner is built).
262pub fn fillet_edges_conic(
263    solid: &BrepSolid,
264    edge_points: &[Vec3],
265    edge_names: Option<&[String]>,
266    radius: f64,
267    rho: f64,
268    name: Option<&str>,
269) -> Result<BrepSolid, KernelRefusal> {
270    let _operation = crate::blend::BlendOperation::enter();
271    if edge_points.is_empty() {
272        return Err(KernelRefusal::input(
273            KernelStage::Collect,
274            "conic_selection",
275            "fillet_edges_conic: no edges selected",
276        ));
277    }
278    let mut result = solid.clone();
279    for (index, point) in edge_points.iter().enumerate() {
280        let edge_id = resolve_edge_by_point(&result, *point)?;
281        result = fillet_edge_conic(&result, edge_id, radius, rho, per_edge_name(edge_names, name, index))?;
282    }
283    Ok(result)
284}
285
286/// The ids of the edge's two faces in `analyze_edge`'s order (face 1 first):
287/// the faces the setbacks `d1` and `d2` are measured on.
288fn setback_faces(solid: &BrepSolid, edge_id: u64) -> Result<[u64; 2], KernelRefusal> {
289    let (_, faces) = super::analyze::edge_and_faces(solid, edge_id)?;
290    match faces.as_slice() {
291        [first, second] if first.id != second.id => Ok([first.id, second.id]),
292        _ => Err(KernelRefusal::input(
293            KernelStage::Collect,
294            "edge_faces",
295            format!("asymmetric chamfer: edge {edge_id} does not join two faces"),
296        )),
297    }
298}
299
300/// The input positions of the selected points that resolve onto the smooth
301/// chain through `edge_id`, when the chain has two or more edges and the
302/// not-yet-chamfered selection covers every one of them; else `None`.
303fn selected_chain(
304    solid: &BrepSolid,
305    edge_id: u64,
306    edge_points: &[Vec3],
307    done: &[bool],
308) -> Result<Option<Vec<usize>>, KernelRefusal> {
309    let Ok((members, _closed)) = crate::blend::smooth_chain_members(solid, edge_id) else {
310        return Ok(None);
311    };
312    if members.len() < 2 {
313        return Ok(None);
314    }
315    let mut positions = Vec::new();
316    for member in &members {
317        let position = edge_points.iter().enumerate().position(|(index, point)| {
318            !done[index] && resolve_edge_by_point(solid, *point).is_ok_and(|id| id == *member)
319        });
320        match position {
321            Some(position) => positions.push(position),
322            None => return Ok(None),
323        }
324    }
325    Ok(Some(positions))
326}
327
328/// An asymmetric chamfer the exact cutters do not cover (a curved edge on
329/// carriers that are not coaxial straight-meridian revolutions): the closed
330/// rim's march with its stations solved from the setback law
331/// (`blend/setback.rs`): a closed edge as its own rim, an open edge as the
332/// closed smooth chain it lies on or else alone, and with `walk_chain` the
333/// whole smooth chain (open or closed) a selection covers.
334fn chamfer_by_setback_law(
335    solid: &BrepSolid,
336    edge_id: u64,
337    law: crate::blend::setback::SetbackLaw,
338    name: Option<&str>,
339    entry: &str,
340    walk_chain: bool,
341) -> Result<BrepSolid, KernelRefusal> {
342    let edge = solid
343        .edges
344        .iter()
345        .find(|edge| edge.id == edge_id)
346        .ok_or_else(|| KernelRefusal::input(KernelStage::Collect, "edge", format!("{entry}: edge {edge_id} not found")))?;
347    let closed = edge.start_vertex_id == edge.end_vertex_id;
348    // The operand heal the symmetric ladder runs first (ids preserved).
349    let mut healed = solid.clone();
350    let policy = crate::KernelTolerances::for_solid(&healed, 1e-7);
351    crate::heal::heal_operands(&mut healed, &policy)?;
352    let reach = law.reach();
353    let mut result = crate::blend::setback::with_setback_law(law, || {
354        if walk_chain {
355            crate::blend::blend_smooth_chain(&healed, edge_id, reach, true, name)
356        } else if closed {
357            crate::blend::blend_closed_edge(&healed, edge_id, reach, true, name)
358        } else {
359            // An arc of a closed smooth chain (a rim the carriers' seams
360            // split) is chamfered as the whole rim; a lone open edge on its
361            // own.  An open tangent chain is not walked from one of its edges
362            // (`chamfer_edges_asymmetric` takes a whole selected chain).
363            crate::blend::blend_smooth_chain_if_closed(&healed, edge_id, reach, true, name).or_else(|refusal| {
364                let lone = matches!(&refusal.class, RefusalClass::Internal { what } if what == "chain_single_segment");
365                if lone {
366                    crate::blend::blend_open_edge(&healed, edge_id, reach, true, name)
367                } else {
368                    Err(refusal)
369                }
370            })
371        }
372    })?;
373    heal_edge_vertex_gaps(&mut result, reach)?;
374    crate::blend::fit_planar_charts_to_trims(&healed, &mut result)?;
375    let result = settle_cutter_scaffold(result);
376    refuse_invalid_result(&result, entry)?;
377    super::analyze::check_blend_interference(&healed, &result, &[edge_id], "chamfer")?;
378    super::analyze::check_blend_wall_loops(&result, "chamfer")?;
379    Ok(result)
380}
381
382/// Distance-angle chamfer of one STRAIGHT edge between two planar faces
383/// (Golovanov §6.11): setback `d1` along face 1 and angle `angle_rad` between
384/// the chamfer face and face 1.  `d2` is constructed geometrically in the
385/// cross-section plane (see `chamfer_angle_second_distance`), then the
386/// two-distance builder is applied.
387pub fn chamfer_edge_angle(
388    solid: &BrepSolid,
389    edge_id: u64,
390    d1: f64,
391    angle_rad: f64,
392    name: Option<&str>,
393) -> Result<BrepSolid, KernelRefusal> {
394    // One blend operation: the reports of an earlier one, never consumed, are
395    // dropped as it starts (nested calls keep this operation's).
396    let _operation = crate::blend::BlendOperation::enter();
397    if !(d1 > 0.0) || !d1.is_finite() {
398        return Err(KernelRefusal::input(
399            KernelStage::Collect,
400            "setback_d1",
401            "chamfer_edge_angle: setback distance d1 must be positive",
402        ));
403    }
404    let cross = match analyze_edge(solid, edge_id, d1) {
405        Ok(cross) => cross,
406        Err(refusal) if chamfer_asym_curved_on() => {
407            let [first, _] = setback_faces(solid, edge_id).map_err(|_| refusal)?;
408            if !(angle_rad > 1e-9) || !(angle_rad < std::f64::consts::PI) {
409                return Err(KernelRefusal::input(
410                    KernelStage::Collect,
411                    "chamfer_angle",
412                    format!("chamfer_edge_angle: angle {angle_rad} must be positive"),
413                ));
414            }
415            let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
416            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_angle", false);
417        }
418        Err(refusal) => return Err(refusal),
419    };
420    let d2 = chamfer_angle_second_distance(&cross, d1, angle_rad)?;
421    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
422    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
423}
424
425/// Snap small trim/intersection gaps between blend edges and their vertices.
426/// The boolean endpoint welder preserves gaps already inside the validation
427/// band and limits repairs to `max(|radius| * 1e-3, 1e-4)`.
428pub(super) fn heal_edge_vertex_gaps(
429    solid: &mut BrepSolid,
430    radius: f64,
431) -> Result<(), KernelRefusal> {
432    let search = (radius.abs() * 1e-3).max(1e-7);
433    crate::boolean::commit_nearby_edge_endpoints(solid, search)
434}
435
436/// The fillet pipeline's exit acceptance: a solid with a validation ERROR is
437/// refused by name, never returned.
438///
439/// Warnings do not refuse; only the issues `validate()` itself calls errors.
440fn refuse_invalid_result(result: &BrepSolid, entry: &str) -> Result<(), KernelRefusal> {
441    let errors: Vec<_> = result.validate_memoised().into_iter().filter(|issue| issue.severity == "error").collect();
442    let Some(first) = errors.first() else {
443        return Ok(());
444    };
445    Err(KernelRefusal::new(
446        RefusalClass::InvalidResultTopology { issues: errors.len() as u32 },
447        KernelStage::Validate,
448        format!(
449            "{entry}: the blend built a solid that fails validation ({} errors, first: {}); \
450             refused rather than returned",
451            errors.len(),
452            first.message
453        ),
454    ))
455}
456
457/// `BREP_FILLET_PICK_SKIPS_SEAM` (default on; `=0` restores): a pick point that lies as near a
458/// SEAM (an edge one face uses on both sides) as a blendable edge picks the
459/// blendable one.
460///
461/// Cause (brep-bench probe, a ball r 5 bored through by a cylinder r 2, its rim
462/// filleted or chamfered from the point (0, 2, √21), refused "edge 4 borders 1
463/// faces"): the point is the vertex where the rim meets the bore's seam, both
464/// edges read distance 0, and the first found, the seam, was taken. A seam has
465/// one face on both sides and can never be blended, so it loses every tie.
466fn pick_skips_seam_on() -> bool {
467    switch!("BREP_FILLET_PICK_SKIPS_SEAM", true)
468}
469
470/// Whether `edge_id` is a seam: every coedge of it lies on one face.
471fn is_seam(solid: &BrepSolid, edge_id: u64) -> bool {
472    let users = solid
473        .shells
474        .iter()
475        .flat_map(|shell| &shell.faces)
476        .filter(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges).any(|coedge| coedge.edge_id == edge_id))
477        .count();
478    users == 1
479}
480
481/// Resolve a point within 1e-3 of a trimmed edge.
482pub fn resolve_edge_by_point(solid: &BrepSolid, point: Vec3) -> Result<u64, KernelRefusal> {
483    let nearest = crate::topology::nearest_edge(solid, point);
484    if pick_skips_seam_on() {
485        if let Some((edge_id, distance)) = nearest {
486            if distance <= 1e-3 && is_seam(solid, edge_id) {
487                let tie = distance + 1e-9 * (1.0 + point.length());
488                let blendable = solid.edges.iter().filter(|edge| edge.id != edge_id && !edge.degenerate).find(|edge| {
489                    crate::project_point_to_curve(&edge.curve, point).ok().is_some_and(|projection| {
490                        let at = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
491                        edge.curve.evaluate(at).is_ok_and(|sample| sample.sub(point).length() <= tie)
492                    }) && !is_seam(solid, edge.id)
493                });
494                if let Some(edge) = blendable {
495                    return Ok(edge.id);
496                }
497            }
498        }
499    }
500    match nearest {
501        Some((edge_id, distance)) if distance <= 1e-3 => Ok(edge_id),
502        Some((_, distance)) => Err(KernelRefusal::input(
503            KernelStage::Collect,
504            "edge_point",
505            format!(
506                "fillet_edges: no edge within tolerance of the point (nearest {distance:.6})"
507            ),
508        )),
509        None => Err(KernelRefusal::input(
510            KernelStage::Collect,
511            "no_edges",
512            "fillet_edges: solid has no edges",
513        )),
514    }
515}
516
517/// Fillet (or chamfer) a GROUP of edges as ONE operation, and — for fillets —
518/// round the convex "star" vertices where three or more of the selected edges
519/// meet (Golovanov §6.9.7).  This is the whole multi-edge fillet in a single
520/// kernel call: the caller passes the object plus one 3D point on each edge,
521/// and the kernel orchestrates the filleting and corner blending against the
522/// full topology (so acute corners resolve coherently instead of being
523/// stitched edge-by-edge by the app).  A corner the kernel cannot round (e.g.
524/// non-orthogonal beyond support, or a general no-common-ball star) is left as
525/// the edge fillets rather than failing the whole group.
526///
527/// When the WHOLE selection cannot be blended as one unit — a shared convex
528/// corner where a revolve axis/pole edge meets the adjacent cap edges can
529/// defeat the sequential corner surgery even though each edge and every proper
530/// SUBSET of the selection blends cleanly (the three fillets converge on the
531/// pole with no single end face across the corner) — a maximal-valid-SUBSET
532/// search blends the largest subset that works, dropping only the edges that
533/// cannot co-blend.  That is a real outcome and [`fillet_edges_reported`]
534/// returns it, WITH the list of edges it could not blend.
535///
536/// This entry point does not.  A solid holding eight of the ten walls that
537/// were asked for is not the answer to the question that was asked, and
538/// returning it as a plain `Ok` reports success for a different result; so an
539/// incomplete selection is an error here, naming every edge that was dropped
540/// and the group refusal behind them.  A caller that genuinely wants the
541/// partial answer asks for it by name.
542///
543/// `edge_names` (when `Some`) is the per-edge blend-FACE name parallel to
544/// `edge_points` — each grown wall is named after ITS originating edge; `None`
545/// names every wall with the single base `name` (the legacy/test behavior,
546/// byte-identical to before). The whole `*_edges` family takes the same
547/// `edge_names` slot in the same position.
548pub fn fillet_edges(
549    solid: &BrepSolid,
550    edge_points: &[Vec3],
551    edge_names: Option<&[String]>,
552    radius: f64,
553    chamfer: bool,
554    name: Option<&str>,
555) -> Result<BrepSolid, KernelRefusal> {
556    // A selected closed rim with a corner at its one vertex, on a mate creased
557    // along its own seam, is blended on the body canonicalised for it — the
558    // mate split along a smooth meridian so the network's miter closes the
559    // crease — and the walls are merged back afterwards
560    // (`blend/creased_rim.rs`). Every other selection takes the body as it
561    // came.
562    let prepared = crate::blend::creased_rim::split_creased_rims(solid, edge_points, edge_names, &resolve_edge_by_point)?;
563    match prepared {
564        Some(prepared) => {
565            let names = prepared.names.as_deref();
566            let built = fillet_edges_prepared(&prepared.solid, &prepared.points, names, radius, chamfer, name)?;
567            Ok(prepared.rejoin(built))
568        }
569        None => {
570            // A chamfer selection holding a MIXED STAR (one concave and two
571            // convex selected edges at a vertex, the convex two on one cap) is
572            // built in two phases (`fillet/chamfer_star.rs`); a phase that
573            // refuses hands the selection to the ordinary path below.
574            if chamfer {
575                let build = |body: &BrepSolid, points: &[Vec3], names: Option<&[String]>| {
576                    fillet_edges_prepared(body, points, names, radius, true, name)
577                };
578                if let Some(built) = super::chamfer_star::chamfer_mixed_stars(solid, edge_points, edge_names, &build) {
579                    return Ok(built);
580                }
581            }
582            let ordinary = fillet_edges_prepared(solid, edge_points, edge_names, radius, chamfer, name);
583            // A closed rim written as a chain of edges along the halves of a
584            // split carrier, refused because only the closed-rim rollover
585            // follows its ball and that lane takes one closed edge, is blended
586            // on the body with those halves merged and the chain joined into one
587            // closed edge (`blend/split_rim.rs`; default on,
588            // `BREP_SPLIT_RIM_MERGE=0` off). Only that refusal asks: a selection
589            // the ordinary path builds keeps its body and names.
590            let answered = match ordinary {
591                Err(refusal)
592                    if crate::blend::split_rim::split_rim_merge_on()
593                        && matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == super::analyze::TANGENT_ROLLOVER_ONLY_WHAT) =>
594                {
595                    match crate::blend::split_rim::merge_split_rims(solid, edge_points, edge_names, &resolve_edge_by_point) {
596                        // The merged attempt's own reason is appended: the
597                        // first refusal names the lane that is missing, the
598                        // second why the canonical body did not answer either
599                        // (lane F's open item).
600                        Some(merged) => fillet_edges_prepared(&merged.solid, &merged.points, merged.names.as_deref(), radius, chamfer, name)
601                            .map_err(|merged_refusal| {
602                                refusal.with_message(|message| {
603                                    format!("{message} The rim merged into one closed edge refused too: {}", merged_refusal.message)
604                                })
605                            }),
606                        None => Err(refusal),
607                    }
608                }
609                other => other,
610            };
611            // A closed ridge split into two arcs because its walls' seams sit
612            // a hair apart is blended on the body with one wall turned about
613            // the axis onto the other's seam and the arcs joined into one
614            // closed edge (`blend/turned_rim.rs`; default on,
615            // `BREP_FILLET_TURNED_RIM=0` off). Only a refusal asks.
616            let answered = match answered {
617                Err(refusal) if crate::blend::turned_rim::turned_rim_on() => {
618                    match crate::blend::turned_rim::turn_rim_seams_together(solid, edge_points, edge_names, &resolve_edge_by_point) {
619                        Some(turned) => fillet_edges_prepared(&turned.solid, &turned.points, turned.names.as_deref(), radius, chamfer, name)
620                            .map_err(|turned_refusal| {
621                                refusal.with_message(|message| {
622                                    format!("{message} The rim turned into one closed edge refused too: {}", turned_refusal.message)
623                                })
624                            }),
625                        None => Err(refusal),
626                    }
627                }
628                other => other,
629            };
630            // A sheet's edge that runs out at the free boundary has no face
631            // across its end: each such end is closed by a temporary planar
632            // face, the body blended, and the faces removed again
633            // (`blend/sheet_ends.rs`; default on, `BREP_SHEET_FREE_END=0` off).
634            // Only a refused sheet selection asks; the refusal stands unless
635            // the reopened sheet validates.
636            match answered {
637                Err(refusal) if solid.kind == crate::BodyKind::Sheet && crate::blend::sheet_ends::sheet_free_end_on() => {
638                    let edge_ids = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<Vec<_>, _>>();
639                    let Ok(edge_ids) = edge_ids else { return Err(refusal) };
640                    let Some(closed) = crate::blend::sheet_ends::close_free_ends(solid, &edge_ids) else { return Err(refusal) };
641                    let count = crate::blend::sheet_ends::temporary_faces(&closed);
642                    match fillet_edges_prepared(&closed, edge_points, edge_names, radius, chamfer, name) {
643                        Ok(built) => crate::blend::sheet_ends::open_free_ends(built, count).ok_or(refusal),
644                        Err(closed_refusal) => Err(refusal.with_message(|message| {
645                            format!("{message} The sheet with its free ends closed refused too: {}", closed_refusal.message)
646                        })),
647                    }
648                }
649                other => other,
650            }
651        }
652    }
653}
654
655fn fillet_edges_prepared(
656    solid: &BrepSolid,
657    edge_points: &[Vec3],
658    edge_names: Option<&[String]>,
659    radius: f64,
660    chamfer: bool,
661    name: Option<&str>,
662) -> Result<BrepSolid, KernelRefusal> {
663    // One blend operation: the reports of an earlier one, never consumed, are
664    // dropped as it starts (nested calls keep this operation's).
665    let _operation = crate::blend::BlendOperation::enter();
666    // Each operation pays for the first read of every body it validates
667    // (`BrepSolid::validate_memoised`, lane R1 row 3).
668    BrepSolid::clear_validate_memo();
669    // One coedge-check memo per operation, as a boolean opens one (lane R1
670    // row 3b): the surgery's, the group lane's
671    // and the exit's validations re-read the coedges the rims left unchanged.
672    let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
673    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
674    // The search is capped at one dropped edge here (lane F row 3);
675    // `BREP_SUBSET_SEARCH_FULL=1` restores the full search.
676    let cap = std::env::var_os("BREP_SUBSET_SEARCH_FULL").is_none().then_some(1);
677    let _cap = SubsetDropCap::set(cap);
678    let (result, selection) = match fillet_edges_reported(solid, edge_points, edge_names, radius, chamfer, name) {
679        // A wall that folds is relieved where it folds, not refused
680        // (`blend/relief.rs`).
681        Err(fold) if !chamfer && crate::blend::is_wall_fold(&fold) && crate::blend::relief::radius_relief_on() => {
682            let misfit = crate::blend::relief::is_misfit_fold(&fold);
683            let relieved = relieve_fold(solid, edge_points, edge_names, radius, name, fold);
684            // A misfit (a lane's refusal read as the ball not fitting) took
685            // the group off the ladder that follows the network; when no
686            // relief builds, that ladder answers, as it did before the relief.
687            if relieved.is_err() && misfit {
688                let _off = crate::blend::relief::MisfitOff::enter();
689                return fillet_edges(solid, edge_points, edge_names, radius, chamfer, name);
690            }
691            return relieved;
692        }
693        reported => reported?,
694    };
695    if selection.is_complete() {
696        return Ok(result);
697    }
698    // Every dropped edge BY NAME: the caller's own per-edge name when it gave
699    // one, and always its index and the point it was selected by.
700    let dropped: Vec<String> = selection
701        .rejected
702        .iter()
703        .map(|index| {
704            let point = edge_points[*index];
705            let named = edge_names
706                .and_then(|names| names.get(*index))
707                .map(|name| format!("`{name}` "))
708                .unwrap_or_default();
709            format!(
710                "{named}#{index} at ({:.6}, {:.6}, {:.6})",
711                point.x, point.y, point.z
712            )
713        })
714        .collect();
715    // The selection, as specified, has no single answer the kernel will
716    // stand behind: the group refusal behind the drop travels as TEXT in
717    // `BlendSelection::reason`, so this refusal carries its own class.
718    Err(KernelRefusal::ill_posed(
719        KernelStage::Select,
720        "incomplete_selection",
721        format!(
722            "{entry}: {} of the {} selected edges were blended — {} could not co-blend with the \
723             rest of the selection and carry no wall in the result ({}). The group refusal was: \
724             {}. Blend them separately, or call the reported entry point to accept the partial \
725             selection deliberately.",
726            selection.applied.len(),
727            selection.requested,
728            selection.rejected.len(),
729            dropped.join(", "),
730            selection
731                .reason
732                .as_deref()
733                .unwrap_or("the whole group built but not every edge grew a wall"),
734        ),
735    ))
736}
737
738/// The fillet a constant `radius` would fold: rebuilt with the radius reduced
739/// only where it does not fit (`blend/relief.rs`), and a note saying where
740/// and to what. Selected edges joined (through shared vertices) to no relief
741/// zone are built at the constant radius first; each relieved group is then
742/// built by the taper network on that body. A relief that still folds is
743/// planned again with a wider margin; when none builds, the fold stands with
744/// the last relief's reason appended.
745fn relieve_fold(
746    solid: &BrepSolid,
747    edge_points: &[Vec3],
748    edge_names: Option<&[String]>,
749    radius: f64,
750    name: Option<&str>,
751    fold: KernelRefusal,
752) -> Result<BrepSolid, KernelRefusal> {
753    let _relieving = crate::blend::relief::Relieving::enter();
754    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
755    let selected: Vec<u64> = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<_, _>>()?;
756    // One edge per carrier continued (`relief::join_continuations`): the
757    // selection is read again on the joined body, two points on one joined
758    // edge selecting it once.
759    let joined = crate::blend::relief::join_continuations(solid, &selected);
760    let solid = joined.as_ref().unwrap_or(solid);
761    let mut ids: Vec<u64> = Vec::with_capacity(edge_points.len());
762    let mut points: Vec<Vec3> = Vec::with_capacity(edge_points.len());
763    let mut names: Vec<String> = Vec::with_capacity(edge_points.len());
764    for (index, point) in edge_points.iter().enumerate() {
765        let id = resolve_edge_by_point(solid, *point)?;
766        if !ids.contains(&id) {
767            ids.push(id);
768            points.push(*point);
769            if let Some(name) = edge_names.and_then(|names| names.get(index)) {
770                names.push(name.clone());
771            }
772        }
773    }
774    let (edge_points, edge_names) = (&points[..], edge_names.map(|_| &names[..]));
775    if debug && joined.is_some() {
776        eprintln!("radius relief: joined continuation edges, {} selected edges become {}", selected.len(), ids.len());
777    }
778    let started = web_time::Instant::now();
779    let measured = match crate::blend::relief::measure_ceilings(solid, &ids, radius) {
780        Ok(measured) => measured,
781        Err(refusal) => return Err(fold.with_message(|message| format!("{message}; the relief could not measure the edges: {refusal}"))),
782    };
783    if debug {
784        eprintln!("radius relief: ceilings measured in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
785    }
786    // A relief is LOCAL: the requested radius stands where it fits. Where it
787    // fits nowhere on the selection (a ball wider than a rod's rim, the whole
788    // rim short alike) a radius lowered everywhere is a different request,
789    // and the fold stands, naming the largest ball that does fit.
790    let largest = measured.iter().flatten().map(|(_, ceiling)| *ceiling).fold(0.0_f64, f64::max);
791    if largest < radius {
792        return Err(fold.with_message(|message| {
793            format!("{message}; r {radius} fits nowhere along the selection, so it is not reduced locally: the largest ball that fits anywhere on it is {largest:.6}")
794        }));
795    }
796    let mut last: Option<KernelRefusal> = None;
797    for attempt in 0..crate::blend::relief::ATTEMPTS {
798        let plan = match crate::blend::relief::plan_relief(solid, &ids, radius, &measured, attempt) {
799            Ok(Some(plan)) => plan,
800            // The ball fits everywhere the probe reads: the fold is not one
801            // a smaller radius answers.
802            Ok(None) => break,
803            Err(refusal) => {
804                last = Some(refusal);
805                break;
806            }
807        };
808        let mark = crate::blend::blend_notes_mark();
809        match build_relief_plan(solid, edge_points, edge_names, &ids, radius, name, &plan) {
810            Ok(body) => {
811                for zone in &plan.zones {
812                    let near: Vec<String> = zone
813                        .edges
814                        .iter()
815                        .filter_map(|index| solid.edges.iter().find(|edge| edge.id == ids[*index]))
816                        .map(|edge| edge.name.clone().unwrap_or_else(|| format!("edge #{}", edge.id)))
817                        .map(|label| format!("`{label}`"))
818                        .collect();
819                    // The note states what was built: where the law never
820                    // climbs back to the requested radius on the zone's edges
821                    // (report 5e49bb42's rim, 1.08 to 1.78 against r 2.2), it
822                    // says so instead of "locally".
823                    let (low, high) = zone
824                        .edges
825                        .iter()
826                        .flat_map(|index| plan.stops[*index].iter().map(|(_, r)| *r))
827                        .fold((f64::INFINITY, 0.0_f64), |(low, high), r| (low.min(r), high.max(r)));
828                    let note = if high < radius * (1.0 - 1e-9) {
829                        format!(
830                            "radius reduced over the whole of {}: {low:.2} to {high:.2}, so r {radius} is reached nowhere \
831                             on them (where they turn tightest the largest ball that fits is {:.2})",
832                            near.join(", "),
833                            zone.ceiling,
834                        )
835                    } else {
836                        format!(
837                            "radius reduced to {:.2} locally near {}: r {radius} does not fit there (the largest ball that does is {:.2})",
838                            zone.radius,
839                            near.join(", "),
840                            zone.ceiling,
841                        )
842                    };
843                    crate::blend::record_blend_note(note);
844                }
845                return Ok(body);
846            }
847            Err(refusal) => {
848                crate::blend::blend_notes_truncate(mark);
849                if debug {
850                    eprintln!("radius relief attempt {attempt} refused at {:.1} ms: {refusal}", started.elapsed().as_secs_f64() * 1e3);
851                }
852                last = Some(refusal);
853            }
854        }
855    }
856    Err(match last {
857        Some(last) => fold.with_message(|message| format!("{message}; a locally reduced radius did not build either: {last}")),
858        None => fold,
859    })
860}
861
862/// Build one relief plan (see [`relieve_fold`]).
863fn build_relief_plan(
864    solid: &BrepSolid,
865    edge_points: &[Vec3],
866    edge_names: Option<&[String]>,
867    ids: &[u64],
868    radius: f64,
869    name: Option<&str>,
870    plan: &crate::blend::relief::ReliefPlan,
871) -> Result<BrepSolid, KernelRefusal> {
872    // Groups of selected edges joined through shared vertices.
873    let count = ids.len();
874    let mut group: Vec<usize> = (0..count).collect();
875    let find = |group: &mut Vec<usize>, mut index: usize| {
876        while group[index] != index {
877            group[index] = group[group[index]];
878            index = group[index];
879        }
880        index
881    };
882    let vertices: Vec<[u64; 2]> = ids
883        .iter()
884        .map(|id| {
885            solid.edges.iter().find(|edge| edge.id == *id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).unwrap_or([u64::MAX; 2])
886        })
887        .collect();
888    for a in 0..count {
889        for b in a + 1..count {
890            if vertices[a].iter().any(|vertex| *vertex != u64::MAX && vertices[b].contains(vertex)) {
891                let (root_a, root_b) = (find(&mut group, a), find(&mut group, b));
892                group[root_a] = root_b;
893            }
894        }
895    }
896    let reduced: Vec<bool> = plan.stops.iter().map(|stops| stops.iter().any(|(_, r)| *r < radius)).collect();
897    let relieved_group: Vec<bool> = (0..count)
898        .map(|index| {
899            let root = find(&mut group, index);
900            (0..count).any(|other| reduced[other] && find(&mut group, other) == root)
901        })
902        .collect();
903    let pick = |want: bool| -> (Vec<Vec3>, Option<Vec<String>>, Vec<Vec<(f64, f64)>>) {
904        let indices: Vec<usize> = (0..count).filter(|index| relieved_group[*index] == want).collect();
905        (
906            indices.iter().map(|index| edge_points[*index]).collect(),
907            edge_names.map(|names| indices.iter().filter_map(|index| names.get(*index).cloned()).collect()),
908            indices.iter().map(|index| plan.stops[*index].clone()).collect(),
909        )
910    };
911    let (constant_points, constant_names, _) = pick(false);
912    let (relieved_points, relieved_names, relieved_stops) = pick(true);
913    let mut body = solid.clone();
914    if !constant_points.is_empty() {
915        body = fillet_edges(&body, &constant_points, constant_names.as_deref(), radius, false, name)?;
916    }
917    let built = fillet_edges_variable_impl(
918        &body,
919        &relieved_points,
920        relieved_names.as_deref(),
921        &relieved_stops,
922        false,
923        name,
924        "fillet_edges",
925        false,
926    )?;
927    let issues = built.validate();
928    if !issues.is_empty() {
929        return Err(KernelRefusal::internal(
930            KernelStage::Validate,
931            "relief_validate",
932            format!("radius relief: the relieved fillet does not validate: {issues:?}"),
933        ));
934    }
935    Ok(built)
936}
937
938/// What a blend selection actually achieved.
939///
940/// The kernel can answer a group blend with fewer walls than were asked for —
941/// the maximal-valid-subset search drops the edges that cannot co-blend at a
942/// shared corner rather than failing outright. This says WHICH, so partial
943/// fulfilment is a statement instead of a silence.
944#[derive(Clone, Debug)]
945pub struct BlendSelection {
946    /// How many edges the caller selected.
947    pub requested: usize,
948    /// Indices into that selection that carry a blend wall in the result.
949    pub applied: Vec<usize>,
950    /// Indices that do not.
951    pub rejected: Vec<usize>,
952    /// Why the whole selection could not be built, when something was dropped.
953    pub reason: Option<String>,
954}
955
956impl BlendSelection {
957    /// Every requested edge carries a wall.
958    pub fn is_complete(&self) -> bool {
959        self.rejected.is_empty()
960    }
961}
962
963/// [`fillet_edges`] with the selection outcome reported rather than refused.
964///
965/// The result is the same solid `fillet_edges` would build; the difference is
966/// that an incomplete selection comes back as `Ok` with the misses named,
967/// which is the explicit partial-result contract. Every named refusal that
968/// applies to the WHOLE selection — mixed concavity, a radius the local wall
969/// cannot hold, a mixed-convexity corner — is still an `Err`: dropping edges
970/// cannot rescue those, so a partial answer would be a different defect.
971/// [`fillet_edges_reported`] with the solid and the edge points translated by
972/// `offset` for the operation and the result translated back. Refusal
973/// messages name the translated coordinates.
974pub fn fillet_edges_reported_at_offset(
975    solid: &BrepSolid,
976    edge_points: &[Vec3],
977    edge_names: Option<&[String]>,
978    radius: f64,
979    chamfer: bool,
980    name: Option<&str>,
981    offset: Vec3,
982) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
983    fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Control)
984}
985
986/// The translated run behind the control and the guard.
987#[allow(clippy::too_many_arguments)]
988fn fillet_translated(
989    solid: &BrepSolid,
990    edge_points: &[Vec3],
991    edge_names: Option<&[String]>,
992    radius: f64,
993    chamfer: bool,
994    name: Option<&str>,
995    offset: Vec3,
996    kind: crate::recentre::EntryKind,
997) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
998    let _entry = crate::recentre::TranslatedEntry::open(kind);
999    let translate = |solid: &BrepSolid, offset: Vec3| {
1000        crate::recentre::translate_solid(solid, offset).map_err(|message| {
1001            KernelRefusal::internal(
1002                KernelStage::Collect,
1003                "translation_control",
1004                format!("fillet_edges: the translation control could not move the solid: {message}"),
1005            )
1006        })
1007    };
1008    let moved = translate(solid, offset)?;
1009    let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
1010    let (result, selection) = fillet_edges_reported(&moved, &points, edge_names, radius, chamfer, name)?;
1011    Ok((translate(&result, offset.scale(-1.0))?, selection))
1012}
1013
1014pub fn fillet_edges_reported(
1015    solid: &BrepSolid,
1016    edge_points: &[Vec3],
1017    edge_names: Option<&[String]>,
1018    radius: f64,
1019    chamfer: bool,
1020    name: Option<&str>,
1021) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
1022    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
1023    // the outermost entry runs the fillet on a translated solid.
1024    if let Some(offset) = crate::recentre::control_offset_at_entry() {
1025        return fillet_edges_reported_at_offset(solid, edge_points, edge_names, radius, chamfer, name, offset);
1026    }
1027    // The recentre guard: a solid far from the origin in its own units
1028    // is filleted at the origin.
1029    let bounds = crate::recentre::solid_bounds(solid);
1030    if let Some(offset) = crate::recentre::guard_offset(bounds) {
1031        crate::recentre::profile_fired("fillet", offset, bounds);
1032        return fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Guard);
1033    }
1034    // One blend operation: the reports of an earlier one, never consumed, are
1035    // dropped as it starts (nested calls keep this operation's).
1036    let _operation = crate::blend::BlendOperation::enter();
1037    // Dropped before `_operation`, so the total is on the ledger when the
1038    // outermost operation prints it.
1039    let _total = crate::blend::BlendTimer::start("timing.total_ms");
1040    if !(radius > 0.0) || !radius.is_finite() {
1041        return Err(KernelRefusal::input(
1042            KernelStage::Collect,
1043            "radius",
1044            "fillet_edges: radius must be positive",
1045        ));
1046    }
1047    if edge_points.is_empty() {
1048        return Err(KernelRefusal::input(
1049            KernelStage::Collect,
1050            "selection",
1051            "fillet_edges: no edges selected",
1052        ));
1053    }
1054    // The rolling ball must reach both supports of every SELECTED edge — see
1055    // `check_support_extent`.  Checked ONCE, here, against the solid the
1056    // selection was made on: inside the group build the faces have already
1057    // been eaten into by earlier blends of the same selection, and a fillet
1058    // legitimately runs off that remainder (two rounds pinching on a shared
1059    // face).  Dropping edges cannot rescue an oversized radius either, so
1060    // this runs before the subset search rather than inside it.
1061    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
1062    let mut selected_ids = Vec::with_capacity(edge_points.len());
1063    if crate::blend::blend_operation_outermost() {
1064        super::analyze::clear_rollover_only();
1065    }
1066    let selection_checks = crate::blend::BlendTimer::start("timing.selection_checks_ms");
1067    let _boundaries = super::analyze::SupportBoundaryScope::open();
1068    for point in edge_points {
1069        let resolve = crate::blend::BlendTimer::start("timing.selection_checks.resolve_ms");
1070        let edge_id = resolve_edge_by_point(solid, *point)?;
1071        resolve.stop();
1072        let concavity = crate::blend::BlendTimer::start("timing.selection_checks.concavity_ms");
1073        check_mixed_concavity(solid, edge_id, entry)?;
1074        concavity.stop();
1075        let _extent = crate::blend::BlendTimer::start("timing.selection_checks.extent_ms");
1076        // A lone fillet edge may take the clipped concave fill (lane F row 5).
1077        if edge_points.len() == 1 && !chamfer {
1078            check_support_extent_clipping(solid, edge_id, radius, entry)?;
1079        } else {
1080            check_support_extent(solid, edge_id, radius, entry)?;
1081        }
1082        selected_ids.push(edge_id);
1083    }
1084    drop(_boundaries);
1085    selection_checks.stop();
1086    // A corner where the selection mixes convexity — a convex edge dying into
1087    // the concave edges it meets — has no rolling-ball closure at all: the
1088    // blends run out against each other partway along, which is the vertex
1089    // blend the stripe network does not construct yet.  It is TERMINAL, and
1090    // for the same reason as the two checks above it runs once, here: neither
1091    // the cutter composition nor the subset search below can rescue it.  The
1092    // cutter "succeeds" on this shape by shredding the solid (a sliver end cap
1093    // per corner, the carrier face split and renamed), which is worse than
1094    // the named refusal — see the 2026-09-09 rib-spine report.
1095    //
1096    // Nor can PARTITIONING the selection at the corner rescue it, which is why
1097    // this is still a refusal and not a split (measured 2026-09-13, the
1098    // partition record): the two convexity-pure halves each build on the
1099    // network, and composing them walls every selected edge and leaves every
1100    // other face's area identical to twelve digits — but the convex wall comes
1101    // out as the full untrimmed quarter-round prism (2·(1 − π/4)·r²·L to
1102    // 2.2e-10, with NO rolled-corner term) because its contact rail runs off
1103    // its own face at the TRI-TANGENT STATION and the surgery splices the
1104    // overhang in rather than clipping it. The faces it runs along come back
1105    // with self-crossing loops that `validate()`, `solid_self_intersections`,
1106    // the connectivity report and the Euler check all pass — and that
1107    // `check_loop_self_crossings` REFUSES since 9e50f6d55, so the split is not
1108    // a route to ten walls either: blend the concave half first and the
1109    // acceptance refuses every convex edge whose wall runs out into it — on
1110    // the rib both spines, at that same station, so that feature fails
1111    // outright; blend the convex half first and the maximal-valid-subset
1112    // search drops one ring edge and returns NINE walls of ten. The
1113    // construction that is missing is the runout itself: past that station the
1114    // ball rolls on one input face and on the concave stripe's own surface, so
1115    // the march needs a STRIPE as its second carrier.
1116    //
1117    // And more than that, measured 2026-09-13 (`blend/runout.rs`, which this
1118    // refusal now reports): the KEPT mate runs out too, at the mirror-image
1119    // station, so the FIRST carrier becomes the other concave stripe and the
1120    // last stretch rolls on two stripes; that stretch ends in a POLE where the
1121    // two stripes' rails on the face they share meet and the section shrinks
1122    // to a point. Two carrier switches and a degenerate terminus, not a march
1123    // with a stop.
1124    if !chamfer {
1125        // The class is BUILT where the runout composition applies — the ring
1126        // first, then one wall per spine from pole to pole (`blend/runout.rs`,
1127        // the 2026-09-30 record §5) — and refused by name, with the
1128        // composition's own reason appended, where it does not.
1129        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1130        let mut corners = crate::blend::mixed_convexity_corners(solid, &selected_ids, radius);
1131        corners.extend(crate::blend::runout::one_ended_runout_corners(solid, &selected_ids, radius));
1132        corner_analysis.stop();
1133        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1134            for corner in &corners {
1135                eprintln!(
1136                    "mixed corner at vertex {} ({:.4}, {:.4}, {:.4}): convex {:?} concave {:?}",
1137                    corner.vertex, corner.point.x, corner.point.y, corner.point.z,
1138                    corner.convex.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>(),
1139                    corner.concave.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>()
1140                );
1141            }
1142        }
1143        if !corners.is_empty() {
1144            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1145            // Cleared on entry: only THIS composition's runout may set it.
1146            RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(false));
1147            // BREP lane L: end walls_missing_tie_all_stations_20261015
1148            let composed = rounded_boss_composition(
1149                solid, &selected_ids, edge_points, edge_names, radius, name, &corners,
1150            ).or_else(|error| {
1151                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1152                    eprintln!("rounded boss composition refused: {error}");
1153                }
1154                runout_composition(
1155                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1156                )
1157            }).or_else(|error| {
1158                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1159                    eprintln!("runout composition refused: {error}");
1160                }
1161                // The open-pad composition (2026-10-17 face-ring report): one
1162                // convex and one concave edge at each mixed corner over a
1163                // planar face, the concave pads continued onto the convex
1164                // walls. Declines by name on any other corner shape, so the
1165                // runout's refusal stands where it stood.
1166                open_pad_composition(
1167                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1168                ).map_err(|pad_error| {
1169                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1170                        eprintln!("open-pad composition refused: {pad_error}");
1171                    }
1172                    // The decline is carried in the refusal's CLASS (`what`),
1173                    // never in its text: 2026-10-18 the text test let the
1174                    // decline replace the runout's named refusal on the
1175                    // nine-pick wedge (three lib tests).
1176                    let declined = matches!(&pad_error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "open_pad_shape");
1177                    if declined { error } else { pad_error }
1178                })
1179            }).or_else(|error| {
1180                // The cusp composition (reports 80c5d9d1 and 6dfd5a22): every
1181                // mixed corner a CUSP, the convex and concave edges leaving it
1182                // tangent. Declines by class on any other corner, and every
1183                // other refusal keeps the one before it: it is the last try.
1184                cusp_composition(solid, &selected_ids, edge_points, edge_names, radius, name, &corners).map_err(|cusp_error| {
1185                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1186                        eprintln!("cusp composition refused: {cusp_error}");
1187                    }
1188                    error
1189                })
1190            });
1191            match composed {
1192                Ok(result) => {
1193                    // BREP lane L: begin walls_missing_tie_all_stations_20261015
1194                    // The runout composition's walls are built and checked by
1195                    // construction; a station its OWN neighbouring wall consumes
1196                    // (a runout trimmed at an edge's end) is not a missing wall.
1197                    // Only on the NETWORK's ring: there every concave edge has its
1198                    // own wall by construction and a runout trims at most its
1199                    // ends; a ring the cutter fallback built keeps the strict
1200                    // first-station rule (the rounded boss path too).
1201                    let network_ring = RUNOUT_RING_IS_NETWORK.with(|flag| flag.replace(false));
1202                    // Integrator merge 2026-10-16 (lanes F + L): the flag above is consumed
1203                    // BEFORE lane F's exit acceptance can return early, so a refused result
1204                    // never leaves it set for the next call on this thread.
1205                    refuse_invalid_result(&result, entry)?;
1206                    let missing = walls_missing_ties(
1207                        solid, &result, edge_points, &(0..edge_points.len()).collect::<Vec<_>>(), radius, chamfer, entry, network_ring,
1208                    )?;
1209                    // BREP lane L: end walls_missing_tie_all_stations_20261015
1210                    if !missing.is_empty() {
1211                        return Err(KernelRefusal::internal(
1212                            KernelStage::Validate,
1213                            "runout_walls_missing",
1214                            format!(
1215                                "{entry}: the composition built a solid with no wall on {}",
1216                                missing.iter().map(|index| selection_label(*index, edge_points, edge_names, name)).collect::<Vec<_>>().join(", ")
1217                            ),
1218                        ));
1219                    }
1220                    let n = edge_points.len();
1221                    return Ok((
1222                        result,
1223                        BlendSelection { requested: n, applied: (0..n).collect(), rejected: Vec::new(), reason: None },
1224                    ));
1225                }
1226                Err(error) => {
1227                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1228                        eprintln!("runout composition refused: {error}");
1229                    }
1230                    check_mixed_corner_convexity(
1231                        solid, &selected_ids, edge_points, edge_names, radius, name, Some(&error),
1232                    )?;
1233                }
1234            }
1235        }
1236        // A selection whose corner setbacks consume a whole edge — the exact
1237        // degenerate radius, every face shrunk to a point — has no strip for
1238        // the network to build and nothing the cutter or the subset search
1239        // can rescue (the search answered the r = 10 cube with nine walls and
1240        // a 5174 volume against the sphere's 4189).  Terminal, by name, here.
1241        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1242        check_degenerate_corner_setbacks(
1243            solid,
1244            &selected_ids,
1245            edge_points,
1246            edge_names,
1247            radius,
1248            name,
1249        )?;
1250        corner_analysis.stop();
1251    }
1252
1253    let n = edge_points.len();
1254    let complete = |applied: Vec<usize>| BlendSelection {
1255        requested: n,
1256        applied,
1257        rejected: Vec::new(),
1258        reason: None,
1259    };
1260    // Every subset below is built against the SAME solid, and a selection of
1261    // several components is composed one component at a time in input order,
1262    // so two subsets that keep the same leading components rebuild the same
1263    // intermediate solids. The memo keeps each component's result under the
1264    // chain of components composed before it, which is everything that result
1265    // depends on here (the solid, radius, chamfer and name are fixed for the
1266    // call), so the search returns what it did without the memo, only without
1267    // the rebuilding. On the 2026-09-26 cross-drilled sphere report four bored
1268    // rims were re-blended ahead of the same failing component in each of the
1269    // (up to 372) subsets tried: 13 min 25 s for one refusal, 34 s with it.
1270    let mut memo = ComponentMemo::default();
1271    let profile = crate::profile::profile_enabled();
1272    let group_started = web_time::Instant::now();
1273    let group = fillet_edges_group_in(
1274        solid,
1275        edge_points,
1276        edge_names,
1277        radius,
1278        chamfer,
1279        name,
1280        Some(&mut memo),
1281    );
1282    if profile {
1283        profile_line!(
1284            "blend.selection group edges={n} ok={} ms={:.3}",
1285            group.is_ok(),
1286            group_started.elapsed().as_secs_f64() * 1e3
1287        );
1288    }
1289    let group_err = match group {
1290        // A group solid that fails `validate()` is never returned: it becomes
1291        // the group's refusal, so the subset search below (which validates
1292        // every subset it builds) still gets its turn, and a selection with
1293        // nothing to drop refuses by that name.
1294        Ok(result) if refuse_invalid_result(&result, entry).is_err() => {
1295            refuse_invalid_result(&result, entry).unwrap_err()
1296        }
1297        Ok(result) => {
1298            // The group returned a solid, which is NOT the same as the group
1299            // having blended every edge.  `validate()` cannot tell the
1300            // difference — it checks incidence, and a solid missing a wall is
1301            // perfectly incident — so the walls are COUNTED.
1302            let missing =
1303                walls_missing(solid, &result, edge_points, &(0..n).collect::<Vec<_>>(), radius, chamfer, entry)?;
1304            if missing.is_empty() {
1305                return Ok((result, complete((0..n).collect())));
1306            }
1307            let applied: Vec<usize> = (0..n).filter(|index| !missing.contains(index)).collect();
1308            return Ok((
1309                result,
1310                BlendSelection {
1311                    requested: n,
1312                    applied,
1313                    rejected: missing,
1314                    reason: None,
1315                },
1316            ));
1317        }
1318        Err(error) => error,
1319    };
1320    // A wall that FOLDS THROUGH ITSELF is terminal for the whole selection, and
1321    // for the reason the two checks above are: dropping edges cannot rescue it.
1322    // The subset search would happily answer this document's two collars with
1323    // the ONE that does not fold, and return a solid whose volume is a blend
1324    // short — the same silent partial `both_collars_add_independently` exists
1325    // to catch.  Reported by name instead (`blend/fold.rs`).
1326    // A miter past the sharp edge's far vertex needs support-face switching,
1327    // not a smaller selection. Do not let the subset search mask the limit.
1328    // Nor can dropping another edge close a tangential end whose taper failed.
1329    if crate::blend::is_wall_fold(&group_err) || crate::blend::is_miter_support_overrun(&group_err)
1330        || crate::blend::is_tangential_transverse_end(&group_err)
1331        || matches!(&group_err.class, RefusalClass::UnsupportedGeometry { what } if what == "canal_footprint_bound")
1332        || crate::blend::is_ball_does_not_fit(&group_err)
1333    {
1334        return Err(group_err);
1335    }
1336    // Fewer than two edges: nothing to drop, so the group error is final.
1337    // Cap the combinatorial search so a large malformed selection cannot
1338    // explode (the full group carries the common case; the search is a
1339    // rare fallback).
1340    if n < 2 || n > 12 {
1341        return Err(group_err);
1342    }
1343    // Drop the fewest edges first (largest surviving subset), trying the
1344    // drop-sets in lexicographic order so the result is deterministic.
1345    // Take the first subset that blends to a valid solid IN WHICH EVERY KEPT
1346    // EDGE GREW A WALL: a subset that itself silently drops one of its own
1347    // edges is not the maximal subset, it is a smaller one wearing a larger
1348    // one's label.
1349    let max_drop = SUBSET_DROP_CAP.with(|cap| cap.get()).map_or(n - 1, |cap| cap.min(n - 1));
1350    for drop in 1..=max_drop {
1351        for dropped in index_combinations(n, drop) {
1352            let keep: Vec<usize> = (0..n).filter(|i| !dropped.contains(i)).collect();
1353            let points: Vec<Vec3> = keep.iter().map(|i| edge_points[*i]).collect();
1354            // Subset the per-edge blend-face names with the IDENTICAL
1355            // drop-set so `kept_names[k]` still names `kept[k]`.
1356            let kept_names: Option<Vec<String>> =
1357                edge_names.map(|names| keep.iter().map(|i| names[*i].clone()).collect());
1358            crate::blend::record_count("count.subset.builds", 1);
1359            let subset_started = web_time::Instant::now();
1360            let subset = fillet_edges_group_in(
1361                solid,
1362                &points,
1363                kept_names.as_deref(),
1364                radius,
1365                chamfer,
1366                name,
1367                Some(&mut memo),
1368            );
1369            if profile {
1370                profile_line!(
1371                    "blend.selection subset dropped={dropped:?} ok={} ms={:.3}",
1372                    subset.is_ok(),
1373                    subset_started.elapsed().as_secs_f64() * 1e3
1374                );
1375            }
1376            let result = match subset {
1377                Ok(result) => result,
1378                Err(error) => {
1379                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1380                        eprintln!("subset dropped={dropped:?} refused: {error}");
1381                    }
1382                    continue;
1383                }
1384            };
1385            if !result.validate().is_empty() {
1386                continue;
1387            }
1388            if !walls_missing(solid, &result, edge_points, &keep, radius, chamfer, entry)?.is_empty() {
1389                continue;
1390            }
1391            return Ok((
1392                result,
1393                BlendSelection {
1394                    requested: n,
1395                    applied: keep,
1396                    rejected: dropped,
1397                    reason: Some(group_err.message),
1398                },
1399            ));
1400        }
1401    }
1402    Err(group_err)
1403}
1404
1405
1406/// Which of `selected` (indices into the caller's own selection) carry NO blend
1407/// wall in `result` — decided by the MATERIAL, not by a name.
1408///
1409/// A blended edge is an edge whose material changed: a convex blend removes
1410/// the sliver under the edge, so a point of the original edge ends up OUTSIDE
1411/// the answer; a concave one pads the crease, so it ends up INSIDE. An edge
1412/// the selection dropped is still the sharp edge it was, and its points still
1413/// lie ON the skin. That statement holds for every caller and every lane,
1414/// which the previous attribution did not: it looked for one face per edge
1415/// carrying the caller's per-edge name, so a caller passing `None` (the wasm
1416/// ABI, `fillet_edges_json`) got NO count at all, and a caller passing names
1417/// was told a wall was missing where the network had merged two coaxial walls
1418/// into one face (the U-channel at half its width keeps one name for two
1419/// edges) or collapsed the walls of a full-width star into its corner patch
1420/// (`{base}:CORNER:…`, and no wall name at all). Both were measured
1421/// 2026-09-26; the named path REFUSED those complete blends.
1422///
1423/// The classifier answers `On` inside a band, so the check states how far
1424/// the blend of THIS size moves the edge at each probed station — `r·(1/cos(α/2)
1425/// − 1)` for a fillet and `d·sin(α/2)` for a chamfer, `α` the angle between the
1426/// two faces' outward normals there — and probes the station the blend moves
1427/// MOST. An edge that is tangent at one end (the miter seam two rounds leave
1428/// runs to 180° at its pole) is still attributed where it is sharp. Only when
1429/// no station clears the band is the selection refused by name, rather than
1430/// an unseeable move read as a missing wall.
1431pub fn walls_missing(
1432    original: &BrepSolid,
1433    result: &BrepSolid,
1434    edge_points: &[Vec3],
1435    selected: &[usize],
1436    size: f64,
1437    chamfer: bool,
1438    entry: &str,
1439) -> Result<Vec<usize>, KernelRefusal> {
1440    walls_missing_ties(original, result, edge_points, selected, size, chamfer, entry, false)
1441}
1442
1443// BREP lane L: begin walls_missing_tie_all_stations_20261015
1444/// [`walls_missing`], with `tie_majority`: on a clearance TIE (a uniform
1445/// dihedral, every station moving the same) the first station stands for
1446/// all of them unless this is set, when a wall is missing only if MORE THAN
1447/// HALF of the tied stations still lie on the skin (an unwalled edge whose
1448/// two ends neighbouring walls consume — the wedge nine-pick's unselected
1449/// side A ∩ wall — still reads missing; "every tied station" did not).  Only the runout composition sets it: its
1450/// own neighbouring wall may consume an edge's end (the rib nine-edge
1451/// selection's trimmed runout over the wall ∩ roof pad's first tenth read
1452/// as that pad having no wall), while elsewhere the first station is what
1453/// catches a cutter composition's wrong corners (the one-ended channel with
1454/// its runout switched off: stations ON at both ends of an edge whose middle
1455/// is walled — a measured 1253.219 against its 1253.373 body) and a station
1456/// reading alone cannot tell the two apart.
1457#[allow(clippy::too_many_arguments)]
1458pub fn walls_missing_ties(
1459    original: &BrepSolid,
1460    result: &BrepSolid,
1461    edge_points: &[Vec3],
1462    selected: &[usize],
1463    size: f64,
1464    chamfer: bool,
1465    entry: &str,
1466    tie_majority: bool,
1467) -> Result<Vec<usize>, KernelRefusal> {
1468// BREP lane L: end walls_missing_tie_all_stations_20261015
1469    use crate::{PointClass, SolidClassifier};
1470    if selected.is_empty() {
1471        return Ok(Vec::new());
1472    }
1473    let _timing = crate::blend::BlendTimer::start("timing.walls_missing_ms");
1474    crate::classification::classify_profile_begin();
1475    crate::classification::containment_profile_begin();
1476    let band = crate::KernelTolerances::for_solid(result, 1e-7).model;
1477    // `classify` reads `On` within ten times its band; attribution needs the
1478    // move to clear that by the same margin again.
1479    let visible = band * 100.0;
1480    let build_timing = crate::blend::BlendTimer::start("timing.walls_missing.classifier_ms");
1481    let classifier = SolidClassifier::new(result, band)
1482        .or_refuse(KernelStage::Validate, "wall_classifier")?;
1483    // Lane R1: a station's On-or-not is read
1484    // off its nearest face first (`NearestFaceSide`, the classifier's own On
1485    // band of ten `band`s, answering only where the read is rigorous); the
1486    // ray answers whatever it declines.
1487    let nearest = Some(super::analyze::NearestFaceSide::new(result, band).or_refuse(KernelStage::Validate, "wall_nearest_face")?);
1488    let reads_on = |point: Vec3| -> Result<bool, KernelRefusal> {
1489        if let Some(class) = nearest.as_ref().and_then(|nearest| nearest.side(point)) {
1490            crate::blend::record_count("count.walls_missing.nearest", 1);
1491            return Ok(class == PointClass::On);
1492        }
1493        Ok(classifier.classify(point).or_refuse(KernelStage::Validate, "wall_classify")?.class == PointClass::On)
1494    };
1495    build_timing.stop();
1496    const STATIONS: usize = 9;
1497    let mut missing = Vec::new();
1498    for &index in selected {
1499        let point = edge_points[index];
1500        let edge_id = resolve_edge_by_point(original, point)?;
1501        let (edge, faces) = super::analyze::edge_and_faces(original, edge_id)?;
1502        // The station the blend moves most, and how far.
1503        let mut best: Option<(Vec3, f64)> = None;
1504        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1505        let mut read: Vec<(Vec3, f64)> = Vec::with_capacity(STATIONS);
1506        // BREP lane L: end walls_missing_tie_all_stations_20261015
1507        for step in 1..=STATIONS {
1508            let t = edge.t0 + (edge.t1 - edge.t0) * step as f64 / (STATIONS + 1) as f64;
1509            let Ok(station) = edge.curve.evaluate(t) else {
1510                continue;
1511            };
1512            let clearance = match faces[..] {
1513                [first, second] => {
1514                    let (Ok((_, a)), Ok((_, b))) = (
1515                        super::analyze::face_plane_normal(first, station),
1516                        super::analyze::face_plane_normal(second, station),
1517                    ) else {
1518                        continue;
1519                    };
1520                    let half: f64 = 0.5 * a.dot(b).clamp(-1.0, 1.0).acos();
1521                    if chamfer {
1522                        size * half.sin()
1523                    } else {
1524                        size * (1.0 / half.cos().max(1e-12) - 1.0)
1525                    }
1526                }
1527                // No dihedral to read: probe anyway, unguarded.
1528                _ => f64::INFINITY,
1529            };
1530            if best.map_or(true, |(_, known)| clearance > known) {
1531                best = Some((station, clearance));
1532            }
1533            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1534            read.push((station, clearance));
1535            // BREP lane L: end walls_missing_tie_all_stations_20261015
1536        }
1537        let Some((station, clearance)) = best else {
1538            return Err(KernelRefusal::internal(
1539                KernelStage::Validate,
1540                "wall_attribution_stations",
1541                format!(
1542                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — no \
1543                     station of it could be evaluated",
1544                    point.x, point.y, point.z
1545                ),
1546            ));
1547        };
1548        if !(clearance > visible) {
1549            // The faces themselves put the move under the band: the input
1550            // leaves the attribution undecidable, and it is refused rather
1551            // than guessed.
1552            return Err(KernelRefusal::ill_posed(
1553                KernelStage::Validate,
1554                "wall_attribution_band",
1555                format!(
1556                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — \
1557                     its faces are so nearly tangent that a size-{size} blend moves the edge by at \
1558                     most {clearance:.3e}, inside the {visible:.3e} the classifier can see; the \
1559                     selection is refused rather than reported on a guess",
1560                    point.x, point.y, point.z
1561                ),
1562            ));
1563        }
1564        let classify_timing = crate::blend::BlendTimer::start("timing.walls_missing.classify_ms");
1565        // The question is On or not On, never In against Out: a station the
1566        // certificate below puts farther than `visible` from every face of
1567        // the result cannot read On by the classifier's band pass (a foot on
1568        // a carrier within ten bands) nor by its ray pass (a hit within ten
1569        // bands), so it is not asked. Anything the certificate declines is
1570        // classified as before.
1571        let certified = station_clear_of_skin(result, station, band * 10.0, visible)
1572            || station_clear_of_trimmed_skin(result, station, band * 10.0, visible);
1573        let on = if certified {
1574            crate::blend::record_count("count.walls_missing.certified", 1);
1575            false
1576        } else {
1577            crate::blend::record_count("count.walls_missing.classified", 1);
1578            reads_on(station)?
1579        };
1580        classify_timing.stop();
1581        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1582        let on = on && (!tie_majority || {
1583            // The most-moved station read On; on a tie, so must more than
1584            // half of the tied stations (itself included).
1585            let tolerance = 1e-12 * clearance.abs().max(1.0);
1586            let (mut tied, mut on_skin) = (1usize, 1usize);
1587            for (other, other_clearance) in read.iter().copied() {
1588                if other.sub(station).length() == 0.0 || clearance - other_clearance > tolerance {
1589                    continue;
1590                }
1591                tied += 1;
1592                if !station_clear_of_skin(result, other, band * 10.0, visible) && reads_on(other)? {
1593                    on_skin += 1;
1594                }
1595            }
1596            2 * on_skin > tied
1597        });
1598        // BREP lane L: end walls_missing_tie_all_stations_20261015
1599        if on {
1600            missing.push(index);
1601        }
1602    }
1603    crate::classification::classify_profile_report("blend.walls_missing");
1604    crate::classification::containment_profile_report("blend.walls_missing");
1605    Ok(missing)
1606}
1607
1608
1609
1610/// Is `station` certainly farther than `margin` from every face of `result`,
1611/// trims included, read without a classifier query? `true` only when every
1612/// face is certified by one of three readings, each a lower bound on the
1613/// distance from the station to that face's trimmed carrier:
1614///
1615/// - its control-point box, widened by `on_band`, does not hold the station
1616///   (the carrier lies in the hull of positively weighted control points);
1617/// - its carrier is a recognised revolution (`NurbsSurface::analytic`,
1618///   matched to 1e-9 relative): a sphere or torus farther than `margin` in
1619///   closed form; a cone, cylinder or straight-generatrix partial sweep
1620///   whose PATCH is farther than `margin` by the larger of three lower
1621///   bounds, the meridian distance to the generatrix line, the axial
1622///   clearance from the generatrix's slab and the clearance from the
1623///   sweep's wedge (a station on one box edge lies ON the infinite cylinder
1624///   of each neighbouring wall, a radius from its centre line, and is a
1625///   radius short of its slab);
1626/// - its carrier is a recognised plane, the station's foot on it is
1627///   `Outside` the trims (`parameter_point_in_face`, the kernel's own lane
1628///   at the band the classifier would use), every loop pcurve is a straight
1629///   two-point unit-weight chord (so its image under the affine chart is a
1630///   straight 3-D segment, and the trim polygon is exact), and the station
1631///   is farther than `margin` from every chord's segment: a foot outside the
1632///   region is nearer to the region's boundary than to any of its points.
1633///
1634/// Any face none of the three reads (an unrecognised carrier, a plane the
1635/// station lies on whose trims are curved, a foot inside or on the trims)
1636/// declines the whole station to the classifier. The recogniser's 1e-9
1637/// relative bar sits four orders below the `margin` the caller passes
1638/// (a hundred model bands), which is what absorbs it.
1639fn station_clear_of_skin(result: &BrepSolid, station: Vec3, on_band: f64, margin: f64) -> bool {
1640    use crate::AnalyticSurface;
1641    // The station in a revolution frame: (ρ, h) in the meridian plane and
1642    // its azimuth θ in [0, 2π) from the frame's x axis.
1643    let meridian = |frame: &crate::RevolutionFrame| -> (f64, f64, f64) {
1644        let offset = station.sub(frame.origin);
1645        let axial = offset.dot(frame.axis);
1646        let radial = offset.sub(frame.axis.scale(axial));
1647        let mut azimuth = radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis));
1648        if azimuth < 0.0 {
1649            azimuth += std::f64::consts::TAU;
1650        }
1651        (radial.length(), axial, azimuth)
1652    };
1653    // A patch of a revolution lies inside the axial slab of its generatrix
1654    // and inside the wedge of its sweep, so the station's clearance from
1655    // either is a lower bound on its distance to the patch.
1656    let axial_clearance = |axial: f64, h0: f64, h1: f64| (h0.min(h1) - axial).max(axial - h0.max(h1)).max(0.0);
1657    let wedge_clearance = |radial: f64, azimuth: f64, sweep: f64| -> f64 {
1658        if sweep >= std::f64::consts::TAU || azimuth <= sweep {
1659            return 0.0;
1660        }
1661        // Outside the sweep: the angle to the nearer bounding meridian.
1662        let turn = (azimuth - sweep).min(std::f64::consts::TAU - azimuth);
1663        if turn >= std::f64::consts::FRAC_PI_2 { radial } else { radial * turn.sin() }
1664    };
1665    // Distance in the meridian plane from (ρ, h) to the LINE through two
1666    // generatrix points: a lower bound for a cone or cylinder's carrier.
1667    let line_distance = |radial: f64, axial: f64, (rho0, h0): (f64, f64), (rho1, h1): (f64, f64)| -> Option<f64> {
1668        let (du, dv) = (rho1 - rho0, h1 - h0);
1669        let length = (du * du + dv * dv).sqrt();
1670        (length > 0.0).then(|| ((radial - rho0) * dv - (axial - h0) * du).abs() / length)
1671    };
1672    let clear = |distance: f64| distance.is_finite() && distance > margin;
1673    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1674        let Ok(controls) = crate::Aabb::from_surface_controls(&face.surface) else { return false };
1675        if !controls.expanded(on_band).contains(station) {
1676            continue;
1677        }
1678        let certified = match face.surface.analytic() {
1679            Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) => {
1680                let (radial, axial, _) = meridian(frame);
1681                let Some(line) = line_distance(radial, axial, (*rho0, 0.0), (*rho1, *height)) else { return false };
1682                clear(line.max(axial_clearance(axial, 0.0, *height)))
1683            }
1684            Some(AnalyticSurface::Sphere { frame, radius }) => clear((station.sub(frame.origin).length() - radius).abs()),
1685            Some(AnalyticSurface::Torus { frame, major_radius, minor_radius }) => {
1686                let (radial, axial, _) = meridian(frame);
1687                let tube = radial - major_radius;
1688                clear(((tube * tube + axial * axial).sqrt() - minor_radius).abs())
1689            }
1690            Some(AnalyticSurface::Revolution { frame, sweep, generatrix, .. }) => {
1691                // A STRAIGHT generatrix in the frame's zero meridian (the
1692                // extruded-arc walls: a line parallel to the axis at the
1693                // radius): its two control points read as (ρ, h), and the
1694                // patch's distance is bounded below by the meridian line
1695                // distance, the axial clearance and the wedge clearance
1696                // together. A curved or off-meridian generatrix declines.
1697                let [a, b] = generatrix.control_points.as_slice() else { return false };
1698                if generatrix.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1699                    return false;
1700                }
1701                let meridian_of = |point: Vec3| -> Option<(f64, f64)> {
1702                    let offset = point.sub(frame.origin);
1703                    let axial = offset.dot(frame.axis);
1704                    let radial = offset.sub(frame.axis.scale(axial));
1705                    let rho = radial.length();
1706                    let on_meridian = radial.dot(frame.y_axis).abs() <= 1e-9 * rho.max(1.0) && radial.dot(frame.x_axis) >= -1e-9 * rho.max(1.0);
1707                    on_meridian.then_some((rho, axial))
1708                };
1709                let (Some(p0), Some(p1)) = (meridian_of(Vec3::new(a.x, a.y, a.z)), meridian_of(Vec3::new(b.x, b.y, b.z))) else {
1710                    return false;
1711                };
1712                let (radial, axial, azimuth) = meridian(frame);
1713                let Some(line) = line_distance(radial, axial, p0, p1) else { return false };
1714                // The TRIMMED face's slab is narrower than the surface's:
1715                // a station on one box edge lies on the untrimmed surface
1716                // of each perpendicular wall (that wall's rail line runs
1717                // through the corner), a radius short of its trimmed face.
1718                let slab = trimmed_axial_slab(face, frame).unwrap_or((p0.1, p1.1));
1719                clear(line.max(axial_clearance(axial, slab.0, slab.1)).max(wedge_clearance(radial, azimuth, *sweep)))
1720            }
1721            Some(plane @ AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => {
1722                let Ok(normal) = u_dir.cross(*v_dir).normalized() else { return false };
1723                if clear(station.sub(*origin).dot(normal).abs()) {
1724                    true
1725                } else {
1726                    planar_trims_clear_of(face, plane, station, on_band, margin)
1727                }
1728            }
1729            None => false,
1730        };
1731        if !certified {
1732            return false;
1733        }
1734    }
1735    true
1736}
1737
1738/// A tighter sufficient Not-On certificate. General carriers use subdivided
1739/// positive-weight hulls. Analytic carriers retain the projector and trim
1740/// band used by the nearest-face reader; an exterior foot also needs every
1741/// exact boundary edge farther than the existing attribution margin.
1742/// Any inconclusive read leaves the original nearest/ray query in charge.
1743fn station_clear_of_trimmed_skin(result: &BrepSolid, point: Vec3, on_band: f64, margin: f64) -> bool {
1744    let _timer = crate::blend::BlendTimer::start("timing.walls_missing.trimmed_bound_ms");
1745    if !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1746        || !margin.is_finite() || !(margin > on_band && on_band > 0.0)
1747    { return false; }
1748    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1749        let Ok(bounds) = crate::Aabb::from_surface_controls(&face.surface) else { return false; };
1750        if !bounds.expanded(margin).contains(point) { continue; }
1751        if face.surface.analytic().is_none() {
1752            if general_carrier_clear(&face.surface, point, margin) { continue; }
1753            return false;
1754        }
1755        // Within `margin`, these regular carriers have a unique nearest
1756        // foot; every other stationary foot is farther than the margin.
1757        // The sphere/torus medial sets and spindle/horn tori decline. Thus
1758        // an exterior nearest foot can meet a trimmed region within the
1759        // margin only by crossing a boundary edge inside that same ball.
1760        match face.surface.analytic() {
1761            Some(crate::AnalyticSurface::Plane { .. }) => {},
1762            Some(crate::AnalyticSurface::Sphere { radius, .. }) if *radius > 4.0 * margin => {},
1763            Some(crate::AnalyticSurface::Torus { major_radius, minor_radius, .. })
1764                if *minor_radius > 4.0 * margin && *major_radius > *minor_radius + 4.0 * margin => {},
1765            _ => return false,
1766        }
1767        let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false; };
1768        if !projection.distance.is_finite() { return false; }
1769        if projection.distance > margin { continue; }
1770        let band = crate::classification::surface_uv_band(&face.surface, projection.u, projection.v, on_band);
1771        let Ok(inside) = crate::parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, band) else { return false; };
1772        if inside != crate::PolygonClass::Outside { return false; }
1773        let mut edges = 0;
1774        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1775            let Some(edge) = result.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false; };
1776            let Some(piece) = super::analyze::edge_piece(&edge.curve, edge.t0.min(edge.t1), edge.t0.max(edge.t1)) else { return false; };
1777            let Ok(foot) = crate::project_point_to_curve(&piece, point) else { return false; };
1778            if !foot.distance.is_finite() || foot.distance <= margin { return false; }
1779            edges += 1;
1780        }
1781        if edges == 0 { return false; }
1782    }
1783    true
1784}
1785
1786/// A sufficient clearance test for a general carrier, without finding its
1787/// nearest point. Positive-weight Bezier patches lie inside their control
1788/// hulls. Decompose both clamped knot vectors, then bisect only boxes still
1789/// within `margin` of the query. Any unsupported net or exhausted work budget
1790/// declines to the existing classifier; no approximate distance is accepted.
1791fn general_carrier_clear(surface: &crate::NurbsSurface, point: Vec3, margin: f64) -> bool {
1792    use crate::Vec4;
1793    let rows = surface.control_points.len();
1794    let columns = surface.control_points.first().map_or(0, Vec::len);
1795    if rows == 0 || columns == 0 || rows.saturating_mul(columns) > 4096
1796        || surface.degree_u > 16 || surface.degree_v > 16 || surface.control_points.iter().any(|row| row.len() != columns)
1797        || !margin.is_finite() || margin <= 0.0
1798        || !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1799    { return false; }
1800    let mut scale = 1.0_f64;
1801    for control in surface.control_points.iter().flatten() {
1802        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1803        let Ok(p) = control.point() else { return false; };
1804        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1805        scale = scale.max(p.x.abs()).max(p.y.abs()).max(p.z.abs());
1806    }
1807    // Leave a rounding cushion far below the caller's existing model margin.
1808    // Unsupported scales decline rather than consume the classification band.
1809    let roundoff = 256.0 * f64::EPSILON * scale * (surface.degree_u + 1) as f64 * (surface.degree_v + 1) as f64;
1810    if roundoff >= margin * 0.01 { return false; }
1811    let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1812    let blend = |a: Vec4, b: Vec4, alpha: f64| a.scale(alpha).add(b.scale(1.0 - alpha));
1813    let mut fibres = Vec::with_capacity(columns);
1814    for column in 0..columns {
1815        let controls: Vec<_> = surface.control_points.iter().map(|row| row[column]).collect();
1816        let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_u, &controls, surface.degree_u, zero, blend) else { return false; };
1817        fibres.push(spans);
1818    }
1819    let mut budget = 256usize;
1820    for u_span in 0..fibres[0].len() {
1821        let mut across = Vec::with_capacity(surface.degree_u + 1);
1822        for row in 0..=surface.degree_u {
1823            let controls: Vec<_> = fibres.iter().map(|fibre| fibre[u_span][row]).collect();
1824            let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_v, &controls, surface.degree_v, zero, blend) else { return false; };
1825            across.push(spans);
1826        }
1827        for v_span in 0..across[0].len() {
1828            let net = across.iter().map(|row| row[v_span].clone()).collect();
1829            if !bezier_box_clear(net, point, margin + roundoff, 0, &mut budget) { return false; }
1830        }
1831    }
1832    true
1833}
1834
1835fn bezier_box_clear(net: Vec<Vec<crate::Vec4>>, point: Vec3, margin: f64, depth: usize, budget: &mut usize) -> bool {
1836    if *budget == 0 { return false; }
1837    *budget -= 1;
1838    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
1839    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
1840    for control in net.iter().flatten() {
1841        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1842        let Ok(p) = control.point() else { return false; };
1843        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1844        low.x = low.x.min(p.x); low.y = low.y.min(p.y); low.z = low.z.min(p.z);
1845        high.x = high.x.max(p.x); high.y = high.y.max(p.y); high.z = high.z.max(p.z);
1846    }
1847    // One separating coordinate is enough, and avoids a rounded square root.
1848    if point.x < low.x - margin || point.x > high.x + margin
1849        || point.y < low.y - margin || point.y > high.y + margin
1850        || point.z < low.z - margin || point.z > high.z + margin
1851    { return true; }
1852    if depth == 10 { return false; }
1853    let rows = net.len();
1854    let columns = net[0].len();
1855    let mut left = net.clone();
1856    let mut right = net.clone();
1857    // Alternate directions: every child covers exactly half the parent's
1858    // parameter rectangle; both must prove clearance.
1859    if depth % 2 == 0 {
1860        for column in 0..columns {
1861            let mut work: Vec<_> = net.iter().map(|row| row[column]).collect();
1862            for level in 1..rows {
1863                for i in 0..rows - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1864                left[level][column] = work[0];
1865                right[rows - level - 1][column] = work[rows - level - 1];
1866            }
1867        }
1868    } else {
1869        for row in 0..rows {
1870            let mut work = net[row].clone();
1871            for level in 1..columns {
1872                for i in 0..columns - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1873                left[row][level] = work[0];
1874                right[row][columns - level - 1] = work[columns - level - 1];
1875            }
1876        }
1877    }
1878    bezier_box_clear(left, point, margin, depth + 1, budget)
1879        && bezier_box_clear(right, point, margin, depth + 1, budget)
1880}
1881
1882/// The axial range `(h_low, h_high)` of a face's TRIMMED region on a
1883/// revolution whose generatrix is straight: the region lies in the uv box
1884/// of its straight-chord loops (every pcurve a two-point unit-weight
1885/// chord), the surface is a tensor product in which the axial coordinate
1886/// `h = (S − origin)·axis` depends on one parameter only and affinely
1887/// (degree 1, two control points along it), so `h` over the box is the
1888/// range between its values at the box's corners. `None` when any of that
1889/// is not read: a curved chord, an `h` that moves along both parameters,
1890/// a degree or control count that is not affine, an evaluation that fails.
1891fn trimmed_axial_slab(face: &FaceRecord, frame: &crate::RevolutionFrame) -> Option<(f64, f64)> {
1892    let (mut u_low, mut u_high, mut v_low, mut v_high) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
1893    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1894        let pcurve = &coedge.pcurve;
1895        let [a, b] = pcurve.control_points.as_slice() else { return None };
1896        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1897            return None;
1898        }
1899        for control in [a, b] {
1900            u_low = u_low.min(control.x);
1901            u_high = u_high.max(control.x);
1902            v_low = v_low.min(control.y);
1903            v_high = v_high.max(control.y);
1904        }
1905    }
1906    if !(u_low <= u_high && v_low <= v_high) {
1907        return None;
1908    }
1909    let axial_at = |u: f64, v: f64| face.surface.evaluate(u, v).ok().map(|point| point.sub(frame.origin).dot(frame.axis));
1910    let corners = [axial_at(u_low, v_low)?, axial_at(u_high, v_low)?, axial_at(u_low, v_high)?, axial_at(u_high, v_high)?];
1911    let scale = corners.iter().fold(1.0_f64, |scale, h| scale.max(h.abs()));
1912    let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * scale;
1913    let surface = &face.surface;
1914    // h constant along u (the generatrix runs along v), or along v.
1915    let affine_in_v = same(corners[0], corners[1]) && same(corners[2], corners[3])
1916        && surface.degree_v == 1 && surface.control_points.first().is_some_and(|row| row.len() == 2);
1917    let affine_in_u = same(corners[0], corners[2]) && same(corners[1], corners[3])
1918        && surface.degree_u == 1 && surface.control_points.len() == 2;
1919    if !(affine_in_v || affine_in_u) {
1920        return None;
1921    }
1922    let low = corners.iter().copied().fold(f64::INFINITY, f64::min);
1923    let high = corners.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1924    (low.is_finite() && high.is_finite()).then_some((low, high))
1925}
1926
1927/// The planar reading of [`station_clear_of_skin`]: the station's foot on
1928/// the plane lies `Outside` the face's trims and every straight loop chord's
1929/// 3-D segment is farther than `margin` from the station.
1930fn planar_trims_clear_of(
1931    face: &FaceRecord,
1932    plane: &crate::AnalyticSurface,
1933    station: Vec3,
1934    on_band: f64,
1935    margin: f64,
1936) -> bool {
1937    use crate::PolygonClass;
1938    let Some(foot) = plane.project(&face.surface, station) else { return false };
1939    let uv_band = crate::classification::surface_uv_band(&face.surface, foot.u, foot.v, on_band);
1940    match crate::parameter_point_in_face(face, crate::Vec2 { x: foot.u, y: foot.v }, uv_band) {
1941        Ok(PolygonClass::Outside) => {}
1942        _ => return false,
1943    }
1944    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1945        let pcurve = &coedge.pcurve;
1946        let [a, b] = pcurve.control_points.as_slice() else { return false };
1947        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1948            return false;
1949        }
1950        let (Ok(start), Ok(end)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else { return false };
1951        let chord = end.sub(start);
1952        let length_squared = chord.dot(chord);
1953        let offset = station.sub(start);
1954        let along = if length_squared > 0.0 { (offset.dot(chord) / length_squared).clamp(0.0, 1.0) } else { 0.0 };
1955        let distance = offset.sub(chord.scale(along)).length();
1956        if !(distance.is_finite() && distance > margin) {
1957            return false;
1958        }
1959    }
1960    true
1961}
1962
1963/// The blend-FACE name for the `i`-th selected edge: its per-edge name when the
1964/// caller supplied the parallel `edge_names` (feature path — each wall named
1965/// after its originating edge, `{fid}:BLEND:{edge}`), else the single base
1966/// `name` for every wall (the legacy/test path, byte-identical to before).
1967fn per_edge_name<'a>(
1968    edge_names: Option<&'a [String]>,
1969    base: Option<&'a str>,
1970    i: usize,
1971) -> Option<&'a str> {
1972    match edge_names {
1973        Some(names) => names.get(i).map(|value| value.as_str()),
1974        None => base,
1975    }
1976}
1977
1978/// The star-corner patch name: `{base}:CORNER:{sorted+join of adjacent edge
1979/// names}` when per-edge names were supplied (feature path), else the single
1980/// `base` (legacy/test path — the corner keeps the wall name, pre-change
1981/// behavior).  `base` is `{fid}:BLEND` and each `edge_names[i]` is the composed
1982/// `{fid}:BLEND:{edge}`, so stripping the `{base}:` prefix recovers the bare
1983/// originating-edge name for the join.  Unique per corner: two distinct corners
1984/// never share the same set of >=3 selected edges.
1985fn corner_face_name(
1986    edge_names: Option<&[String]>,
1987    base: Option<&str>,
1988    adjacent: &[usize],
1989) -> Option<String> {
1990    match (edge_names, base) {
1991        (Some(names), Some(base)) => {
1992            let prefix = format!("{base}:");
1993            let mut raws: Vec<&str> = adjacent
1994                .iter()
1995                .filter_map(|&i| names.get(i))
1996                .map(|composed| composed.strip_prefix(&prefix).unwrap_or(composed.as_str()))
1997                .collect();
1998            raws.sort_unstable();
1999            raws.dedup();
2000            Some(format!("{base}:CORNER:{}", raws.join("+")))
2001        }
2002        _ => base.map(|value| value.to_string()),
2003    }
2004}
2005
2006/// Round a connected group of convex edges first, including its ordinary
2007/// convex corner patches, then blend the concave rim across a curved bridge
2008/// at each transverse mixed corner. The spine's carriers and the cap may be
2009/// planes or curved analytic faces alike: transversality is read from the
2010/// three normals at the corner, and the rim network marches the bridge on the
2011/// actual carriers. Without these bridges the rim stripes would remain
2012/// disconnected. Redispatch the remaining selection: other mixed corners may
2013/// need another convex group or a pole-to-pole runout.
2014/// Each step removes the rounded group from the pending selection.
2015#[allow(clippy::too_many_arguments)]
2016fn rounded_boss_composition(
2017    solid: &BrepSolid,
2018    selected_ids: &[u64],
2019    edge_points: &[Vec3],
2020    edge_names: Option<&[String]>,
2021    radius: f64,
2022    name: Option<&str>,
2023    corners: &[crate::blend::MixedCorner],
2024) -> Result<BrepSolid, KernelRefusal> {
2025    // The legacy API gives every wall the same base name (or none). Use
2026    // distinct temporary identities through the recursive composition so a
2027    // bridge can be attributed to its own convex wall. Restore that API's
2028    // naming contract after the whole selection has been built.
2029    if edge_names.is_none() {
2030        let prefix = "FILLET:COMPOSITION";
2031        let names: Vec<_> = selected_ids
2032            .iter()
2033            .map(|id| format!("{prefix}:{id}"))
2034            .collect();
2035        let mut result = rounded_boss_composition(
2036            solid,
2037            selected_ids,
2038            edge_points,
2039            Some(&names),
2040            radius,
2041            Some(prefix),
2042            corners,
2043        )?;
2044        for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
2045            if face
2046                .name
2047                .as_deref()
2048                .is_some_and(|value| value.starts_with("FILLET:COMPOSITION:"))
2049            {
2050                face.name = name.map(str::to_owned);
2051            }
2052        }
2053        return Ok(result);
2054    }
2055    let decline = || {
2056        KernelRefusal::unsupported(KernelStage::Classify, "rounded_boss_selection",
2057        "the rounded boss composition requires a convex group meeting transverse mixed corners at one end of each spine")
2058    };
2059    if std::env::var("BREP_NO_NETWORK").is_ok() {
2060        return Err(decline());
2061    }
2062    // Select by topology id so reversing the requested edges preserves the
2063    // construction order. Two-ended spines are left for runout composition.
2064    let corner = corners
2065        .iter()
2066        .filter(|corner| {
2067            corner.convex.len() == 1
2068                && corner.concave.len() == 2
2069                && corners
2070                    .iter()
2071                    .filter(|other| other.convex.contains(&corner.convex[0]))
2072                    .count()
2073                    == 1
2074        })
2075        .min_by_key(|corner| selected_ids[corner.convex[0]])
2076        .ok_or_else(decline)?;
2077    let convexity =
2078        crate::blend::selection_convexity(solid, selected_ids, radius).ok_or_else(decline)?;
2079    if !convexity[corner.convex[0]] {
2080        return Err(decline());
2081    }
2082    let spine_index = corner.convex[0];
2083    // Resolve once so a missing selected edge refuses before connectivity
2084    // traversal rather than panicking inside the adjacency predicate.
2085    let selected_edges: Vec<&EdgeRecord> = selected_ids
2086        .iter()
2087        .map(|id| {
2088            solid
2089                .edges
2090                .iter()
2091                .find(|edge| edge.id == *id)
2092                .ok_or_else(|| {
2093                    KernelRefusal::internal(
2094                        KernelStage::Collect,
2095                        "rounded_boss_selected_edge",
2096                        format!("rounded boss composition: selected edge {id} is missing"),
2097                    )
2098                })
2099        })
2100        .collect::<Result<_, _>>()?;
2101    // Round the connected convex selection together. Its far corners need
2102    // their usual vertex patches before a concave rim can cross these walls.
2103    let mut rounded_indices = vec![spine_index];
2104    loop {
2105        let next = (0..selected_ids.len()).find(|index| {
2106            convexity[*index]
2107                && !rounded_indices.contains(index)
2108                && rounded_indices.iter().any(|other| {
2109                    let edge = selected_edges[*index];
2110                    let mate = selected_edges[*other];
2111                    [edge.start_vertex_id, edge.end_vertex_id]
2112                        .iter()
2113                        .any(|v| *v == mate.start_vertex_id || *v == mate.end_vertex_id)
2114                })
2115        });
2116        match next {
2117            Some(index) => rounded_indices.push(index),
2118            None => break,
2119        }
2120    }
2121    // Keep complete stars together. A selected concave edge between two
2122    // convex rims is part of their vertex blend, even though it is not part
2123    // of the convex flood above. Rounding the rims without it builds a horn
2124    // torus for an *unselected* third edge; adding that edge later leaves a
2125    // flat cap against the torus instead of the selected star's tangent sector.
2126    // Only absorb an edge whose selected neighbours are already in this
2127    // group at BOTH ends. In particular, never pull in a concave rim leading
2128    // to another mixed corner: that rim still needs the bridge below.
2129    loop {
2130        let next = (0..selected_ids.len()).find(|&index| {
2131            if convexity[index] || rounded_indices.contains(&index) {
2132                return false;
2133            }
2134            let edge = selected_edges[index];
2135            let mut has_star = false;
2136            for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2137                let neighbours: Vec<_> = selected_edges.iter().enumerate()
2138                    .filter(|(other, mate)| *other != index
2139                        && (mate.start_vertex_id == vertex || mate.end_vertex_id == vertex))
2140                    .map(|(other, _)| other)
2141                    .collect();
2142                if neighbours.iter().any(|other| !rounded_indices.contains(other)) {
2143                    return false;
2144                }
2145                has_star |= neighbours.len() >= 2;
2146            }
2147            has_star
2148        });
2149        match next {
2150            Some(index) => rounded_indices.push(index),
2151            None => break,
2152        }
2153    }
2154    rounded_indices.sort_by_key(|index| selected_ids[*index]);
2155    let mixed: Vec<_> = corners
2156        .iter()
2157        .filter(|corner| {
2158            corner
2159                .convex
2160                .iter()
2161                .any(|index| rounded_indices.contains(index))
2162        })
2163        .collect();
2164    if mixed.iter().any(|corner| {
2165        corner.convex.len() != 1
2166            || corner.concave.len() != 2
2167            || corners
2168                .iter()
2169                .filter(|other| other.convex.contains(&corner.convex[0]))
2170                .count()
2171                != 1
2172    }) {
2173        return Err(decline());
2174    }
2175    let uses = |face: &FaceRecord, edge: u64| {
2176        face.loops
2177            .iter()
2178            .flat_map(|rim| &rim.coedges)
2179            .any(|coedge| coedge.edge_id == edge)
2180    };
2181    let mut caps = Vec::new();
2182    for corner in &mixed {
2183        let spine_id = selected_ids[corner.convex[0]];
2184        let cap = solid
2185            .shells
2186            .iter()
2187            .flat_map(|shell| &shell.faces)
2188            .find(|face| {
2189                corner
2190                    .concave
2191                    .iter()
2192                    .all(|index| uses(face, selected_ids[*index]))
2193            })
2194            .ok_or_else(decline)?;
2195        let faces: Vec<_> = solid
2196            .shells
2197            .iter()
2198            .flat_map(|shell| &shell.faces)
2199            .filter(|face| face.id == cap.id || uses(face, spine_id))
2200            .collect();
2201        // The normals at the corner: a plane's from its frame, any other
2202        // carrier's at the corner's own foot on it.  The 2026-10-12 sprocket
2203        // report (`inbox_20261012_sprocket_fillet`) was the first curved CAP;
2204        // the 2026-10-13 reports on the same part put the SPINE on a cylinder
2205        // (the rim top's arc, rim wall ∩ rim top, dying into the spoke wall)
2206        // and were declined here before anything was tried, which handed the
2207        // whole selection to the runout lane and its refusal
2208        // (`inbox_20261013_sprocket_spoke_fillet`).
2209        let normals: Option<Vec<Vec3>> = faces
2210            .iter()
2211            .map(|face| match face.surface.analytic() {
2212                Some(crate::AnalyticSurface::Plane { u_dir, v_dir, .. }) => {
2213                    u_dir.cross(*v_dir).normalized().ok()
2214                }
2215                _ => {
2216                    let uv = crate::project_point_to_surface(&face.surface, corner.point).ok()?;
2217                    face.surface.normal(uv.u, uv.v).ok()
2218                }
2219            })
2220            .collect();
2221        let normals = normals.ok_or_else(decline)?;
2222        // The cap need not be perpendicular to the spine's two carriers.
2223        // An oblique or cylindrical cap cuts the rounded wall in a curved
2224        // bridge. The rim network marches that bridge on the actual carriers.
2225        // Test transversality at the corner; a cylindrical cap need not be
2226        // replaced by its tangent plane to build this composition.
2227        if normals.len() != 3
2228            || normals[0].cross(normals[1]).dot(normals[2]).abs() < 1e-6
2229        {
2230            return Err(decline());
2231        }
2232        caps.push(cap.id);
2233    }
2234    // Give unnamed walls distinct identities too: bridges are located by
2235    // their two carriers, never proximity to the old corner.
2236    let rounded_names: Vec<String> = rounded_indices
2237        .iter()
2238        .map(|index| {
2239            per_edge_name(edge_names, name, *index)
2240                .map(str::to_owned)
2241                .unwrap_or_else(|| format!("FILLET:ROUNDED_BOSS_SPINE:{index}"))
2242        })
2243        .collect();
2244    let rounded_points: Vec<Vec3> = rounded_indices
2245        .iter()
2246        .map(|index| edge_points[*index])
2247        .collect();
2248    let rounded = fillet_edges_group_in(
2249        solid,
2250        &rounded_points,
2251        Some(&rounded_names),
2252        radius,
2253        false,
2254        name,
2255        None,
2256    )?;
2257    let mut bridges = Vec::new();
2258    for (corner, cap) in mixed.iter().zip(&caps) {
2259        let wall_index = rounded_indices
2260            .iter()
2261            .position(|index| *index == corner.convex[0])
2262            .ok_or_else(|| {
2263                KernelRefusal::internal(
2264                    KernelStage::Classify,
2265                    "rounded_boss_bridge_wall",
2266                    format!(
2267                        "rounded boss composition: no convex wall for corner {}",
2268                        corner.vertex
2269                    ),
2270                )
2271            })?;
2272        let candidates: Vec<_> = rounded
2273            .edges
2274            .iter()
2275            .filter(|edge| {
2276                let faces: Vec<_> = rounded
2277                    .shells
2278                    .iter()
2279                    .flat_map(|shell| &shell.faces)
2280                    .filter(|face| uses(face, edge.id))
2281                    .collect();
2282                faces.iter().any(|face| face.id == *cap)
2283                    && faces
2284                        .iter()
2285                        .any(|face| face.name.as_deref() == Some(&rounded_names[wall_index]))
2286            })
2287            .collect();
2288        if candidates.len() != 1 {
2289            return Err(decline());
2290        }
2291        bridges.push(candidates[0]);
2292    }
2293    let rim_ids: Vec<u64> = selected_ids
2294        .iter()
2295        .enumerate()
2296        .filter(|(index, _)| !rounded_indices.contains(index))
2297        .map(|(_, id)| *id)
2298        .collect();
2299    // Both ends must join requested rim edges: never extend a selection
2300    // into an unselected perimeter.
2301    if !bridges.iter().all(|bridge| {
2302        [bridge.start_vertex_id, bridge.end_vertex_id]
2303            .iter()
2304            .all(|vertex| {
2305                rounded.edges.iter().any(|edge| {
2306                    rim_ids.contains(&edge.id)
2307                        && (edge.start_vertex_id == *vertex || edge.end_vertex_id == *vertex)
2308                })
2309            })
2310    }) {
2311        return Err(decline());
2312    }
2313    let mut points = Vec::new();
2314    let mut names = Vec::new();
2315    for (index, id) in selected_ids.iter().enumerate() {
2316        if rounded_indices.contains(&index) {
2317            continue;
2318        }
2319        let edge = rounded
2320            .edges
2321            .iter()
2322            .find(|edge| edge.id == *id)
2323            .ok_or_else(decline)?;
2324        points.push(
2325            edge.curve
2326                .evaluate(0.5 * (edge.t0 + edge.t1))
2327                .or_refuse(KernelStage::Collect, "rim_midpoint")?,
2328        );
2329        names.push(
2330            per_edge_name(edge_names, name, index)
2331                .unwrap_or("FILLET:RIM")
2332                .to_owned(),
2333        );
2334    }
2335    for (corner, bridge) in mixed.iter().zip(&bridges) {
2336        points.push(
2337            bridge
2338                .curve
2339                .evaluate(0.5 * (bridge.t0 + bridge.t1))
2340                .or_refuse(KernelStage::Collect, "bridge_midpoint")?,
2341        );
2342        let mut adjacent = corner.concave.clone();
2343        adjacent.push(corner.convex[0]);
2344        names.push(
2345            corner_face_name(edge_names, name, &adjacent)
2346                .unwrap_or_else(|| format!("FILLET:BOSS_CORNER:{}", corner.vertex)),
2347        );
2348    }
2349    // A partial rim would leave an open mixed-corner construction. Require
2350    // every pending wall, including each bridge, before accepting composition.
2351    fillet_edges_reported(&rounded, &points, Some(&names), radius, false, name).and_then(
2352        |(result, selection)| {
2353            if selection.applied.len() != points.len() {
2354                Err(decline())
2355            } else {
2356                Ok(result)
2357            }
2358        },
2359    )
2360}
2361
2362// A corner with two concave edges and a convex one requires composition.
2363//
2364// Where selected edges meet, the rolling ball has to touch every face around
2365// the vertex from ONE side. A convex edge running into the concave edges it
2366// meets (a rib spine dying into the fillets at its own base) asks the ball to
2367// sit under the shared face for one blend and over it for the other, so no
2368// ball seats there and the corner has no closure: physically the convex blend
2369// runs out against the concave beads partway along the edge, which is a vertex
2370// blend the stripe network does not construct.
2371//
2372// The re-entrant vertex of a notch — ONE concave edge, the rest convex — is
2373// NOT this: the ball rolls round that single concave edge from one convex
2374// blend to the next, and `round_concave_chain_corner` / `round_convex_corner`
2375// close it with the horn-torus sector.  Only its mirror is refused.
2376//
2377// This is TERMINAL — deliberately not a fall-through to the cutter
2378// composition. The cutter answers this shape with a watertight but shredded
2379// solid: a sliver end cap at each unclosed corner and the carrier face split
2380// so the original name lands on a fragment, which breaks every downstream
2381// reference to it. A named refusal that says which edges to separate is
2382// worth more than that solid. The runout composition (the 2026-09-30 record
2383// §5): a selection whose convex edges die into concave ones at
2384// mixed-convexity corners is built in two stages — the CONCAVE edges first,
2385// through the ordinary group path (exactly the ring the user gets selecting
2386// them alone), then one runout wall per convex spine on that ring result,
2387// marched from pole to pole with its carriers switching onto the ring's own
2388// pads. Accepted under the network's own checks.
2389//
2390// The class built here: every convex edge of the selection ends on a mixed
2391// corner at BOTH ends and shares no vertex with another convex edge, and
2392// every other selected edge is concave.  Anything else keeps the named
2393// refusal.
2394#[allow(clippy::too_many_arguments)]
2395/// The OPEN-PAD composition (the 2026-10-17 "fillet takes way too long"
2396/// face-ring report): a selection whose every mixed corner is ONE convex edge
2397/// meeting ONE concave edge over the planar face they share, the third edge
2398/// at the corner either a tangent rail (the convex edge is a blend's own end
2399/// cut by the plane, the concave one the boss it was blended to: a zero-angle
2400/// sliver on the plane) or a sharp concave edge (the boss meeting the convex
2401/// edge's other mate). Neither the rounded-boss nor the runout composition
2402/// admits it (flush-joined convex chains, concave pads ending at the corners,
2403/// no concave ring).
2404///
2405/// Built in two stages on the stripe network, each an ordinary group build:
2406///
2407/// 1. Every CONVEX edge first. A convex chain's free end at a mixed corner
2408///    is the §6.9 transverse construction against the boss as the end face:
2409///    the wall is trimmed where its envelope enters the boss, the sliver tip
2410///    of the planar face goes, and the boss skin that lay under it is exposed
2411///    along the trim curve (no cliff: the trim runs from the wall's floor
2412///    rail to its rail on the other mate, which at a tangent-rail corner
2413///    lands on that rail where wall and boss are tangent).
2414/// 2. Every CONCAVE edge on the stage-1 body, EXTENDED by the trim curves it
2415///    now continues into G1 at each trimmed end (floor|boss into wall|boss
2416///    across the wall's floor rail, a tangent seam): a flush join with a seam
2417///    at the trim's start, and at the trim's far end a pole where the wall
2418///    is tangent to the boss, or a cap where the trim meets an unselected
2419///    sharp edge. The pad rides the wall past the floor rails' crossing.
2420///
2421/// The walls are named after their edges; a trim continuation is named
2422/// `{base}:RUNOUT:{pad}+{wall}` from the two bare edge names.
2423#[allow(clippy::too_many_arguments)]
2424fn open_pad_composition(
2425    solid: &BrepSolid,
2426    selected_ids: &[u64],
2427    edge_points: &[Vec3],
2428    edge_names: Option<&[String]>,
2429    radius: f64,
2430    name: Option<&str>,
2431    corners: &[crate::blend::MixedCorner],
2432    entry: &str,
2433) -> Result<BrepSolid, KernelRefusal> {
2434    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "open_pad_shape", message);
2435    if std::env::var("BREP_NO_NETWORK").is_ok() {
2436        return Err(shape("the open-pad composition is a network construction and BREP_NO_NETWORK is set".into()));
2437    }
2438    if corners.is_empty() || corners.iter().any(|corner| corner.convex.len() != 1 || corner.concave.len() != 1) {
2439        return Err(shape("the open-pad composition is built for corners of one convex and one concave edge".into()));
2440    }
2441    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2442        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2443    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2444    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2445    if concave.is_empty() || convex.is_empty() {
2446        return Err(shape("the open-pad composition needs convex and concave edges".into()));
2447    }
2448    // Every concave edge ends at mixed corners (an open pad), and the face
2449    // the two edges share at each corner is planar.
2450    let mates = crate::blend::selection_mates(solid, selected_ids, radius)
2451        .map_err(|error| shape(format!("the selection's mates could not be read: {error}")))?;
2452    for corner in corners {
2453        let (_, convex_faces) = &mates[corner.convex[0]];
2454        let (_, concave_faces) = &mates[corner.concave[0]];
2455        let Some(shared) = convex_faces.iter().find(|face| concave_faces.iter().any(|other| other.id == face.id)) else {
2456            return Err(shape(format!("the two edges at vertex {} share no face", corner.vertex)));
2457        };
2458        if !matches!(shared.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
2459            return Err(shape(format!("the face {} the edges share at vertex {} is not planar", shared.id, corner.vertex)));
2460        }
2461    }
2462    for &index in &concave {
2463        let edge = mates[index].0;
2464        for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2465            if !corners.iter().any(|corner| corner.vertex == vertex && corner.concave[0] == index) {
2466                return Err(shape(format!(
2467                    "concave {} does not end at a mixed corner at vertex {vertex}; the open-pad composition is built for pads that do",
2468                    selection_label(index, edge_points, edge_names, name)
2469                )));
2470            }
2471        }
2472    }
2473    let base = name.unwrap_or("FILLET:OPEN_PAD");
2474    let bare = |index: usize| -> String {
2475        per_edge_name(edge_names, name, index)
2476            .map(|composed| composed.strip_prefix(&format!("{base}:")).unwrap_or(composed).to_string())
2477            .unwrap_or_else(|| selected_ids[index].to_string())
2478    };
2479    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2480
2481    // ---- Stage 1: the convex edges, as the group they are. ----
2482    let convex_points: Vec<Vec3> = convex.iter().map(|index| edge_points[*index]).collect();
2483    let convex_names: Vec<String> = convex
2484        .iter()
2485        .map(|index| per_edge_name(edge_names, name, *index).map(str::to_owned).unwrap_or_else(|| format!("{base}:WALL:{}", selected_ids[*index])))
2486        .collect();
2487    // Stage 1's body is an intermediate: the bowtie and soundness scans run
2488    // once, on stage 2's body (and the caller's acceptance after it), not on
2489    // a body the pads are about to change (1.2 s of tessellation on the
2490    // reported ring).
2491    // Both stages run as the open-pad composition's network
2492    // (`with_open_pad_network`: carrier-boundary stations, the march
2493    // extended to a section end outside the overshoot); no other network
2494    // takes those, so every body the plain network built stays as it was.
2495    let stage1 = crate::blend::with_open_pad_network(|| {
2496        fillet_edges_group_with_corner_policy(solid, &convex_points, Some(&convex_names), radius, false, name, None, true, false)
2497    })
2498    .map_err(|error| error.with_message(|error| format!("open-pad composition, the convex walls: {error}")))?;
2499    if debug {
2500        eprintln!("open-pad composition: stage 1 built the {} convex walls", convex.len());
2501    }
2502
2503    // ---- Stage 2: each pad with its trim continuations, on the stage-1 body. ----
2504    let uses = |face: &FaceRecord, edge_id: u64| face.loops.iter().flat_map(|l| &l.coedges).any(|c| c.edge_id == edge_id);
2505    let mut points: Vec<Vec3> = Vec::new();
2506    let mut names: Vec<String> = Vec::new();
2507    for &index in &concave {
2508        let (edge, faces) = &mates[index];
2509        let boss_id = if matches!(faces[0].surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) { faces[1].id } else { faces[0].id };
2510        let pad = stage1
2511            .edges
2512            .iter()
2513            .find(|candidate| candidate.id == edge.id)
2514            .ok_or_else(|| KernelRefusal::internal(KernelStage::Classify, "open_pad_edge", format!(
2515                "open-pad composition: concave edge {} vanished from the stage-1 body", edge.id
2516            )))?;
2517        points.push(pad.curve.evaluate(0.5 * (pad.t0 + pad.t1)).or_refuse(KernelStage::Collect, "pad_midpoint")?);
2518        names.push(per_edge_name(edge_names, name, index).map(str::to_owned).unwrap_or_else(|| format!("{base}:PAD:{}", edge.id)));
2519        // The trim continuations: at each end of the (trimmed) pad, the edge
2520        // that borders the boss and a stage-1 wall.
2521        for vertex in [pad.start_vertex_id, pad.end_vertex_id] {
2522            let trims: Vec<&EdgeRecord> = stage1
2523                .edges
2524                .iter()
2525                .filter(|candidate| {
2526                    candidate.id != pad.id
2527                        && !candidate.degenerate
2528                        && (candidate.start_vertex_id == vertex || candidate.end_vertex_id == vertex)
2529                })
2530                .filter(|candidate| {
2531                    let faces: Vec<&FaceRecord> = stage1.shells.iter().flat_map(|shell| &shell.faces).filter(|face| uses(face, candidate.id)).collect();
2532                    faces.iter().any(|face| face.id == boss_id)
2533                        && faces.iter().any(|face| face.name.as_deref().is_some_and(|value| convex_names.iter().any(|wall| wall == value)))
2534                })
2535                .collect();
2536            match trims.as_slice() {
2537                [trim] => {
2538                    let wall_name = stage1
2539                        .shells
2540                        .iter()
2541                        .flat_map(|shell| &shell.faces)
2542                        .filter(|face| uses(face, trim.id))
2543                        .find_map(|face| face.name.clone().filter(|value| convex_names.contains(value)))
2544                        .unwrap_or_default();
2545                    let wall_bare = wall_name.strip_prefix(&format!("{base}:")).unwrap_or(&wall_name).to_string();
2546                    points.push(trim.curve.evaluate(0.5 * (trim.t0 + trim.t1)).or_refuse(KernelStage::Collect, "trim_midpoint")?);
2547                    names.push(format!("{base}:RUNOUT:{}+{wall_bare}", bare(index)));
2548                    if debug {
2549                        eprintln!("open-pad composition: pad {} continues into trim edge {} (wall {wall_name}) at vertex {vertex}", edge.id, trim.id);
2550                    }
2551                }
2552                [] => {
2553                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2554                        "open-pad composition: at vertex {vertex} the concave {} meets no trim curve of a stage-1 wall on the boss",
2555                        selection_label(index, edge_points, edge_names, name)
2556                    )));
2557                }
2558                _ => {
2559                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2560                        "open-pad composition: at vertex {vertex} the concave {} meets {} trim curves",
2561                        selection_label(index, edge_points, edge_names, name), trims.len()
2562                    )));
2563                }
2564            }
2565        }
2566    }
2567    let result = crate::blend::with_open_pad_network(|| fillet_edges_group_in(&stage1, &points, Some(&names), radius, false, name, None))
2568        .map_err(|error| error.with_message(|error| format!("open-pad composition, the pads on the walls: {error}")))?;
2569    let _ = entry;
2570    Ok(result)
2571}
2572
2573/// The CUSP composition (2026-10-24/25 reports 80c5d9d1 and 6dfd5a22): a
2574/// selection whose every mixed corner is a CUSP — a convex edge and a concave
2575/// edge leaving the vertex tangent to each other, the face they share
2576/// narrowing to zero width between them. Report 6dfd5a22 selects the whole
2577/// of E6's start-face sliver outside F2's r 5 round: its two straight convex
2578/// edges run on G1 into the concave arc at both tips.
2579///
2580/// No other composition admits it: the pads of the open-pad composition
2581/// trim into the boss, and here both blends must TAPER to the tip, each
2582/// against the face the other leaves. Built in two stages, each an ordinary
2583/// group build, the order report 80c5d9d1 took by hand (F9, then F10):
2584///
2585/// 1. Every CONCAVE edge first: its round tapers to zero at each cusp
2586///    (`blend/taper_runout.rs`), leaving a hairline of the shared face
2587///    beside it.
2588/// 2. Every CONVEX edge on the stage-1 body: its round tapers to zero at the
2589///    same tips, with the width read against the stage-1 round's rail (the
2590///    face's boundary past the cusp line, `taper_runout::boundary_chain`).
2591///    The two rounds are G1 to the hairline between them.
2592fn cusp_composition(
2593    solid: &BrepSolid,
2594    selected_ids: &[u64],
2595    edge_points: &[Vec3],
2596    edge_names: Option<&[String]>,
2597    radius: f64,
2598    name: Option<&str>,
2599    corners: &[crate::blend::MixedCorner],
2600) -> Result<BrepSolid, KernelRefusal> {
2601    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "cusp_composition_shape", message);
2602    if std::env::var("BREP_NO_NETWORK").is_ok() {
2603        return Err(shape("the cusp composition is a network construction and BREP_NO_NETWORK is set".into()));
2604    }
2605    let edge_of = |index: usize| solid.edges.iter().find(|edge| edge.id == selected_ids[index]);
2606    // The unit tangent leaving `vertex` into the edge.
2607    let away = |index: usize, vertex: u64| -> Option<Vec3> {
2608        let edge = edge_of(index)?;
2609        let at_start = edge.start_vertex_id == vertex;
2610        let tangent = edge.curve.unit_tangent(if at_start { edge.t0 } else { edge.t1 }, edge.t0, edge.t1).ok()?;
2611        Some(if at_start { tangent } else { tangent.scale(-1.0) })
2612    };
2613    if corners.is_empty() {
2614        return Err(shape("no mixed corners".into()));
2615    }
2616    for corner in corners {
2617        let cusped = corner.convex.iter().all(|&convex| {
2618            corner.concave.iter().any(|&concave| {
2619                matches!((away(convex, corner.vertex), away(concave, corner.vertex)), (Some(a), Some(b)) if a.dot(b) >= 1.0 - 1e-6)
2620            })
2621        });
2622        if !cusped || corner.convex.is_empty() || corner.concave.is_empty() {
2623            return Err(shape(format!("the mixed corner at vertex {} is not a cusp", corner.vertex)));
2624        }
2625    }
2626    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2627        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2628    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2629    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2630    if concave.is_empty() || convex.is_empty() {
2631        return Err(shape("the cusp composition needs convex and concave edges".into()));
2632    }
2633    let names_of = |indices: &[usize]| -> Option<Vec<String>> { edge_names.map(|names| indices.iter().map(|index| names[*index].clone()).collect()) };
2634    let points_of = |indices: &[usize]| -> Vec<Vec3> { indices.iter().map(|index| edge_points[*index]).collect() };
2635    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2636    let stage1 = fillet_edges_group_in(solid, &points_of(&concave), names_of(&concave).as_deref(), radius, false, name, None)
2637        .map_err(|error| error.with_message(|error| format!("cusp composition, the concave rounds: {error}")))?;
2638    if debug {
2639        eprintln!("cusp composition: stage 1 built the {} concave rounds", concave.len());
2640    }
2641    // Each convex edge is read again on the stage-1 body by its point: the
2642    // taper split it only at its hairline's end, beside the tip.
2643    for &index in &convex {
2644        resolve_edge_by_point(&stage1, edge_points[index])
2645            .map_err(|error| error.with_message(|error| format!("cusp composition: a convex edge is not on the stage-1 body: {error}")))?;
2646    }
2647    let result = fillet_edges_group_in(&stage1, &points_of(&convex), names_of(&convex).as_deref(), radius, false, name, None)
2648        .map_err(|error| error.with_message(|error| format!("cusp composition, the convex rounds: {error}")))?;
2649    // Every round here tapers to zero at a tip, and the two rounds meet on
2650    // the hairline of the face between them: an edge's end stations stay ON
2651    // the skin (the concave arc's first tenth, where the convex round's
2652    // contact lands back on the arc), and the wall check reads the majority
2653    // of a tie, as it does for the runout composition's network ring.
2654    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(true));
2655    Ok(result)
2656}
2657
2658fn runout_composition(
2659    solid: &BrepSolid,
2660    selected_ids: &[u64],
2661    edge_points: &[Vec3],
2662    edge_names: Option<&[String]>,
2663    radius: f64,
2664    name: Option<&str>,
2665    corners: &[crate::blend::MixedCorner],
2666    entry: &str,
2667) -> Result<BrepSolid, KernelRefusal> {
2668    if std::env::var("BREP_NO_NETWORK").is_ok() {
2669        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_no_network", "the runout composition is a network construction and BREP_NO_NETWORK is set"));
2670    }
2671    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2672        .ok_or(KernelRefusal::unsupported(KernelStage::Classify, "runout_convexity", "the selection's convexity could not be read edge by edge"))?;
2673    let mut spine_ends = vec![0usize; selected_ids.len()];
2674    for corner in corners {
2675        if corner.convex.len() != 1 {
2676            return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_corner_shape", format!(
2677                "the corner at ({:.3}, {:.3}, {:.3}) has {} convex edges; the runout is built for one convex edge dying into concave ones",
2678                corner.point.x, corner.point.y, corner.point.z, corner.convex.len()
2679            )));
2680        }
2681        spine_ends[corner.convex[0]] += 1;
2682    }
2683    let mut spines: Vec<usize> = Vec::new();
2684    let mut concave: Vec<usize> = Vec::new();
2685    for (index, ends) in spine_ends.iter().enumerate() {
2686        match (*ends, convexity[index]) {
2687            (2, true) => spines.push(index),
2688            (1, true) => spines.push(index),
2689            (0, false) => concave.push(index),
2690            (ends, convex) => {
2691                return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", format!(
2692                    "{} is {} and meets a mixed corner at {ends} of its ends; the runout is built for a convex edge running out at both ends among concave edges",
2693                    selection_label(index, edge_points, edge_names, name),
2694                    if convex { "convex" } else { "concave" },
2695                )));
2696            }
2697        }
2698    }
2699    if concave.is_empty() {
2700        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", "no concave edges to build the ring from"));
2701    }
2702    // Stage 1: the ring, exactly as the concave edges build on their own.
2703    let ring_points: Vec<Vec3> = concave.iter().map(|index| edge_points[*index]).collect();
2704    let ring_names: Option<Vec<String>> = edge_names.map(|names| concave.iter().map(|index| names[*index].clone()).collect());
2705    LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = None);
2706    let ring = fillet_edges_group_with_corner_policy(solid, &ring_points, ring_names.as_deref(), radius, false, name, None, false, true)
2707        .map_err(|error| {
2708            LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2709            error.with_message(|error| format!("the concave ring did not build: {error}"))
2710        })?;
2711    // Whether the ring is the NETWORK's ring (no network refusal recorded).
2712    let network_declined = LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2713    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2714    let ring_is_network = network_declined.is_none();
2715    // BREP lane L: end walls_missing_tie_all_stations_20261015
2716    // Stage 2: the runout walls on it.
2717    let spine_walls: Vec<(u64, Option<String>)> = spines
2718        .iter()
2719        .map(|index| (selected_ids[*index], per_edge_name(edge_names, name, *index).map(str::to_string)))
2720        .collect();
2721    let spine_ids: Vec<u64> = spine_walls.iter().map(|(id, _)| *id).collect();
2722    let mut result = crate::blend::build_runout_walls(&ring, &spine_walls, radius)?;
2723    heal_edge_vertex_gaps(&mut result, radius)?;
2724    crate::blend::fit_planar_charts_to_trims(&ring, &mut result)?;
2725    let issues = result.validate();
2726    if !issues.is_empty() {
2727        return Err(KernelRefusal::new(
2728            RefusalClass::InvalidResultTopology { issues: issues.len() as u32 },
2729            KernelStage::Validate,
2730            format!("the runout walls do not validate: {issues:?}"),
2731        ));
2732    }
2733    check_blend_interference(&ring, &result, &spine_ids, entry)?;
2734    check_loop_self_crossings(&result, entry)?;
2735    check_blend_wall_loops(&result, entry)?;
2736    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
2737    let accepted = crate::accept_sound(result, entry)?;
2738    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2739    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(ring_is_network));
2740    // BREP lane L: end walls_missing_tie_all_stations_20261015
2741    Ok(accepted)
2742}
2743
2744// BREP lane L: begin walls_missing_tie_all_stations_20261015
2745thread_local! {
2746    /// Set by a runout composition that SUCCEEDED on the network's ring (no
2747    /// network refusal recorded while its ring was built), and by a cusp
2748    /// composition that built (`cusp_composition`), read and cleared by the
2749    /// acceptance: only there does a tie take the majority.
2750    static RUNOUT_RING_IS_NETWORK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2751}
2752// BREP lane L: end walls_missing_tie_all_stations_20261015
2753
2754fn check_mixed_corner_convexity(
2755    solid: &BrepSolid,
2756    edge_ids: &[u64],
2757    edge_points: &[Vec3],
2758    edge_names: Option<&[String]>,
2759    radius: f64,
2760    name: Option<&str>,
2761    composition_error: Option<&KernelRefusal>,
2762) -> Result<(), KernelRefusal> {
2763    match crate::blend::mixed_convexity_corner(solid, edge_ids, radius) {
2764        Some(corner) => {
2765            // The refusal carries the RUNOUT's own numbers when they can be
2766            // measured — the station, the carrier pair, the stop and the pole
2767            // — so it says which construction is missing and where, not only
2768            // that the corner has none.  A measurement that fails leaves the
2769            // refusal exactly as it was: the corner is refused either way.
2770            let measured = match crate::blend::plan_runout(solid, edge_ids, radius, &corner) {
2771                Ok(plan) => Some(plan),
2772                Err(error) => {
2773                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
2774                        eprintln!("runout not measured: {error}");
2775                    }
2776                    None
2777                }
2778            };
2779            // "this kernel does not build that runout here": a named deferral,
2780            // carrying why the composition declined this selection.
2781            let mut message = mixed_corner_message(
2782                &corner,
2783                edge_points,
2784                edge_names,
2785                name,
2786                measured.as_ref(),
2787            );
2788            if let Some(error) = composition_error {
2789                message.push_str(&format!(" The runout composition was tried on this selection and refused: {error}"));
2790            }
2791            Err(KernelRefusal::unsupported(
2792                KernelStage::Classify,
2793                "mixed_corner_convexity",
2794                message,
2795            ))
2796        }
2797        None => Ok(()),
2798    }
2799}
2800
2801/// Refuse a selection one of whose edges keeps NO blend strip between the
2802/// corner balls at its two ends (see `degenerate_corner_setbacks`).
2803fn check_degenerate_corner_setbacks(
2804    solid: &BrepSolid,
2805    edge_ids: &[u64],
2806    edge_points: &[Vec3],
2807    edge_names: Option<&[String]>,
2808    radius: f64,
2809    name: Option<&str>,
2810) -> Result<(), KernelRefusal> {
2811    let Some(setback) = crate::blend::degenerate_corner_setbacks(solid, edge_ids, radius) else {
2812        return Ok(());
2813    };
2814    let [from, to] = setback.stops;
2815    let how = if setback.crossed {
2816        format!(
2817            "run {:.3e} PAST each other along it (the radius is beyond the limit)",
2818            setback.strip
2819        )
2820    } else {
2821        format!(
2822            "meet there ({:.3e} apart against a bar of {:.3e})",
2823            setback.strip, setback.bar
2824        )
2825    };
2826    // "The radius is at or past the degenerate limit … reduce it": a
2827    // parameter the geometry refuses, read at `Classify`.
2828    Err(KernelRefusal::input(
2829        KernelStage::Classify,
2830        "degenerate_corner_setbacks",
2831        format!(
2832            "fillet_edges: at r = {radius} the corner setbacks consume the whole of {} — the rolling \
2833             balls seated at its two corners touch face {} at ({:.4}, {:.4}, {:.4}) and ({:.4}, \
2834             {:.4}, {:.4}) and {how}, so no blend strip is left between them and the faces it lies \
2835             on are consumed whole. The radius is at or past the degenerate limit for this \
2836             selection; reduce it.",
2837            selection_label(setback.edge, edge_points, edge_names, name),
2838            setback.face_id,
2839            from.x,
2840            from.y,
2841            from.z,
2842            to.x,
2843            to.y,
2844            to.z,
2845        ),
2846    ))
2847}
2848
2849/// How a refusal names the `index`-th selected edge: its originating edge
2850/// name when the feature layer supplied one (with the feature's base prefix
2851/// stripped), else the picked point.
2852fn selection_label(
2853    index: usize,
2854    edge_points: &[Vec3],
2855    edge_names: Option<&[String]>,
2856    name: Option<&str>,
2857) -> String {
2858    let named = edge_names.and_then(|names| names.get(index)).map(|composed| match name {
2859        Some(base) => composed
2860            .strip_prefix(&format!("{base}:"))
2861            .unwrap_or(composed)
2862            .to_string(),
2863        None => composed.clone(),
2864    });
2865    named.unwrap_or_else(|| match edge_points.get(index) {
2866        Some(point) => format!("the edge at ({:.3}, {:.3}, {:.3})", point.x, point.y, point.z),
2867        None => format!("selection #{}", index + 1),
2868    })
2869}
2870
2871/// The refusal text for [`check_mixed_corner_convexity`], naming the edges the
2872/// way the user selected them (their originating edge names when the feature
2873/// layer supplied them, else the picked point).
2874fn mixed_corner_message(
2875    corner: &crate::blend::MixedCorner,
2876    edge_points: &[Vec3],
2877    edge_names: Option<&[String]>,
2878    name: Option<&str>,
2879    measured: Option<&crate::blend::RunoutPlan>,
2880) -> String {
2881    let label = |index: usize| selection_label(index, edge_points, edge_names, name);
2882    let list = |indices: &[usize]| -> String {
2883        let parts: Vec<String> = indices.iter().map(|index| label(*index)).collect();
2884        match parts.split_last() {
2885            None => "none".to_string(),
2886            Some((last, [])) => last.clone(),
2887            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
2888        }
2889    };
2890    let mut message = format!(
2891        "fillet_edges: the selection mixes convexity at the corner ({:.3}, {:.3}, {:.3}) — convex \
2892         {} meets concave {} there. One rolling ball cannot touch the face they share from both \
2893         sides at once, so that corner has no closure: the convex blend runs out against the \
2894         concave ones partway along the edge, and this kernel does not build that runout yet. \
2895         Blending the concave edges in one fillet and the convex ones in another does not reach \
2896         a wall on every one of them either: the convex wall comes out at FULL length in either \
2897         order, and its contact leaves the faces it runs along where their own loops would then \
2898         cross. Blend the concave edges first and the blend acceptance refuses each convex edge \
2899         whose wall runs out into them; blend the convex ones first and the subset search drops \
2900         the concave edges it cannot compose instead, leaving those unfilleted.",
2901        corner.point.x,
2902        corner.point.y,
2903        corner.point.z,
2904        list(&corner.convex),
2905        list(&corner.concave),
2906    );
2907    // The runout, measured: where the ball's carriers switch, what they switch
2908    // to, and where the last stretch degenerates.  These are the numbers the
2909    // construction owes, so the refusal states them rather than leaving the
2910    // reader to derive them (`blend/runout.rs`).
2911    if let Some(plan) = measured {
2912        message.push_str(&format!(
2913            " Measured on this selection: the convex edge {}'s ball becomes tangent to face {} — \
2914             the face its two concave neighbours share — at s = {:.6} from the corner, centred \
2915             ({:.6}, {:.6}, {:.6}), where its contact on face {} reaches edge {}'s own rail \
2916             (ball-to-stripe residual {:.3e}). Past that station the second carrier is edge {}'s \
2917             STRIPE SURFACE, not a face of the input, and the march holds on it for {} \
2918             stations that fit rows reproducing their own contacts to {:.3e}. On the way the \
2919             kept mate's contact walks {:.3e} of a span off that face's own patch — into the \
2920             strip the concave stripe's pad ADDS to it — which is the shape, not an escape: \
2921             the bar a march is refused at is a full span.",
2922            plan.convex_edge,
2923            plan.shared_face,
2924            plan.station.s,
2925            plan.station.center.x,
2926            plan.station.center.y,
2927            plan.station.center.z,
2928            plan.replaced_mate,
2929            plan.second_carrier,
2930            plan.station.stripe_residual,
2931            plan.second_carrier,
2932            plan.marched,
2933            plan.fit_residual,
2934            plan.carrier_excursion,
2935        ));
2936        match (&plan.stop, plan.first_carrier) {
2937            (Some(stop), Some(first)) => message.push_str(&format!(
2938                " It does not simply stop there: at s = {:.6} the KEPT mate (face {}) runs out too \
2939                 — the ball's contact on it reaches edge {}'s rail, residual {:.3e} — so the FIRST \
2940                 carrier becomes that stripe as well and the last stretch rolls on two stripes.",
2941                stop.s, plan.kept_mate, first, stop.stripe_residual,
2942            )),
2943            _ => message.push_str(&format!(
2944                " Where the kept mate (face {}) runs out was not measurable on this selection.",
2945                plan.kept_mate
2946            )),
2947        }
2948        if let Some(pole) = plan.pole {
2949            message.push_str(&format!(
2950                " That stretch ends at a POLE, ({:.6}, {:.6}, {:.6}), where the two concave \
2951                 stripes' rails on face {} meet and the ball's two contacts merge, so the blend \
2952                 section shrinks to a point. Two carrier switches and a degenerate terminus is \
2953                 more than a stop station on a stripe, and none of it is composed yet.",
2954                pole.x, pole.y, pole.z, plan.shared_face,
2955            ));
2956        }
2957    }
2958    message
2959}
2960
2961/// All ways to choose `k` distinct indices from `0..n`, in lexicographic order.
2962fn index_combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
2963    let mut out = Vec::new();
2964    if k == 0 || k > n {
2965        return out;
2966    }
2967    let mut idx: Vec<usize> = (0..k).collect();
2968    loop {
2969        out.push(idx.clone());
2970        // Advance to the next combination (like counting with carry).
2971        let mut i = k;
2972        loop {
2973            if i == 0 {
2974                return out;
2975            }
2976            i -= 1;
2977            if idx[i] != i + n - k {
2978                break;
2979            }
2980        }
2981        idx[i] += 1;
2982        for j in (i + 1)..k {
2983            idx[j] = idx[j - 1] + 1;
2984        }
2985    }
2986}
2987
2988thread_local! {
2989    /// Running count (per thread) of group builds that reached the CUTTER
2990    /// COMPOSITION — every network lane above it refused or was rejected.  A
2991    /// zero delta across a call is the witness that the network answered it;
2992    /// a face count or a volume cannot say which lane built a solid, since the
2993    /// cutter can build the same one.  Test-observable; not part of any result.
2994    pub static CUTTER_COMPOSITIONS: std::cell::Cell<u64> =
2995        const { std::cell::Cell::new(0) };
2996}
2997
2998thread_local! {
2999    /// The most edges the maximal-valid-subset search may drop on this
3000    /// thread; `None` searches every subset. Set by [`fillet_edges`] for its
3001    /// own call (lane F row 3, 2026-10-15): that entry refuses any partial
3002    /// selection, so the search there only words the refusal, and a search
3003    /// past one dropped edge cost lCount_125 117 s of booleans (112 subsets)
3004    /// to refuse what the drop-one level refuses in 11 s.
3005    static SUBSET_DROP_CAP: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
3006}
3007
3008/// Restores the previous [`SUBSET_DROP_CAP`] when the strict entry returns.
3009struct SubsetDropCap(Option<usize>);
3010
3011impl SubsetDropCap {
3012    fn set(cap: Option<usize>) -> Self {
3013        Self(SUBSET_DROP_CAP.with(|current| current.replace(cap)))
3014    }
3015}
3016
3017impl Drop for SubsetDropCap {
3018    fn drop(&mut self) {
3019        SUBSET_DROP_CAP.with(|current| current.set(self.0));
3020    }
3021}
3022
3023thread_local! {
3024    /// Running count (per thread) of [`fillet_edges_group_in`] builds, nested
3025    /// component builds included. Test-observable; not part of any result.
3026    pub static GROUP_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
3027    /// The network's last refusal in a group build on this thread, read
3028    /// back by the runout composition when its ring stage fails.
3029    static LAST_NETWORK_REFUSAL: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3030    /// The wall fold the network refused THIS group build's selection by,
3031    /// scoped to one [`fillet_edges_group_unchecked`] call (nested component
3032    /// builds save and restore it).
3033    static GROUP_NETWORK_FOLD: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3034}
3035
3036/// One component of a selection: its edge points (as bits, so the key is
3037/// exact) and its per-edge wall names.
3038type ComponentKey = (Vec<[u64; 3]>, Option<Vec<String>>);
3039
3040/// One step of the cutter composition's sequential build: the edge's
3041/// selection point (as bits), its wall name, the cutter's end pads (as bits)
3042/// and the composition lane (0 = general first, 1 = cutter first). The pads
3043/// and the lane are part of the key because both are read off the WHOLE
3044/// selection (its corners), so the same edge can take a different cutter in
3045/// a subset that drops a corner's third edge.
3046type SequentialKey = ([u64; 3], Option<String>, [u64; 2], u8);
3047
3048/// Component results of one [`fillet_edges_reported`] call, keyed by the chain
3049/// of components composed up to and including the one built. Valid only for
3050/// the solid, radius, chamfer flag and name of that call.
3051///
3052/// `sequential` is the same memo one level down, for a single connected
3053/// component: the evolving body of the cutter composition after each edge
3054/// blended, keyed by the chain of steps composed up to and including it. The
3055/// subset search's one-drop subsets of a connected selection mostly open
3056/// with the same edges in the same order, so without it every such subset
3057/// rebuilt the same cutter booleans before reaching the edge that refuses.
3058/// On the 2026-10-17 "fillet takes way too long" report (a 7-edge face ring
3059/// whose second edge refuses after the first edge's 6-8 s cutter boolean)
3060/// that boolean ran six times for one refusal: for the group and for the
3061/// five subsets that keep the first edge.
3062///
3063/// A one-drop subset of a connected ring can split it into two components
3064/// (the ring minus an edge that is not an end of a path), and the component
3065/// chains then differ from subset to subset while the cutter composition's
3066/// first steps do not; so the sequential memo is keyed by the chain of
3067/// components composed BEFORE the body being built (`prefix`, empty for a
3068/// single-component selection) together with the steps, and the component
3069/// builds carry the memo down instead of `None`. A FIRST component's steps
3070/// key under the empty prefix like a single-component selection's, which
3071/// is sound because both start from the same body: the component build
3072/// re-heals the selection's already healed input, and `heal_operands`
3073/// leaves a clean input byte-identical (its contract, stated at the heal
3074/// above; the cross-partition hits on the reported ring are its evidence).
3075#[derive(Default)]
3076struct ComponentMemo {
3077    built: std::collections::HashMap<Vec<ComponentKey>, Result<BrepSolid, KernelRefusal>>,
3078    /// The components composed before the build in progress, from the
3079    /// outermost selection down (set around each component build).
3080    prefix: Vec<ComponentKey>,
3081    sequential: std::collections::HashMap<
3082        (Vec<ComponentKey>, Vec<SequentialKey>),
3083        Result<BrepSolid, KernelRefusal>,
3084    >,
3085}
3086
3087/// [`fillet_edges_group_in`], with the subset search's component memo when
3088/// `memo` is `Some`. The search passes it on its own solid, and the component
3089/// builds pass it on down with `ComponentMemo::prefix` naming the components
3090/// composed before them (see `ComponentMemo::sequential`).
3091fn fillet_edges_group_in(
3092    solid: &BrepSolid,
3093    edge_points: &[Vec3],
3094    edge_names: Option<&[String]>,
3095    radius: f64,
3096    chamfer: bool,
3097    name: Option<&str>,
3098    memo: Option<&mut ComponentMemo>,
3099) -> Result<BrepSolid, KernelRefusal> {
3100    fillet_edges_group_with_corner_policy(solid, edge_points, edge_names, radius, chamfer, name, memo, true, true)
3101}
3102
3103fn fillet_edges_group_with_corner_policy(
3104    solid: &BrepSolid,
3105    edge_points: &[Vec3],
3106    edge_names: Option<&[String]>,
3107    radius: f64,
3108    chamfer: bool,
3109    name: Option<&str>,
3110    memo: Option<&mut ComponentMemo>,
3111    wrap_concave: bool,
3112    accept: bool,
3113) -> Result<BrepSolid, KernelRefusal> {
3114    GROUP_BUILDS.with(|count| count.set(count.get() + 1));
3115    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3116    let GroupBody { body: result, bowtie_clean } =
3117        fillet_edges_group_unchecked(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave)?;
3118    if !accept {
3119        return Ok(result);
3120    }
3121    // A body the network or the closed-rim lane already scanned clean and
3122    // handed up untouched is not scanned again (the scan is a pure function
3123    // of the body, 2026-10-12). The composite road and the cutter road hand
3124    // up bodies no lane scanned, and are scanned here.
3125    if bowtie_clean {
3126        crate::blend::record_count("count.bowtie.lane_scan_reused", 1);
3127    } else {
3128        check_loop_self_crossings(&result, entry)?;
3129        check_blend_wall_loops(&result, entry)?;
3130    }
3131    let soundness = crate::blend::BlendTimer::start("timing.soundness_ms");
3132    // The BODY's own soundness, beside the loop's. A blend wall is a FITTED
3133    // surface and a fit can carry two parameters of one wall to one point in
3134    // space — measured on `inbox-20260902-fillet-two-torus-box-edges`, whose
3135    // wall `F8:BLEND:Box_NZ|P.T5_Side[0]` does exactly that while `validate()`,
3136    // connectivity, Euler parity, the loop scan and the face-versus-face scan
3137    // are all silent. Two walls crossing each other is the same class and is
3138    // repaired where it can be. Neither is visible to a volume oracle, so a
3139    // result carrying one reports success for a different shape.
3140    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
3141    let accepted = crate::accept_sound(result, entry);
3142    soundness.stop();
3143    accepted
3144}
3145
3146/// What the unchecked group lane hands up: the body, and whether a lane's
3147/// own acceptance already ran the bowtie scan on exactly this body and
3148/// found it clean (the network and closed-rim exits return the scanned
3149/// body unchanged; the composite and cutter exits do not scan).
3150struct GroupBody {
3151    body: BrepSolid,
3152    bowtie_clean: bool,
3153}
3154
3155/// [`fillet_edges_group_lanes`], answering a selection the network refused
3156/// by a WALL FOLD and the cutter composition then failed too by that fold,
3157/// not by the composition's own text: the fold is the reason, and the
3158/// composition's last cutter ("mates share their end boundary edge" on the
3159/// 2026-10-21 sculpted cap, report 5e49bb42) names nothing the user can act
3160/// on. The fold keeps its class, so the subset search above stops on it.
3161fn fillet_edges_group_unchecked(
3162    solid: &BrepSolid,
3163    edge_points: &[Vec3],
3164    edge_names: Option<&[String]>,
3165    radius: f64,
3166    chamfer: bool,
3167    name: Option<&str>,
3168    memo: Option<&mut ComponentMemo>,
3169    wrap_concave: bool,
3170) -> Result<GroupBody, KernelRefusal> {
3171    let outer = GROUP_NETWORK_FOLD.with(|fold| fold.borrow_mut().take());
3172    let built = fillet_edges_group_lanes(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave);
3173    let fold = GROUP_NETWORK_FOLD.with(|fold| std::mem::replace(&mut *fold.borrow_mut(), outer));
3174    match (built, fold) {
3175        (Err(error), Some(fold)) if !crate::blend::is_wall_fold(&error) => Err(fold),
3176        (built, _) => built,
3177    }
3178}
3179
3180/// `BREP_FILLET_CONCAVE_FIRST_STAGES` (default on; `=0` restores the cutter
3181/// composition): a selection the network refuses for MIXED CONVEXITY whose
3182/// concave edges also meet each other at a corner no selected convex edge
3183/// reaches is built in two network stages, concave edges first.
3184///
3185/// Cause: a boss standing across a block's top edge, filleted along its base
3186/// (two vertical concave edges on the block's side, the concave arc on its
3187/// top) together with the boss's bottom face. The bottom corners are
3188/// re-entrant stars (one concave, two convex edges), which the network
3189/// refuses by convexity, so the WHOLE selection went to the sequential
3190/// cutter build; that build runs each concave cutter past the block's sharp
3191/// top edge and closes it with folded flat caps (a crease of 180 degrees)
3192/// instead of the miter the network builds where the two concave pads meet
3193/// over that edge.
3194/// The stage name a concave pad carries between the two stages of
3195/// [`concave_first_stages`], followed by its selection index.
3196const CONCAVE_FIRST_PAD: &str = "FILLET:CONCAVE_FIRST:";
3197
3198fn concave_first_stages_on() -> bool {
3199    switch!("BREP_FILLET_CONCAVE_FIRST_STAGES", true)
3200}
3201
3202/// One network stage of [`concave_first_stages`], under the acceptance the
3203/// group's own network result gets (heal, planar charts, validation,
3204/// interference, loop scans). `None` when the network refuses or the result
3205/// fails any check.
3206fn concave_first_network_stage(
3207    input: &BrepSolid,
3208    edge_ids: &[u64],
3209    network_names: &[Option<String>],
3210    corner_name: &dyn Fn(&[usize]) -> Option<String>,
3211    radius: f64,
3212    wrap_concave: bool,
3213) -> Option<BrepSolid> {
3214    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3215    let mut body = match crate::blend::blend_star_network_with_corner_policy(
3216        input, edge_ids, radius, false, network_names, corner_name, wrap_concave,
3217    ) {
3218        Ok(body) => body,
3219        Err(refusal) => {
3220            if debug {
3221                eprintln!("concave-first stage on {edge_ids:?} refused: {refusal}");
3222            }
3223            return None;
3224        }
3225    };
3226    let entry = "fillet_edges";
3227    let healed = heal_edge_vertex_gaps(&mut body, radius);
3228    let charts = crate::blend::fit_planar_charts_to_trims(input, &mut body);
3229    let issues = body.validate_memoised();
3230    let interference = check_blend_interference(input, &body, edge_ids, entry);
3231    let bowtie = check_loop_self_crossings(&body, entry).and_then(|()| check_blend_wall_loops(&body, entry));
3232    if healed.is_ok() && charts.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3233        return Some(body);
3234    }
3235    if debug {
3236        eprintln!(
3237            "concave-first stage on {edge_ids:?} rejected: heal={healed:?} charts={charts:?} issues={issues:?} \
3238             interference={interference:?} bowtie={bowtie:?}"
3239        );
3240    }
3241    None
3242}
3243
3244/// The two-stage build [`concave_first_stages_on`] describes: the concave
3245/// edges through the network on the input, then the convex edges through the
3246/// network on that body. Where a concave pad now separates two selected
3247/// convex edges that met it at a re-entrant star, the pad's own edge on their
3248/// shared face joins the second stage, so the star closes as one rounded run
3249/// (named as the star's corner) rather than with flat caps. `None` when the
3250/// selection is not of this shape or either stage fails: the caller's ladder
3251/// then goes on unchanged.
3252#[allow(clippy::too_many_arguments)]
3253fn concave_first_stages(
3254    solid: &BrepSolid,
3255    edge_points: &[Vec3],
3256    edge_names: Option<&[String]>,
3257    selected_edge_ids: &[u64],
3258    radius: f64,
3259    name: Option<&str>,
3260    wrap_concave: bool,
3261) -> Option<BrepSolid> {
3262    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3263    let convex = crate::blend::selection_convexity(solid, selected_edge_ids, radius)?;
3264    let concave_indices: Vec<usize> = (0..convex.len()).filter(|&index| !convex[index]).collect();
3265    let convex_indices: Vec<usize> = (0..convex.len()).filter(|&index| convex[index]).collect();
3266    if concave_indices.is_empty() || convex_indices.is_empty() {
3267        return None;
3268    }
3269    let edge = |id: u64| solid.edges.iter().find(|edge| edge.id == id);
3270    let ends = |id: u64| edge(id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]);
3271    // The shape this answers: two concave edges meeting where no selected
3272    // convex edge ends (the miter the cutter build caps).
3273    let concave_corner = concave_indices.iter().enumerate().any(|(slot, &a)| {
3274        concave_indices[slot + 1..].iter().any(|&b| {
3275            let (Some(ends_a), Some(ends_b)) = (ends(selected_edge_ids[a]), ends(selected_edge_ids[b])) else {
3276                return false;
3277            };
3278            ends_a.iter().any(|vertex| {
3279                ends_b.contains(vertex)
3280                    && !convex_indices.iter().any(|&c| ends(selected_edge_ids[c]).is_some_and(|ends_c| ends_c.contains(vertex)))
3281            })
3282        })
3283    });
3284    if !concave_corner {
3285        return None;
3286    }
3287    let names_of = |indices: &[usize]| -> Vec<Option<String>> {
3288        indices.iter().map(|&index| per_edge_name(edge_names, name, index).map(str::to_string)).collect()
3289    };
3290    // Stage 1: the concave edges on the input. Each pad carries a stage name
3291    // of its own until the end, so finding a pad below never depends on the
3292    // names the caller supplied (or did not).
3293    let concave_ids: Vec<u64> = concave_indices.iter().map(|&index| selected_edge_ids[index]).collect();
3294    let stage_name = |index: usize| format!("{CONCAVE_FIRST_PAD}{index}");
3295    let concave_names: Vec<Option<String>> = concave_indices.iter().map(|&index| Some(stage_name(index))).collect();
3296    let concave_corner_name = |adjacent: &[usize]| {
3297        let members: Vec<usize> = adjacent.iter().map(|&slot| concave_indices[slot]).collect();
3298        corner_face_name(edge_names, name, &members)
3299    };
3300    let staged = concave_first_network_stage(solid, &concave_ids, &concave_names, &concave_corner_name, radius, wrap_concave)?;
3301    let original_faces: rustc_hash::FxHashSet<u64> =
3302        solid.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.id).collect();
3303    let faces_of = |id: u64| -> Vec<&FaceRecord> {
3304        staged
3305            .shells
3306            .iter()
3307            .flat_map(|shell| &shell.faces)
3308            .filter(|face| face.loops.iter().flat_map(|rim| &rim.coedges).any(|coedge| coedge.edge_id == id))
3309            .collect()
3310    };
3311    // Stage 2: the convex edges, resolved on the staged body by their pick
3312    // points (a concave pad trims a convex edge at its end, never at the
3313    // point it was picked by).
3314    let mut stage_ids: Vec<u64> = Vec::with_capacity(convex_indices.len() + 2);
3315    let mut members: Vec<Vec<usize>> = Vec::with_capacity(convex_indices.len() + 2);
3316    for &index in &convex_indices {
3317        let id = resolve_edge_by_point(&staged, edge_points[index]).ok()?;
3318        // A pick that now lands on a pad (one made inside the stretch the pad
3319        // trimmed away) is not the convex edge it named.
3320        if stage_ids.contains(&id) || faces_of(id).iter().any(|face| !original_faces.contains(&face.id)) {
3321            return None;
3322        }
3323        stage_ids.push(id);
3324        members.push(vec![index]);
3325    }
3326    let staged_edge = |id: u64| staged.edges.iter().find(|edge| edge.id == id);
3327    let convex_count = stage_ids.len();
3328    for pad in &staged.edges {
3329        if pad.degenerate || stage_ids.contains(&pad.id) || pad.start_vertex_id == pad.end_vertex_id {
3330            continue;
3331        }
3332        let faces = faces_of(pad.id);
3333        if faces.len() != 2 {
3334            continue;
3335        }
3336        // One side is a stage-1 pad, named after the concave edge it rounds.
3337        let Some(concave_index) = faces.iter().find(|face| !original_faces.contains(&face.id)).and_then(|face| {
3338            concave_indices.iter().copied().find(|&index| face.name.as_deref() == Some(stage_name(index).as_str()))
3339        }) else {
3340            continue;
3341        };
3342        // Its two ends are ends of two DIFFERENT selected convex edges.
3343        let ender = |vertex: u64| {
3344            (0..convex_count).find(|&slot| {
3345                staged_edge(stage_ids[slot]).is_some_and(|edge| edge.start_vertex_id == vertex || edge.end_vertex_id == vertex)
3346            })
3347        };
3348        let (Some(first), Some(second)) = (ender(pad.start_vertex_id), ender(pad.end_vertex_id)) else {
3349            continue;
3350        };
3351        if first == second {
3352            continue;
3353        }
3354        // And the other side is a face both of those convex edges run along.
3355        let Some(other) = faces.iter().find(|face| original_faces.contains(&face.id)) else {
3356            continue;
3357        };
3358        let borders = |slot: usize| faces_of(stage_ids[slot]).iter().any(|face| face.id == other.id);
3359        if !borders(first) || !borders(second) {
3360            continue;
3361        }
3362        match super::analyze::scan_dihedral(&staged, pad.id) {
3363            Ok(profile) if profile.samples > 0 && profile.any_convex && !profile.any_concave => {}
3364            _ => continue,
3365        }
3366        let mut star = vec![concave_index, convex_indices[first], convex_indices[second]];
3367        star.sort_unstable();
3368        stage_ids.push(pad.id);
3369        members.push(star);
3370    }
3371    let mut stage_names = names_of(&convex_indices);
3372    stage_names.extend(members[convex_count..].iter().map(|star| corner_face_name(edge_names, name, star)));
3373    let stage_corner_name = |adjacent: &[usize]| {
3374        let mut flat: Vec<usize> = adjacent.iter().flat_map(|&slot| members[slot].iter().copied()).collect();
3375        flat.sort_unstable();
3376        flat.dedup();
3377        corner_face_name(edge_names, name, &flat)
3378    };
3379    let mut built = concave_first_network_stage(&staged, &stage_ids, &stage_names, &stage_corner_name, radius, wrap_concave)?;
3380    for face in built.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
3381        // The stage name, and anything a stage appended to it, back to the
3382        // pad's own name.
3383        let Some(tail) = face.name.as_deref().and_then(|value| value.strip_prefix(CONCAVE_FIRST_PAD)) else {
3384            continue;
3385        };
3386        let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
3387        let Ok(index) = tail[..digits].parse::<usize>() else {
3388            return None;
3389        };
3390        let rest = tail[digits..].to_string();
3391        face.name = per_edge_name(edge_names, name, index).map(|own| format!("{own}{rest}"));
3392    }
3393    if debug {
3394        eprintln!(
3395            "concave-first stages: {} concave, {} convex and {} star pad edge(s) built",
3396            concave_ids.len(),
3397            convex_count,
3398            stage_ids.len() - convex_count
3399        );
3400    }
3401    Some(built)
3402}
3403
3404fn fillet_edges_group_lanes(
3405    solid: &BrepSolid,
3406    edge_points: &[Vec3],
3407    edge_names: Option<&[String]>,
3408    radius: f64,
3409    chamfer: bool,
3410    name: Option<&str>,
3411    mut memo: Option<&mut ComponentMemo>,
3412    wrap_concave: bool,
3413) -> Result<GroupBody, KernelRefusal> {
3414    use rustc_hash::FxHashSet as HashSet;
3415
3416    // Fuse-first operand heal (Lever A) before the multi-edge surgery: snap the
3417    // input's near-coincident / off-plane vertices (e.g. a revolve pole apex
3418    // sitting a few microns off the axis) to exact and re-anchor incident
3419    // edges.  The selected edges are resolved geometrically below, so a
3420    // sub-heal_tol vertex move never changes which edges are picked; a clean
3421    // input is left byte-identical.
3422    let heal = crate::blend::BlendTimer::start("timing.heal_operands_ms");
3423    let mut healed_input = solid.clone();
3424    let heal_policy = crate::KernelTolerances::for_solid(&healed_input, 1e-7);
3425    crate::heal::heal_operands(&mut healed_input, &heal_policy)?;
3426    let solid = &healed_input;
3427    heal.stop();
3428    let group_analysis = crate::blend::BlendTimer::start("timing.group_analysis_ms");
3429
3430    // 1. Detect convex corners from the ORIGINAL solid: a point that is an
3431    //    endpoint of >=3 of the selected edges (a cube/prism-style vertex).
3432    let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
3433    // The extent each selected edge has BEFORE any blend trims it, so the
3434    // sequential build can run every cutter through the shared corners.
3435    let mut original_extents: Vec<(Vec3, Vec3)> = Vec::with_capacity(edge_points.len());
3436    let mut selected_edge_ids: Vec<u64> = Vec::with_capacity(edge_points.len());
3437    for (i, point) in edge_points.iter().enumerate() {
3438        let edge_id = resolve_edge_by_point(solid, *point)?;
3439        let edge = solid
3440            .edges
3441            .iter()
3442            .find(|e| e.id == edge_id)
3443            .ok_or_else(|| {
3444                KernelRefusal::internal(
3445                    KernelStage::Collect,
3446                    "resolved_edge",
3447                    "fillet_edges: resolved edge vanished",
3448                )
3449            })?;
3450        let (start, end) = (
3451            edge.curve
3452                .evaluate(edge.t0)
3453                .or_refuse(KernelStage::Collect, "edge_start")?,
3454            edge.curve
3455                .evaluate(edge.t1)
3456                .or_refuse(KernelStage::Collect, "edge_end")?,
3457        );
3458        endpoints.push((start, i));
3459        endpoints.push((end, i));
3460        original_extents.push((start, end));
3461        selected_edge_ids.push(edge_id);
3462    }
3463    let mut corners: Vec<Vec3> = Vec::new();
3464    // The selected-edge INPUT INDICES meeting at each star corner (parallel to
3465    // `corners`), sorted — used to name the corner patch after its adjacent
3466    // edges (`{fid}:BLEND:CORNER:{e_a}+{e_b}+…`), UNIQUE per corner because no
3467    // two distinct corners share the same set of >=3 selected edges.
3468    let mut corner_edges: Vec<Vec<usize>> = Vec::new();
3469    let mut chain_corner_count = 0usize;
3470    let mut chain_corners: Vec<(Vec3, [usize; 2])> = Vec::new();
3471    let mut used = vec![false; endpoints.len()];
3472    for i in 0..endpoints.len() {
3473        if used[i] {
3474            continue;
3475        }
3476        used[i] = true;
3477        let mut edges_here: HashSet<usize> = HashSet::default();
3478        edges_here.insert(endpoints[i].1);
3479        for j in (i + 1)..endpoints.len() {
3480            if used[j] {
3481                continue;
3482            }
3483            if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
3484                used[j] = true;
3485                edges_here.insert(endpoints[j].1);
3486            }
3487        }
3488        if edges_here.len() >= 3 {
3489            corners.push(endpoints[i].0);
3490            let mut adjacent: Vec<usize> = edges_here.into_iter().collect();
3491            adjacent.sort_unstable();
3492            corner_edges.push(adjacent);
3493        } else if edges_here.len() == 2 {
3494            chain_corner_count += 1;
3495            let mut adjacent = edges_here.into_iter().collect::<Vec<_>>();
3496            adjacent.sort_unstable();
3497            chain_corners.push((endpoints[i].0, [adjacent[0], adjacent[1]]));
3498        }
3499    }
3500
3501    // A FACE selection may contain several disconnected boundary components
3502    // (the common example is an outer perimeter plus a circular hole rim).
3503    // Miter composition is only meaningful inside one connected edge graph.
3504    // Feeding every component into the same INTERSECT/UNION combines multiple
3505    // independently filleted copies of otherwise untouched support faces; the
3506    // boolean then imprints those coincident copies and can leave redundant
3507    // seams (the reported through-hole cylinder split into three faces).
3508    //
3509    // Partition by shared original endpoints and process components in input
3510    // order.  Each recursive call sees one connected component, so it follows
3511    // the existing miter/sequential path without recursion cycling.  Distinct
3512    // components are then composed sequentially on the evolving solid.
3513    let mut component_of = vec![usize::MAX; edge_points.len()];
3514    let mut components: Vec<Vec<usize>> = Vec::new();
3515    for seed in 0..edge_points.len() {
3516        if component_of[seed] != usize::MAX {
3517            continue;
3518        }
3519        let component_index = components.len();
3520        component_of[seed] = component_index;
3521        let mut component = vec![seed];
3522        let mut cursor = 0;
3523        while cursor < component.len() {
3524            let current = component[cursor];
3525            cursor += 1;
3526            for candidate in 0..edge_points.len() {
3527                if component_of[candidate] != usize::MAX {
3528                    continue;
3529                }
3530                let connected = [original_extents[current].0, original_extents[current].1]
3531                    .into_iter()
3532                    .any(|a| {
3533                        [original_extents[candidate].0, original_extents[candidate].1]
3534                            .into_iter()
3535                            .any(|b| a.sub(b).length() < 1e-6)
3536                    });
3537                if connected {
3538                    component_of[candidate] = component_index;
3539                    component.push(candidate);
3540                }
3541            }
3542        }
3543        component.sort_unstable();
3544        components.push(component);
3545    }
3546    group_analysis.stop();
3547    if components.len() > 1 {
3548        let mut separated = solid.clone();
3549        // The chain continues the memo's prefix, so a component composed
3550        // inside another's build keys under the whole path to it.
3551        let mut chain: Vec<ComponentKey> = memo.as_deref().map(|memo| memo.prefix.clone()).unwrap_or_default();
3552        chain.reserve(components.len());
3553        for component in components {
3554            let points = component
3555                .iter()
3556                .map(|index| edge_points[*index])
3557                .collect::<Vec<_>>();
3558            let names = edge_names.map(|all| {
3559                component
3560                    .iter()
3561                    .map(|index| all[*index].clone())
3562                    .collect::<Vec<_>>()
3563            });
3564            let Some(memo) = memo.as_deref_mut() else {
3565                separated = fillet_edges_group_with_corner_policy(
3566                    &separated,
3567                    &points,
3568                    names.as_deref(),
3569                    radius,
3570                    chamfer,
3571                    name,
3572                    None,
3573                    wrap_concave,
3574                    false,
3575                )?;
3576                continue;
3577            };
3578            let bits = points.iter().map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
3579            chain.push((bits.collect(), names.clone()));
3580            let built = match memo.built.get(&chain) {
3581                Some(built) => built.clone(),
3582                None => {
3583                    // The component builds on the body the chain before it
3584                    // composed: its own cutter steps key under that chain.
3585                    let outer_prefix = std::mem::replace(&mut memo.prefix, chain[..chain.len() - 1].to_vec());
3586                    let built = fillet_edges_group_with_corner_policy(
3587                        &separated,
3588                        &points,
3589                        names.as_deref(),
3590                        radius,
3591                        chamfer,
3592                        name,
3593                        Some(&mut *memo),
3594                        wrap_concave,
3595                        false,
3596                    );
3597                    memo.prefix = outer_prefix;
3598                    memo.built.insert(chain.clone(), built.clone());
3599                    built
3600                }
3601            };
3602            separated = built?;
3603        }
3604        return Ok(GroupBody { body: separated, bowtie_clean: false });
3605    }
3606
3607    // 2a. The stripe network (blend/network.rs) is the lane for EVERY
3608    //     selection: each stripe is marched against THIS solid, each shared
3609    //     vertex is solved before anything is cut — a star closed by a patch
3610    //     of the corner ball, a two-edge corner by the seam between the two
3611    //     blends, a re-entrant corner by a horn torus, a tangent pair by a
3612    //     flush join, an unselected tangent continuation by a cap — and
3613    //     nothing is subtracted, so no cutter can overshoot into a neighbour
3614    //     and no leftover cap has to be identified afterwards.  It refuses
3615    //     BY NAME on what it does not yet construct (mixed-convexity corners,
3616    //     no-common-ball stars, pinched edges), and those fall through to the
3617    //     cutter composition below.
3618    //
3619    //     A CLOSED edge is one of those refusals and it has an answer the
3620    //     network is simply not the lane for: a closed rim has no corner to
3621    //     share, so `blend_star_network` says "edge N is closed and has no
3622    //     corner to share" and the composition took it.  `blend_closed_edge`
3623    //     builds exactly that case and the single-edge ladder in `tool.rs`
3624    //     has always tried it first — but this function reached only the
3625    //     network, so a closed rim inside a GROUP went to a cutter that the
3626    //     same rim selected on its own never saw.  A bored hole's rim splits
3627    //     out as its own one-edge component (see the component partition
3628    //     above), so that was every hole rim chamfered as part of a face
3629    //     selection.  Try it here too, under the same acceptance the network
3630    //     result gets, and under the same `BREP_NO_NETWORK` A/B.
3631    if std::env::var("BREP_NO_NETWORK").is_err() {
3632        if selected_edge_ids.len() == 1 {
3633            let edge_id = selected_edge_ids[0];
3634            let closed = solid
3635                .edges
3636                .iter()
3637                .find(|edge| edge.id == edge_id)
3638                .is_some_and(|edge| edge.start_vertex_id == edge.end_vertex_id);
3639            if closed {
3640                let rim_name = per_edge_name(edge_names, name, 0);
3641                match crate::blend::blend_closed_edge(solid, edge_id, radius, chamfer, rim_name) {
3642                    Ok(mut rim) => {
3643                        let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3644                        let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3645                        let healed = heal_edge_vertex_gaps(&mut rim, radius);
3646                        heal.stop();
3647                        // A trim the surgery ran outside its planar carrier's
3648                        // chart is a wrong body the three checks below all pass
3649                        // (`crate::blend::fit_planar_charts_to_trims`), so the
3650                        // carrier is widened here, after the heal has settled
3651                        // the edges the trims are rebuilt from and before the
3652                        // bowtie scan reads them.  Its refusals are TERMINAL:
3653                        // the composition is not a second opinion on a body
3654                        // whose trims left their carrier.
3655                        let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3656                        crate::blend::fit_planar_charts_to_trims(solid, &mut rim)?;
3657                        charts.stop();
3658                        let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3659                        let issues = rim.validate_memoised();
3660                        validate.stop();
3661                        let interference =
3662                            check_blend_interference(solid, &rim, &selected_edge_ids, entry);
3663                        let bowtie = check_loop_self_crossings(&rim, entry).and_then(|()| check_blend_wall_loops(&rim, entry));
3664                        if healed.is_ok()
3665                            && issues.is_empty()
3666                            && interference.is_ok()
3667                            && bowtie.is_ok()
3668                        {
3669                            return Ok(GroupBody { body: rim, bowtie_clean: true });
3670                        }
3671                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3672                            eprintln!(
3673                                "closed-rim result rejected: heal={healed:?} issues={issues:?} \
3674                                 interference={interference:?} bowtie={bowtie:?}"
3675                            );
3676                        }
3677                    }
3678                    Err(refusal) => {
3679                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3680                            eprintln!("closed-rim refused: {refusal}");
3681                        }
3682                    }
3683                }
3684            }
3685        }
3686        let network_names: Vec<Option<String>> = (0..edge_points.len())
3687            .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
3688            .collect();
3689        let network_corner_name =
3690            |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
3691        // BREP lane L: begin lcount229_knot_aware_group_network_20261016 A
3692        // support pcurve off the floor ends the group's network here, and
3693        // the ladder would go on to the cutter composition: re-run the
3694        // network ONCE with the knot-aware support fit; a re-run that also
3695        // fails keeps the first refusal.
3696        let group_network = || {
3697            crate::blend::blend_star_network_with_corner_policy(
3698                solid,
3699                &selected_edge_ids,
3700                radius,
3701                chamfer,
3702                &network_names,
3703                &network_corner_name,
3704                wrap_concave,
3705            )
3706        };
3707        let network_result = group_network().or_else(|first| {
3708            if crate::blend::is_pcurve_floor_refusal(&first) {
3709                crate::blend::with_pcurve_knot_retry(group_network).map_err(|_| first)
3710            } else {
3711                Err(first)
3712            }
3713        });
3714        // BREP lane L: end lcount229_knot_aware_group_network_20261016
3715        // The network's result under its acceptance: `Ok(Some)` accepted,
3716        // `Ok(None)` rejected (the ladder goes on), `Err` terminal.
3717        let accept_network = |mut network: BrepSolid, built_radius: f64| -> Result<Option<GroupBody>, KernelRefusal> {
3718                // Fail-safe like the rest of the ladder: a heal or validation
3719                // problem in the network result falls through to the cutter,
3720                // it does not fail the group.  So does an UNTRIMMED result: the
3721                // network re-trims only each stripe's two mates, and
3722                // `check_blend_interference` is what notices a third face
3723                // crossing the swept volume -- `validate` cannot, because a
3724                // self-intersecting solid is still a watertight one.
3725                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3726                let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3727                let healed = heal_edge_vertex_gaps(&mut network, built_radius);
3728                heal.stop();
3729                // See the closed-rim lane above: widen a planar carrier the
3730                // surgery overran, or refuse — terminally — rather than fall
3731                // through to a composition that cannot answer that question.
3732                let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3733                crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
3734                charts.stop();
3735                let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3736                let issues = network.validate_memoised();
3737                validate.stop();
3738                let interference =
3739                    check_blend_interference(solid, &network, &selected_edge_ids, entry);
3740                // And the fourth question, which the other three all pass: does
3741                // any face of the result have a loop that crosses ITSELF? A
3742                // wall whose rail ran off its own face comes back as a bowtie,
3743                // and a bowtie is watertight, incident and connected.
3744                let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
3745                if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3746                    return Ok(Some(GroupBody { body: network, bowtie_clean: true }));
3747                }
3748                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3749                    eprintln!(
3750                        "network result rejected: heal={healed:?} issues={issues:?} \
3751                         interference={interference:?} bowtie={bowtie:?}"
3752                    );
3753                    dump_loops_debug("INPUT", solid);
3754                    dump_loops_debug("RESULT", &network);
3755                }
3756                Ok(None)
3757        };
3758        match network_result {
3759            Ok(network) => {
3760                if let Some(body) = accept_network(network, radius)? {
3761                    return Ok(body);
3762                }
3763            }
3764            Err(refusal) => {
3765                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3766                    eprintln!("network refused: {refusal}");
3767                }
3768                // A mixed-convexity refusal over a selection whose concave
3769                // edges also miter each other: build them first, then the
3770                // convex edges (`concave_first_stages_on`).
3771                let mixed = matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what } if what == "mixed_convexity");
3772                if !chamfer && mixed && concave_first_stages_on() {
3773                    if let Some(body) = concave_first_stages(
3774                        solid, edge_points, edge_names, &selected_edge_ids, radius, name, wrap_concave,
3775                    ) {
3776                        return Ok(GroupBody { body, bowtie_clean: true });
3777                    }
3778                }
3779                // A stripe whose TAPER to a cusp reaches its full radius only
3780                // inside the corner setback at its other end has no constant
3781                // run at all (report 80c5d9d1's F10, 2026-10-24: r 1 on the two
3782                // straight edges of a sliver at most 2 wide within 0.9 of its
3783                // square corner). The round is built at the largest smaller
3784                // radius whose taper clears the setback, and says so, as the
3785                // relief says it over a whole rim. Before 2026-10-26 the group
3786                // fell through to the cutter composition, which closed each
3787                // round on a web and a cap under the neighbouring blend (an
3788                // undercut) in 9 minutes.
3789                let pinched_taper = matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what }
3790                    if what == crate::blend::STRIPE_PINCH_TAPER_WHAT);
3791                if !chamfer && pinched_taper && crate::blend::relief::radius_relief_on() {
3792                    let labels: Vec<String> =
3793                        (0..edge_points.len()).map(|index| selection_label(index, edge_points, edge_names, name)).collect();
3794                    for step in 1..=10u32 {
3795                        let reduced = radius * (1.0 - 0.05 * f64::from(step));
3796                        let built = crate::blend::blend_star_network_with_corner_policy(
3797                            solid, &selected_edge_ids, reduced, chamfer, &network_names, &network_corner_name, wrap_concave,
3798                        );
3799                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3800                            eprintln!(
3801                                "taper pinch ladder: r {reduced:.4} -> {}",
3802                                match &built {
3803                                    Ok(_) => "built".to_string(),
3804                                    Err(error) => format!("refused: {error}"),
3805                                }
3806                            );
3807                        }
3808                        match built {
3809                            Ok(network) => {
3810                                let Some(body) = accept_network(network, reduced)? else { break };
3811                                crate::blend::record_blend_note(format!(
3812                                    "radius reduced over the whole of {} to {reduced:.4}: at r {radius} the round tapering to \
3813                                     its tip reaches the full radius only inside the corner setback at its other end, so \
3814                                     r {radius} is reached nowhere",
3815                                    labels.join(", ")
3816                                ));
3817                                return Ok(body);
3818                            }
3819                            Err(again) if matches!(&again.class, crate::RefusalClass::UnsupportedGeometry { what }
3820                                if what == crate::blend::STRIPE_PINCH_TAPER_WHAT) => continue,
3821                            Err(_) => break,
3822                        }
3823                    }
3824                }
3825                // Independent stripe cutters cannot close a corner whose ball
3826                // exceeds the canal footprint. Preserve the requested radius
3827                // and its named refusal instead of searching partial selections.
3828                if matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what }
3829                    if what == "canal_footprint_bound") || crate::blend::is_ball_does_not_fit(&refusal) {
3830                    return Err(refusal);
3831                }
3832                // The runout composition reads the ring's own classification
3833                // back when the ring stage falls through to the cutter and
3834                // that refuses too (`LAST_NETWORK_REFUSAL`).
3835                LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = Some(refusal.clone()));
3836                if crate::blend::is_wall_fold(&refusal) {
3837                    GROUP_NETWORK_FOLD.with(|fold| *fold.borrow_mut() = Some(refusal.clone()));
3838                }
3839                // A refusal that is not a fold where the ball does not fit
3840                // (report 37e16630 at r 1.0, a ball the size of the round it
3841                // rides: its centre curve collapses to a point and the station
3842                // Newton is singular) is the fold the relief answers, not a
3843                // question for the composition, which took 143 s over it.
3844                if !chamfer && !crate::blend::is_wall_fold(&refusal) && crate::blend::relief::radius_relief_on() {
3845                    let started = web_time::Instant::now();
3846                    let misfit = crate::blend::relief::first_misfit(solid, &selected_edge_ids, radius);
3847                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3848                        eprintln!("radius relief: misfit probe {misfit:?} in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
3849                    }
3850                    if let Some((edge_id, least)) = misfit {
3851                        return Err(crate::blend::relief::misfit_fold(edge_id, least, radius, &refusal));
3852                    }
3853                }
3854                // The fail-safe above is for a refusal that says "not this
3855                // lane".  A marched fit that left its carriers does not say
3856                // that, and the cutter's answer to the same selection is not a
3857                // second opinion on it: on the notched cap's stuck connector
3858                // the composition reads 1724.506048919, +1.81e-2 against the
3859                // closed form, and it VALIDATES.  A refusal that falls through
3860                // to a validating wrong solid is not a refusal.
3861                //
3862                // Not every WALL FOLD, though the single-edge tool reads them all
3863                // as terminal (`is_terminal_blend_refusal`): a fold of the lens
3864                // between the rails is one the composition's cutter carves
3865                // (`inbox_20260902_corner_torus_collar_fillet::each_collar_has_its_own_fold_threshold`,
3866                // the r 2.1 collar at fold factor 1.036). One that reaches a
3867                // RAIL is not: the ball pokes out through the face it rides,
3868                // there is no lens to carve, and every cutter sweeps the same
3869                // envelope. Until 2026-10-21 the group fell through on that too:
3870                // report 37e16630's end face at r 1.7 around an r 1 round on its
3871                // outline ran the composition and its subset search for over 20
3872                // minutes. A lens fold the composition cannot rescue either is
3873                // answered by the fold (`fillet_edges_group_unchecked`).
3874                //
3875                // A blend stopping within a sliver of its face's width that
3876                // cannot be snapped onto the far edge without opening the shell
3877                // is terminal for the same reason: the SIZE is the question
3878                // (`blend::CONSUMED_SNAP_UNSOUND`), and the composition's tool
3879                // cut a sliver short of an edge leaves the sliver no lane keeps.
3880                //
3881                // And a FULL-WIDTH corner the network cannot collapse soundly
3882                // (`blend::RAIL_COLLAPSE_UNSUPPORTED`,
3883                // `blend::FULL_WIDTH_COLLAPSE_UNSOUND`): the composition's answer
3884                // to a full-width corner was measured wrong — a 5F/8E/5V miter
3885                // 8.0e-4 off its closed form at 1e-5 short of the width, and the
3886                // picture-frame corner at a full-width chamfer star.
3887                //
3888                // And a trim that left its planar carrier's chart
3889                // (`blend::PLANAR_CHART_EDGE_OFF_PLANE`,
3890                // `blend::PLANAR_CHART_WIDEN_UNSOUND`): the clamped body the
3891                // composition would answer with is the defect being refused.
3892                // A tangential end whose taper could not be planned also has
3893                // no supported closure for cutter composition to recover.
3894                if crate::blend::is_rail_fold(&refusal)
3895                    || crate::blend::is_marched_fit_off_carriers(&refusal)
3896                    || crate::blend::is_consumed_snap(&refusal)
3897                    || crate::blend::is_rail_collapse(&refusal)
3898                    || crate::blend::is_full_width_collapse(&refusal)
3899                    || crate::blend::is_planar_chart_refusal(&refusal)
3900                    || crate::blend::is_miter_support_overrun(&refusal)
3901                    || crate::blend::is_tangential_transverse_end(&refusal)
3902                {
3903                    return Err(refusal);
3904                }
3905            }
3906        }
3907    }
3908
3909    // An edge whose ball reaches its support only by rolling over a tangent
3910    // neighbour (`analyze::rollover_only_refusal`): the composition's tool
3911    // rides the mates' own carriers past the tangent edge and fills over air
3912    // (lCount_409 at r 2: +1.096 against the quadrature's 1103.315046), so
3913    // the reach refusal the unsigned check gave stands.
3914    if let Some(refusal) = super::analyze::rollover_only_refusal(&selected_edge_ids) {
3915        return Err(refusal);
3916    }
3917    CUTTER_COMPOSITIONS.with(|count| count.set(count.get() + 1));
3918    crate::blend::record_count("count.cutter_fallback", 1);
3919    let _cutter = crate::blend::BlendTimer::start("timing.cutter_ms");
3920    // 2. Build the blends.
3921    //
3922    //    CHAIN corners (§6.9.6 — exactly TWO selected edges share a vertex):
3923    //    the sequential build truncates the later blend where it runs into the
3924    //    earlier one and closes it with a flat bulkhead across the fillet
3925    //    channel — a hard step, not a transition.  For selections containing
3926    //    chain corners, blend each edge FULL-LENGTH on the ORIGINAL solid and
3927    //    INTERSECT the per-edge results instead: the removal volumes union, so
3928    //    adjacent blends run through the shared corner and trim each other
3929    //    along their intersection curve — the standard MITER corner, tangent
3930    //    to the shared face at the seam's tangency end.  Non-adjacent edges
3931    //    are unaffected (their removals are disjoint, intersection ≡
3932    //    sequential).
3933    //
3934    //    Selections without chain corners keep the sequential build unchanged
3935    //    (star corners are rounded in step 3 against exactly the sequential
3936    //    geometry round_convex_corner was built for).
3937    //    CONVEXITY GUARD: a convex blend REMOVES material (fillet = orig −
3938    //    cut), a concave blend ADDS it (orig + pad).  Full-length blends
3939    //    combine as orig − ∪cuts + ∪pads, so the per-edge results compose by
3940    //    INTERSECTION when every edge is convex and by UNION when every edge
3941    //    is concave; a mixed selection has no single composition and falls
3942    //    back to the sequential build.
3943    // Fillet stars keep the sequential topology required by their sphere
3944    // patches. Chamfer stars have no subsequent corner patch: compose their
3945    // full-length removals too, so all bevel planes meet at the corner.
3946    let miter_operation = if (chain_corner_count > 0 || !corners.is_empty())
3947        && (chamfer || corners.is_empty())
3948    {
3949        let mut any_convex = false;
3950        let mut any_concave = false;
3951        for point in edge_points {
3952            // Convexity is a DIHEDRAL property, so it is read from the general
3953            // scan (`scan_dihedral`) — the same one `check_mixed_concavity`
3954            // has already run over every selected edge.  `analyze_edge` used
3955            // to answer here and it ALSO refuses an edge the EXACT CUTTER
3956            // cannot build: a straight edge whose mates are not both planes,
3957            // a circular one whose mates do not share its axis.  Reading that
3958            // refusal as "unknown convexity" dropped the §6.9.6 miter for
3959            // every selection touching a curved carrier — the groove rim of a
3960            // bored box, say — and the sequential build then left a bulkhead
3961            // face standing in the shared corner (the 2026-09-10 "chamfer
3962            // produced a spurious face" report).
3963            match resolve_edge_by_point(solid, *point)
3964                .and_then(|edge_id| super::analyze::scan_dihedral(solid, edge_id))
3965            {
3966                // A mixed edge has no single composition either; it takes the
3967                // `_ => None` arm below through both flags.
3968                Ok(profile) if profile.samples > 0 && !profile.is_mixed() => {
3969                    any_convex |= profile.any_convex;
3970                    any_concave |= profile.any_concave;
3971                }
3972                // Unknown edge class: let the sequential path produce its own
3973                // (more specific) error or result.
3974                _ => {
3975                    any_convex = true;
3976                    any_concave = true;
3977                    break;
3978                }
3979            }
3980        }
3981        match (any_convex, any_concave) {
3982            (true, false) => Some(crate::BooleanOperation::Intersect),
3983            (false, true) => Some(crate::BooleanOperation::Union),
3984            _ => None,
3985        }
3986    } else {
3987        None
3988    };
3989
3990    // Fillet/chamfer each edge in turn, resolving its point on the evolving
3991    // solid (ids shift as earlier fillets rewrite topology; the midpoint of an
3992    // edge is untouched by the corner surgery of the others).  This is the
3993    // baseline build used directly for non-miter selections AND as the
3994    // fallback when the miter composition below cannot reassemble.
3995    // The composition's per-edge lane: cutter-first ONLY when a corner
3996    // closure will run afterwards and read cutter-shaped topology (a star or
3997    // a chain corner).  A selection with no shared vertex — a lone closed
3998    // rim, a lone chamfer, disconnected edges — has no such closure, so each
3999    // edge gets the march first there too.
4000    let composition_lane = if corners.is_empty() && chain_corner_count == 0 {
4001        Lane::GeneralFirst
4002    } else {
4003        Lane::CutterFirst
4004    };
4005    // The order the sequential build blends the selection in: the input
4006    // order, except that a CONCAVE edge ending at a star corner goes before
4007    // every convex edge (`sequential_build_order`). The §6.9.7 torus-sector
4008    // closure of a re-entrant vertex whose concave edge is selected too
4009    // (`round_mixed_concave_corner`) reads the concave blend's tangency
4010    // vertices off the convex cap cutters, so it exists only when the concave
4011    // edge was cut FIRST; a user who picks the keyway's rim and then its
4012    // inner corners (the 2026-10-13 sprocket report) got flat caps at both
4013    // corners from the input order, and the closure's own closed form from
4014    // this one. Every other selection keeps its input order, byte for byte.
4015    let concave_at_star = concave_star_edges(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4016    // And at a star corner whose edges the ladder answers with DIFFERENT
4017    // cutters, the marched edges go before the exact ones and the revolved
4018    // cutters last (`mixed_star_class_ranks`): the 2026-10-13 sprocket
4019    // report whose slit walls were selected as faces.
4020    let class_ranks = mixed_star_class_ranks(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4021    let sequential_order = sequential_build_order(edge_points.len(), &concave_at_star, &class_ranks);
4022    // And the corners close in the same precedence: a star with a concave
4023    // edge (the torus sector) before the convex stars, which on the report's
4024    // keyway share a 3.8-long rim edge with it — the convex star's surgery
4025    // read an open edge when it ran first (measured 2026-10-13), and closes
4026    // cleanly after the sector has trimmed that rim.
4027    let (corners, corner_edges) = corners_concave_first(corners, corner_edges, &concave_at_star);
4028    let mut build_sequential = || -> Result<BrepSolid, KernelRefusal> {
4029        let mut sequential = solid.clone();
4030        // The prefix chain of this build, for the subset search's memo (see
4031        // `ComponentMemo::sequential`); unused without one.
4032        let mut chain: Vec<SequentialKey> = Vec::with_capacity(sequential_order.len());
4033        for &index in &sequential_order {
4034            let point = &edge_points[index];
4035            let edge_id = resolve_edge_by_point(&sequential, *point)?;
4036            // Earlier cutters in this loop TRIM the edges that share a corner
4037            // with them; extend this cutter back over what they took so the
4038            // two removal volumes union through the corner (§6.9.6 miter)
4039            // instead of leaving a wedge of material standing behind a flush
4040            // end cap.  Untouched edges get a zero pad and the historical
4041            // flush cutter.
4042            let ends = tool_ends_to_original_extent(
4043                &sequential,
4044                edge_id,
4045                radius,
4046                original_extents[index],
4047                if chamfer { &[] } else { &corners },
4048            );
4049            // This edge's blend wall carries the name of THIS input edge
4050            // (`edge_names[index]`); a smooth chain that engulfs several edges
4051            // is named after the FIRST such input edge processed here (input
4052            // order), the chain's representative.
4053            let edge_name = per_edge_name(edge_names, name, index);
4054            if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4055                eprintln!(
4056                    "sequential build: selection #{index} {} is edge {edge_id} on the evolving body (ends {ends:?}, {composition_lane:?})",
4057                    selection_label(index, edge_points, edge_names, name)
4058                );
4059            }
4060            // Every step is a deterministic function of the body it starts
4061            // from and these four inputs, and the body is itself the chain of
4062            // the steps before it: a chain the search already composed on
4063            // this solid is answered from the memo, refusals included.
4064            chain.push((
4065                [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()],
4066                edge_name.map(str::to_string),
4067                ends.key_bits(),
4068                u8::from(composition_lane == Lane::CutterFirst),
4069            ));
4070            if let Some(memo) = memo.as_deref_mut() {
4071                let key = (memo.prefix.clone(), chain.clone());
4072                let hit = memo.sequential.get(&key);
4073                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4074                    eprintln!(
4075                        "sequential memo: {} components before, step {} {} ({} chains stored)",
4076                        memo.prefix.len(),
4077                        chain.len(),
4078                        if hit.is_some() { "HIT" } else { "miss" },
4079                        memo.sequential.len(),
4080                    );
4081                }
4082                if let Some(built) = hit {
4083                    crate::blend::record_count("count.sequential.memo_hits", 1);
4084                    sequential = built.clone()?;
4085                    continue;
4086                }
4087            }
4088            crate::blend::record_count("count.sequential.steps_built", 1);
4089            let built = fillet_or_chamfer(
4090                &sequential,
4091                edge_id,
4092                radius,
4093                chamfer,
4094                edge_name,
4095                ends,
4096                composition_lane,
4097            );
4098            if let Some(memo) = memo.as_deref_mut() {
4099                memo.sequential.insert((memo.prefix.clone(), chain.clone()), built.clone());
4100            }
4101            sequential = built?;
4102        }
4103        Ok(sequential)
4104    };
4105
4106    let mut result = if let Some(operation) = miter_operation {
4107        // The per-edge results still carry their cutters' standing scaffold,
4108        // which the group settles once its corners are closed. A scaffold face
4109        // merged here would hand its tag to whatever it merged with.
4110        let options = crate::BooleanOptions {
4111            keep_unmerged_name_substrs: vec![CUTTER_SCAFFOLD_NAME.to_string()],
4112            ..crate::BooleanOptions::default()
4113        };
4114        let mut combined: Result<Option<BrepSolid>, KernelRefusal> = Ok(None);
4115        // The units the miter composes: one per selected edge, except that
4116        // edges joined at a TANGENT chain corner blend as one unit through
4117        // this same group build (see `miter_tangent_units`).
4118        let units = miter_tangent_units(solid, &selected_edge_ids, &chain_corners, edge_points.len());
4119        for unit in &units {
4120            let index = unit[0];
4121            let point = &edge_points[index];
4122            let blended = if unit.len() > 1 {
4123                let points = unit.iter().map(|&member| edge_points[member]).collect::<Vec<_>>();
4124                let names = edge_names.map(|all| unit.iter().map(|&member| all[member].clone()).collect::<Vec<_>>());
4125                fillet_edges_group_with_corner_policy(
4126                    solid,
4127                    &points,
4128                    names.as_deref(),
4129                    radius,
4130                    chamfer,
4131                    name,
4132                    None,
4133                    wrap_concave,
4134                    false,
4135                )?
4136            } else {
4137                let edge_id = resolve_edge_by_point(solid, *point)?;
4138                let edge_name = per_edge_name(edge_names, name, index);
4139                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
4140                check_mixed_concavity(solid, edge_id, entry)?;
4141                check_support_extent(solid, edge_id, radius, entry)?;
4142                fillet_or_chamfer(
4143                    solid,
4144                    edge_id,
4145                    radius,
4146                    chamfer,
4147                    edge_name,
4148                    ToolEnds::default(),
4149                    Lane::CutterFirst,
4150                )?
4151            };
4152            combined = match combined {
4153                Err(e) => Err(e),
4154                Ok(None) => Ok(Some(blended)),
4155                Ok(Some(previous)) => {
4156                    crate::boolean_operation(&previous, &blended, operation, &options)
4157                        .map(Some)
4158                        .map_err(|error| {
4159                            // The boolean's own class survives the wrap.
4160                            error.with_message(|error| {
4161                                format!("fillet_edges: chain-corner miter composition failed: {error}")
4162                            })
4163                        })
4164                }
4165            };
4166            if combined.is_err() {
4167                break;
4168            }
4169        }
4170        // A §6.9.6 miter (per-edge blends intersected/unioned through the
4171        // shared chain corners) can fail to reassemble on faces whose
4172        // fragmented boundary does not close — e.g. a planar cap whose ENTIRE
4173        // perimeter is selected, where fragment_face reports an "incomplete
4174        // run".  Rather than let `fillet_edges` silently DROP a selected edge
4175        // to recover a valid subset (the reported defect: not every edge of
4176        // the face gets a fillet), fall back to the sequential build, which
4177        // blends EVERY selected edge (chain corners get a flat bulkhead
4178        // instead of a miter).  Only if that also fails to produce a valid
4179        // solid do we surface the miter error so the caller's
4180        // maximal-valid-subset search can still run.
4181        match combined {
4182            Ok(Some(mut mitered)) => {
4183                drop_slit_shells(&mut mitered);
4184                mitered
4185            }
4186            Ok(None) => {
4187                return Err(KernelRefusal::input(
4188                    KernelStage::Collect,
4189                    "miter_selection",
4190                    "fillet_edges: no edges selected",
4191                ))
4192            }
4193            Err(miter_err) => match build_sequential() {
4194                Ok(seq) if seq.validate().is_empty() => seq,
4195                _ => return Err(miter_err),
4196            },
4197        }
4198    } else {
4199        build_sequential()?
4200    };
4201
4202    // A re-entrant vertex of a selected face perimeter has two selected,
4203    // convex cap-wall edges and one UNSELECTED concave wall-wall edge.  The
4204    // two cutter volumes only touch there, so the boolean miter leaves a
4205    // triangular planar end-cap instead of carrying the rolling ball around
4206    // the corner.  Close that exact orthogonal class with its horn-torus
4207    // sector (major radius = minor radius = fillet radius).
4208    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4209    let mut open_mixed_corners: Vec<(Vec3, [u64; 2], Option<String>)> = Vec::new();
4210    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4211    if !chamfer {
4212        for (corner, adjacent) in &chain_corners {
4213            let has_concave_unselected_edge = solid.edges.iter().any(|edge| {
4214                if selected_edge_ids.contains(&edge.id) {
4215                    return false;
4216                }
4217                let Ok(a) = edge.curve.evaluate(edge.t0) else {
4218                    return false;
4219                };
4220                let Ok(b) = edge.curve.evaluate(edge.t1) else {
4221                    return false;
4222                };
4223                (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4224                    && analyze_edge(solid, edge.id, radius)
4225                        .map(|cross| !cross.convex)
4226                        .unwrap_or(false)
4227            });
4228            // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4229            // The OPEN mixed corner (the 2026-10-13 sprocket's keyway floor):
4230            // one selected convex rim, one selected concave vertical and an
4231            // UNSELECTED convex third edge. The rim's cutter ran through the
4232            // concave pad and left a scaffold square and a misplaced
4233            // bulkhead there; the closure is the one-ended runout's body —
4234            // the §6.9.7 torus sector to C5's stop, ended by its cliff
4235            // (`blend/corner/mixed_open.rs`). It reads the SETTLED body (the
4236            // pad's flush end merged into the cap), so the corner is noted
4237            // here and closed after `settle_cutter_scaffold` below.
4238            if !has_concave_unselected_edge {
4239                let convexity = |edge_id: u64| analyze_edge(solid, edge_id, radius).map(|cross| cross.convex).ok();
4240                let selected_pair = [convexity(selected_edge_ids[adjacent[0]]), convexity(selected_edge_ids[adjacent[1]])];
4241                let one_concave = matches!(selected_pair, [Some(true), Some(false)] | [Some(false), Some(true)]);
4242                let has_convex_unselected_edge = solid.edges.iter().any(|edge| {
4243                    if selected_edge_ids.contains(&edge.id) {
4244                        return false;
4245                    }
4246                    let (Ok(a), Ok(b)) = (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1)) else {
4247                        return false;
4248                    };
4249                    (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4250                        && analyze_edge(solid, edge.id, radius).map(|cross| cross.convex).unwrap_or(false)
4251                });
4252                if one_concave && has_convex_unselected_edge {
4253                    open_mixed_corners.push((
4254                        *corner,
4255                        [selected_edge_ids[adjacent[0]], selected_edge_ids[adjacent[1]]],
4256                        corner_face_name(edge_names, name, adjacent),
4257                    ));
4258                }
4259                continue;
4260            }
4261            // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4262            let corner_name = corner_face_name(edge_names, name, adjacent);
4263            if let Ok(rounded) = crate::blend::round_concave_chain_corner(
4264                &result,
4265                solid,
4266                *corner,
4267                [
4268                    selected_edge_ids[adjacent[0]],
4269                    selected_edge_ids[adjacent[1]],
4270                ],
4271                radius,
4272                corner_name.as_deref(),
4273            ) {
4274                result = rounded;
4275            }
4276        }
4277    }
4278
4279    // 3. Round the convex corners (fillets only — chamfers keep sharp
4280    //    vertices).  A corner that cannot be rounded is left as the edge
4281    //    fillets so the group still succeeds.  Each corner patch is named after
4282    //    the selected edges meeting there (`{fid}:BLEND:CORNER:{e_a}+…`) so no
4283    //    two corners collide and the patch stays under the `{fid}:BLEND` prefix.
4284    if !chamfer {
4285        for (ci, corner) in corners.iter().enumerate() {
4286            let corner_name = corner_face_name(edge_names, name, &corner_edges[ci]);
4287            match crate::blend::round_convex_corner(&result, *corner, radius, corner_name.as_deref()) {
4288                Ok(rounded) => result = rounded,
4289                Err(error) => {
4290                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4291                        eprintln!("corner at {corner:?} left as the edge fillets: {error}");
4292                    }
4293                }
4294            }
4295        }
4296    }
4297
4298    // Heal any residual vertex/edge gaps introduced by the corner-rounding
4299    // surgery (the per-edge results are already healed inside fillet_or_chamfer).
4300    heal_edge_vertex_gaps(&mut result, radius)?;
4301    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4302    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4303    let mut body = settle_cutter_scaffold(result);
4304    for (corner, pair, corner_name) in &open_mixed_corners {
4305        match crate::blend::round_mixed_concave_open_corner(&body, solid, *corner, *pair, radius, corner_name.as_deref()) {
4306            Ok(rounded) => body = rounded,
4307            Err(error) => {
4308                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4309                    eprintln!("open mixed corner at {corner:?} left as the composition built it: {error}");
4310                }
4311            }
4312        }
4313    }
4314    Ok(GroupBody { body, bowtie_clean: false })
4315    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4316}
4317
4318/// The selected edges (indices into the selection) that are CONCAVE and end
4319/// at a star corner (`corner_edges`: three or more selected edges at one
4320/// vertex), in input order. Empty for a chamfer, a selection with no star
4321/// corner, one whose star corners carry no concave edge, and one whose
4322/// convexity cannot be read — the cases the composition builds in input
4323/// order, exactly as before.
4324/// Whether the miter composition drops a stray SLIT shell: on unless
4325/// `BREP_FILLET_MITER_DROP_SLIT_SHELLS=0`/`off`.
4326fn drop_slit_shells_on() -> bool {
4327    switch!(live "BREP_FILLET_MITER_DROP_SLIT_SHELLS", true)
4328}
4329
4330/// Remove from a composed miter body every shell beyond the first whose faces
4331/// are all SLITS — each loop runs along each of its edges once forward and
4332/// once back — over edges no other shell uses, then the edges and vertices
4333/// nothing references any more. Returns how many shells went.
4334///
4335/// Such a shell bounds no area and no volume. The 2026-11-07 "fillet fails"
4336/// report's five-edge selection composed to the right body (the volume of
4337/// the same composition on the serialised input, which has one shell) plus
4338/// one face of the hole's floor plane, `Box_NZ_Offset_1_1`, whose single loop
4339/// ran 1.25 out along one edge and straight back; `validate()` accepts it.
4340fn drop_slit_shells(body: &mut BrepSolid) -> usize {
4341    if !drop_slit_shells_on() || body.shells.len() < 2 {
4342        return 0;
4343    }
4344    let mut users: std::collections::HashMap<u64, std::collections::HashSet<usize>> = std::collections::HashMap::new();
4345    for (index, shell) in body.shells.iter().enumerate() {
4346        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
4347            users.entry(coedge.edge_id).or_default().insert(index);
4348        }
4349    }
4350    let slit_face = |face: &crate::topology::FaceRecord| {
4351        face.loops.iter().all(|lp| {
4352            let mut runs: std::collections::HashMap<u64, (usize, usize)> = std::collections::HashMap::new();
4353            for coedge in &lp.coedges {
4354                let entry = runs.entry(coedge.edge_id).or_default();
4355                if coedge.forward {
4356                    entry.0 += 1;
4357                } else {
4358                    entry.1 += 1;
4359                }
4360            }
4361            !runs.is_empty() && runs.values().all(|&(forward, back)| forward == 1 && back == 1)
4362        })
4363    };
4364    let mut index = 0usize;
4365    let mut dropped = 0usize;
4366    body.shells.retain(|shell| {
4367        let this = index;
4368        index += 1;
4369        let slit = this > 0
4370            && !shell.faces.is_empty()
4371            && shell.faces.iter().all(|face| slit_face(face))
4372            && shell
4373                .faces
4374                .iter()
4375                .flat_map(|face| &face.loops)
4376                .flat_map(|lp| &lp.coedges)
4377                .all(|coedge| users.get(&coedge.edge_id).is_some_and(|set| set.len() == 1));
4378        dropped += usize::from(slit);
4379        !slit
4380    });
4381    if dropped == 0 {
4382        return 0;
4383    }
4384    let used_edges: std::collections::HashSet<u64> = body
4385        .shells
4386        .iter()
4387        .flat_map(|shell| &shell.faces)
4388        .flat_map(|face| &face.loops)
4389        .flat_map(|lp| &lp.coedges)
4390        .map(|coedge| coedge.edge_id)
4391        .collect();
4392    body.edges.retain(|edge| used_edges.contains(&edge.id));
4393    let used_vertices: std::collections::HashSet<u64> =
4394        body.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
4395    body.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
4396    dropped
4397}
4398
4399/// Whether the miter composition blends a TANGENT run of the selection as
4400/// one unit: on unless `BREP_FILLET_MITER_TANGENT_UNITS=0`/`off`.
4401fn miter_tangent_units_on() -> bool {
4402    switch!(live "BREP_FILLET_MITER_TANGENT_UNITS", true)
4403}
4404
4405/// The units the §6.9.6 miter composition blends and then intersects (or
4406/// unions), in input order of each unit's first edge: every selected edge on
4407/// its own, except that edges meeting at a chain corner where their tangents
4408/// CONTINUE each other (a G1 joint, the 1e-6 bar of the tangent-chain walk)
4409/// form one unit.
4410///
4411/// The miter exists for SHARP chain corners: two full-length blends run
4412/// through the corner and trim each other. At a tangent joint there is
4413/// nothing to trim — the two walls meet flush — and two full-length
4414/// per-edge blends of the edges either side of it, each capped where its
4415/// tangent neighbour was left sharp, overlap along that joint in a sliver
4416/// the boolean cannot conform (2026-11-07 "fillet fails" report: a revolve
4417/// end cap's hole loop, one cylinder edge meeting a ceiling plane edge that
4418/// runs on tangentially through an offset blend into a wall; "one-use edge
4419/// conformance did not converge after 8 passes" on the plane-edge result
4420/// intersected with the blend-edge result). The network lane builds such a
4421/// tangent run whole with flush joins; it refused the selection only for
4422/// its sharp re-entrant corners, so a unit that is a STRICT part of the
4423/// selection goes back through the group build, which reaches it there.
4424/// A selection that is one tangent run keeps per-edge units, so the
4425/// recursion always shrinks the selection.
4426fn miter_tangent_units(
4427    solid: &BrepSolid,
4428    selected_edge_ids: &[u64],
4429    chain_corners: &[(Vec3, [usize; 2])],
4430    count: usize,
4431) -> Vec<Vec<usize>> {
4432    let singles = || (0..count).map(|index| vec![index]).collect::<Vec<_>>();
4433    if !miter_tangent_units_on() || selected_edge_ids.len() != count {
4434        return singles();
4435    }
4436    // The tangent along `edge` pointing AWAY from its end at `corner`.
4437    let leaving = |edge_id: u64, corner: Vec3| -> Option<Vec3> {
4438        let edge = solid.edges.iter().find(|edge| edge.id == edge_id)?;
4439        if edge.degenerate {
4440            return None;
4441        }
4442        let start = edge.curve.evaluate(edge.t0).ok()?;
4443        let end = edge.curve.evaluate(edge.t1).ok()?;
4444        let at_start = start.sub(corner).length() <= end.sub(corner).length();
4445        let t = if at_start { edge.t0 } else { edge.t1 };
4446        let tangent = edge.curve.unit_tangent(t, edge.t0, edge.t1).ok()?;
4447        Some(if at_start { tangent } else { tangent.scale(-1.0) })
4448    };
4449    let mut parent: Vec<usize> = (0..count).collect();
4450    fn root(parent: &mut [usize], mut index: usize) -> usize {
4451        while parent[index] != index {
4452            parent[index] = parent[parent[index]];
4453            index = parent[index];
4454        }
4455        index
4456    }
4457    for (corner, [a, b]) in chain_corners {
4458        let (Some(ta), Some(tb)) = (leaving(selected_edge_ids[*a], *corner), leaving(selected_edge_ids[*b], *corner)) else {
4459            continue;
4460        };
4461        // Leaving the corner, a tangent continuation points the opposite way.
4462        if ta.dot(tb) <= -(1.0 - 1e-6) {
4463            let (ra, rb) = (root(&mut parent, *a), root(&mut parent, *b));
4464            if ra != rb {
4465                parent[ra.max(rb)] = ra.min(rb);
4466            }
4467        }
4468    }
4469    let mut units: Vec<Vec<usize>> = Vec::new();
4470    let mut unit_of_root: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
4471    for index in 0..count {
4472        let r = root(&mut parent, index);
4473        let slot = *unit_of_root.entry(r).or_insert_with(|| {
4474            units.push(Vec::new());
4475            units.len() - 1
4476        });
4477        units[slot].push(index);
4478    }
4479    if units.len() <= 1 || units.iter().all(|unit| unit.len() == 1) {
4480        return singles();
4481    }
4482    units
4483}
4484
4485fn concave_star_edges(
4486    solid: &BrepSolid,
4487    selected_edge_ids: &[u64],
4488    corner_edges: &[Vec<usize>],
4489    radius: f64,
4490    chamfer: bool,
4491) -> Vec<usize> {
4492    if chamfer || corner_edges.is_empty() || !concave_first_on() {
4493        return Vec::new();
4494    }
4495    let Some(convexity) = crate::blend::selection_convexity(solid, selected_edge_ids, radius) else {
4496        return Vec::new();
4497    };
4498    (0..selected_edge_ids.len())
4499        .filter(|&index| !convexity[index] && corner_edges.iter().any(|adjacent| adjacent.contains(&index)))
4500        .collect()
4501}
4502
4503/// The cutter the sequential build's single-edge ladder answers a selected
4504/// edge with, read on the ORIGINAL solid: an exact extrusion (a straight
4505/// edge between planes), an exact revolution (a circular edge on
4506/// straight-meridian carriers about its own axis) or, for every other edge,
4507/// the general march (`fillet_or_chamfer_exact` refuses it, so the march
4508/// builds it with direct surgery on the evolving body).
4509#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4510enum CutterClass {
4511    Marched,
4512    Straight,
4513    Circular,
4514}
4515
4516fn cutter_class(solid: &BrepSolid, edge_id: u64, radius: f64) -> CutterClass {
4517    match super::analyze::analyze_edge(solid, edge_id, radius) {
4518        Ok(cross) => match cross.path {
4519            super::analyze::EdgePath::Straight { .. } => CutterClass::Straight,
4520            super::analyze::EdgePath::Circular { .. } => CutterClass::Circular,
4521        },
4522        Err(_) => CutterClass::Marched,
4523    }
4524}
4525
4526/// The sequential build's rank of every selected edge, from the cutter
4527/// classes meeting at the selection's star corners: `1` for a marched edge
4528/// and `3` for a revolved cutter at a star whose edges MIX classes, `2` for
4529/// everything else (a star of one class, a chain corner, a lone edge).
4530/// Within a rank the input order holds ([`sequential_build_order`]).
4531///
4532/// At such a corner the input order fails in two ways, both measured on the
4533/// 2026-10-13 sprocket report whose slit walls were selected as faces
4534/// (`inbox_20261013_sprocket_keyway_slit_fillet`): a revolved cutter leaves
4535/// a TORUS tangent to the hub's top plane along its rail, and the next
4536/// straight cutter's scaffold face lies in that very plane and ends on that
4537/// rail, so the boolean meets a tangent plane/torus contact along a 0.148
4538/// arc that the imprint traces but the assembly cannot close (`unsupported
4539/// tangent-curve surface intersection`, open edges, a 0.067 curve/vertex
4540/// gap); and the slit's vertical, a straight edge on the hub CYLINDER that
4541/// only the march builds, finds "no single end face across the corner" once
4542/// its star mates have been cut. The marched edge cut first sees the pristine
4543/// corner, and a straight cutter cut before the revolved one meets the
4544/// scaffold plane of a CYLINDER tangent along a line — the ordinary planar
4545/// star's own geometry, which the arrangement has always closed. Every
4546/// selection without a mixed-class star keeps its order, byte for byte.
4547fn mixed_star_class_ranks(
4548    solid: &BrepSolid,
4549    selected_edge_ids: &[u64],
4550    corner_edges: &[Vec<usize>],
4551    radius: f64,
4552    chamfer: bool,
4553) -> Vec<u8> {
4554    let mut ranks = vec![2u8; selected_edge_ids.len()];
4555    if chamfer || corner_edges.is_empty() || !class_order_on() {
4556        return ranks;
4557    }
4558    let classes: Vec<CutterClass> = selected_edge_ids
4559        .iter()
4560        .map(|&edge_id| cutter_class(solid, edge_id, radius))
4561        .collect();
4562    for adjacent in corner_edges {
4563        let Some(&head) = adjacent.first() else {
4564            continue;
4565        };
4566        if adjacent.iter().all(|&index| classes[index] == classes[head]) {
4567            continue;
4568        }
4569        for &index in adjacent {
4570            match classes[index] {
4571                CutterClass::Marched => ranks[index] = 1,
4572                CutterClass::Circular => ranks[index] = 3,
4573                CutterClass::Straight => {}
4574            }
4575        }
4576    }
4577    ranks
4578}
4579
4580/// The order the cutter composition's sequential build blends a selection
4581/// in: the input order, except that the edges in `first` (a star corner's
4582/// concave edges, [`concave_star_edges`]) are moved ahead of every other
4583/// edge and the rest follow by `ranks` ([`mixed_star_class_ranks`], lower
4584/// first), keeping the input order among the moved edges and within each
4585/// rank. With `first` empty and every rank equal this is the input order.
4586pub fn sequential_build_order(count: usize, first: &[usize], ranks: &[u8]) -> Vec<usize> {
4587    let mut order: Vec<usize> = (0..count).collect();
4588    // A stable sort: ties keep the input order.
4589    order.sort_by_key(|&index| if first.contains(&index) { 0 } else { ranks.get(index).copied().unwrap_or(2).max(1) });
4590    order
4591}
4592
4593/// Whether the sequential build ranks a mixed-class star's edges by cutter
4594/// class ([`mixed_star_class_ranks`]); always, outside a test that forces it
4595/// off.
4596fn class_order_on() -> bool {
4597    true
4598}
4599
4600
4601/// `corners` and their `corner_edges` (parallel), with every corner that one
4602/// of the `first` edges ends at moved ahead of the rest, both runs in their
4603/// detection order. With `first` empty both come back as they were.
4604fn corners_concave_first(
4605    corners: Vec<Vec3>,
4606    corner_edges: Vec<Vec<usize>>,
4607    first: &[usize],
4608) -> (Vec<Vec3>, Vec<Vec<usize>>) {
4609    if first.is_empty() {
4610        return (corners, corner_edges);
4611    }
4612    let mut ordered: Vec<(Vec3, Vec<usize>)> = Vec::with_capacity(corners.len());
4613    let pairs: Vec<(Vec3, Vec<usize>)> = corners.into_iter().zip(corner_edges).collect();
4614    let with_concave = |adjacent: &Vec<usize>| adjacent.iter().any(|index| first.contains(index));
4615    ordered.extend(pairs.iter().filter(|(_, adjacent)| with_concave(adjacent)).cloned());
4616    ordered.extend(pairs.iter().filter(|(_, adjacent)| !with_concave(adjacent)).cloned());
4617    ordered.into_iter().unzip()
4618}
4619
4620/// Whether the sequential build moves a star corner's concave edge first
4621/// ([`sequential_build_order`]); always, outside a test that forces it off.
4622fn concave_first_on() -> bool {
4623    true
4624}
4625
4626
4627/// Variable-radius fillet/chamfer of a GROUP of edges (§4.9.5), the app entry
4628/// for tapered blends: each selected edge (resolved by a point on it) is
4629/// blended with the SAME radius profile `radii` — a list of (edge-fraction,
4630/// radius) stops in `[0,1]` — applied along that edge's own parameterization.
4631/// Edges are blended independently (no shared-vertex corner rounding; a
4632/// variable-radius star has no single tangent ball), so this is the tapered
4633/// counterpart of `fillet_edges` for the constant case.
4634pub fn fillet_edges_variable(
4635    solid: &BrepSolid,
4636    edge_points: &[Vec3],
4637    edge_names: Option<&[String]>,
4638    radii: &[(f64, f64)],
4639    chamfer: bool,
4640    name: Option<&str>,
4641) -> Result<BrepSolid, KernelRefusal> {
4642    // One blend operation: the reports of an earlier one, never consumed, are
4643    // dropped as it starts (nested calls keep this operation's).
4644    let _operation = crate::blend::BlendOperation::enter();
4645    if edge_points.is_empty() {
4646        return Err(KernelRefusal::input(
4647            KernelStage::Collect,
4648            "variable_selection",
4649            "fillet_edges_variable: no edges selected",
4650        ));
4651    }
4652    let per_edge_stops: Vec<Vec<(f64, f64)>> = vec![radii.to_vec(); edge_points.len()];
4653    fillet_edges_variable_impl(
4654        solid,
4655        edge_points,
4656        edge_names,
4657        &per_edge_stops,
4658        chamfer,
4659        name,
4660        "fillet_edges_variable",
4661        true,
4662    )
4663}
4664
4665/// The shared variable-radius group core: each selected edge `i` is blended
4666/// with ITS OWN stop list `per_edge_stops[i]` (the legacy entry replicates one
4667/// list; the law entries sample a chain-abscissa [`crate::law::RadiusLaw`] per
4668/// edge).  `allow_tapered_sequential` keeps the legacy entry's sequential
4669/// fallback for tapered chains (whose end state is the honest
4670/// "mismatched radii" validation gate); the law entries pass `false` because
4671/// their stop fractions are computed against the ORIGINAL edges — the
4672/// sequential build re-resolves edges on the evolving solid whose shared
4673/// corners are already TRIMMED by earlier blends, which would silently distort
4674/// the law's abscissa mapping (constant stops are immune, so they may still
4675/// fall back).
4676#[allow(clippy::too_many_arguments)]
4677fn fillet_edges_variable_impl(
4678    solid: &BrepSolid,
4679    edge_points: &[Vec3],
4680    edge_names: Option<&[String]>,
4681    per_edge_stops: &[Vec<(f64, f64)>],
4682    chamfer: bool,
4683    name: Option<&str>,
4684    entry: &str,
4685    allow_tapered_sequential: bool,
4686) -> Result<BrepSolid, KernelRefusal> {
4687    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`)
4688    // and the recentre guard, as `fillet_edges_reported` applies them.
4689    let bounds = crate::recentre::solid_bounds(solid);
4690    let translated = match crate::recentre::control_offset_at_entry() {
4691        Some(offset) => Some((offset, crate::recentre::EntryKind::Control)),
4692        None => crate::recentre::guard_offset(bounds).map(|offset| {
4693            crate::recentre::profile_fired(entry, offset, bounds);
4694            (offset, crate::recentre::EntryKind::Guard)
4695        }),
4696    };
4697    if let Some((offset, kind)) = translated {
4698        let _entry = crate::recentre::TranslatedEntry::open(kind);
4699        let translate = |solid: &BrepSolid, offset: Vec3| {
4700            crate::recentre::translate_solid(solid, offset).map_err(|message| {
4701                KernelRefusal::internal(
4702                    KernelStage::Collect,
4703                    "translation_control",
4704                    format!("{entry}: the translation control could not move the solid: {message}"),
4705                )
4706            })
4707        };
4708        let moved = translate(solid, offset)?;
4709        let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
4710        let result = fillet_edges_variable_impl(
4711            &moved,
4712            &points,
4713            edge_names,
4714            per_edge_stops,
4715            chamfer,
4716            name,
4717            entry,
4718            allow_tapered_sequential,
4719        )?;
4720        return translate(&result, offset.scale(-1.0));
4721    }
4722    debug_assert_eq!(per_edge_stops.len(), edge_points.len());
4723    // A law that is one constant everywhere IS the constant-radius fillet:
4724    // hand it to the constant group, whose corners are constructed (the
4725    // stripe network) rather than composed by boolean.
4726    if let Some(constant) = per_edge_stops
4727        .first()
4728        .and_then(|stops| stops.first())
4729        .map(|(_, radius)| *radius)
4730    {
4731        let uniform = per_edge_stops.iter().all(|stops| {
4732            stops
4733                .iter()
4734                .all(|(_, radius)| (radius - constant).abs() <= 1e-12 * (1.0 + constant.abs()))
4735        });
4736        if uniform && constant > 0.0 {
4737            return fillet_edges(solid, edge_points, edge_names, constant, chamfer, name);
4738        }
4739    }
4740    let max_radius = per_edge_stops
4741        .iter()
4742        .flat_map(|stops| stops.iter())
4743        .map(|(_, r)| r.abs())
4744        .fold(0.0_f64, f64::max);
4745
4746    // Tried first; whatever the network does not build (an unequal-radius
4747    // corner, a flush join or re-entrant vertex at a varying radius, a
4748    // result its acceptance rejects) falls through to the composition below
4749    // exactly as before.
4750    if edge_points.len() >= 2 {
4751        match fillet_variable_network(
4752            solid, edge_points, edge_names, per_edge_stops, chamfer, name, entry, max_radius,
4753        )? {
4754            Ok(built) => return Ok(built),
4755            // A radius relief's law is the network's to build: the
4756            // composition below took 75 s a plan on report 37e16630 at r 1.0
4757            // and built none, so the relief's next plan is asked instead.
4758            Err(refusal) if crate::blend::relief::relieving() => return Err(refusal),
4759            Err(_) => {}
4760        }
4761    }
4762
4763    // Chain corners miter exactly like the constant-radius group (§6.9.6):
4764    // per-edge blends on the ORIGINAL solid composed by boolean — Intersect
4765    // when every edge is convex, Union when every edge is concave.  Mixed or
4766    // unclassifiable selections keep the sequential build.  Variable blends
4767    // never round star vertices, so unlike the constant group there is no
4768    // sequential-only star path to protect.
4769    let mut chain_corner = false;
4770    {
4771        use rustc_hash::FxHashSet as HashSet;
4772        let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
4773        for (i, point) in edge_points.iter().enumerate() {
4774            if let Ok(edge_id) = resolve_edge_by_point(solid, *point) {
4775                if let Some(edge) = solid.edges.iter().find(|e| e.id == edge_id) {
4776                    if let (Ok(a), Ok(b)) =
4777                        (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1))
4778                    {
4779                        endpoints.push((a, i));
4780                        endpoints.push((b, i));
4781                    }
4782                }
4783            }
4784        }
4785        let mut used = vec![false; endpoints.len()];
4786        for i in 0..endpoints.len() {
4787            if used[i] {
4788                continue;
4789            }
4790            used[i] = true;
4791            let mut edges_here: HashSet<usize> = HashSet::default();
4792            edges_here.insert(endpoints[i].1);
4793            for j in (i + 1)..endpoints.len() {
4794                if used[j] {
4795                    continue;
4796                }
4797                if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
4798                    used[j] = true;
4799                    edges_here.insert(endpoints[j].1);
4800                }
4801            }
4802            if edges_here.len() == 2 {
4803                chain_corner = true;
4804            }
4805        }
4806    }
4807    let miter_operation = if chain_corner {
4808        let probe_radius = if max_radius > 0.0 { max_radius } else { 1.0 };
4809        let mut any_convex = false;
4810        let mut any_concave = false;
4811        for point in edge_points {
4812            match resolve_edge_by_point(solid, *point)
4813                .and_then(|edge_id| analyze_edge(solid, edge_id, probe_radius))
4814            {
4815                Ok(cross) if cross.convex => any_convex = true,
4816                Ok(_) => any_concave = true,
4817                Err(_) => {
4818                    any_convex = true;
4819                    any_concave = true;
4820                    break;
4821                }
4822            }
4823        }
4824        match (any_convex, any_concave) {
4825            (true, false) => Some(crate::BooleanOperation::Intersect),
4826            (false, true) => Some(crate::BooleanOperation::Union),
4827            _ => None,
4828        }
4829    } else {
4830        None
4831    };
4832
4833    // Try the miter first; the variable blend's FITTED boundary curves are
4834    // only ~1e-3 accurate at blend-blend tangencies (unlike the exact
4835    // constant-radius cylinders), so the composition can fail — fall back to
4836    // the sequential build then, which is never worse than the pre-miter
4837    // behavior.  Tightening the taper surface's endpoint fitting is the
4838    // documented follow-up that would make the miter stick.
4839    let miter_attempt: Option<BrepSolid> = if let Some(operation) = miter_operation {
4840        let options = crate::BooleanOptions::default();
4841        let mut combined: Option<BrepSolid> = None;
4842        let mut failed = false;
4843        for (index, point) in edge_points.iter().enumerate() {
4844            let Ok(edge_id) = resolve_edge_by_point(solid, *point) else {
4845                failed = true;
4846                break;
4847            };
4848            let edge_name = per_edge_name(edge_names, name, index);
4849            let Ok(blended) = crate::blend::blend_edge_variable(
4850                solid,
4851                edge_id,
4852                &per_edge_stops[index],
4853                chamfer,
4854                edge_name,
4855            ) else {
4856                failed = true;
4857                break;
4858            };
4859            let next = match combined.take() {
4860                None => blended,
4861                Some(previous) => {
4862                    match crate::boolean_operation(&previous, &blended, operation, &options) {
4863                        Ok(next) => next,
4864                        Err(_) => {
4865                            failed = true;
4866                            break;
4867                        }
4868                    }
4869                }
4870            };
4871            combined = Some(next);
4872        }
4873        if failed {
4874            None
4875        } else {
4876            combined.filter(|s| s.validate().is_empty())
4877        }
4878    } else {
4879        None
4880    };
4881    let mut result = match miter_attempt {
4882        Some(mitered) => mitered,
4883        None => {
4884            // Any stop list that is NOT radius-uniform (the same 1e-12
4885            // relative criterion `blend_edge_variable` uses for its exact
4886            // constant-radius degeneration) makes the sequential build
4887            // abscissa-distorting on trimmed chain edges; law entries refuse
4888            // instead of silently shifting the law.
4889            let tapered = per_edge_stops.iter().any(|stops| {
4890                stops.first().is_some_and(|(_, first)| {
4891                    stops
4892                        .iter()
4893                        .any(|(_, r)| (r - first).abs() > 1e-12 * (1.0 + first.abs()))
4894                })
4895            });
4896            if chain_corner && tapered && !allow_tapered_sequential {
4897                // The transition patch that would carry a taper through the
4898                // corner is not built: a named deferral.
4899                return Err(KernelRefusal::unsupported(
4900                    KernelStage::Sew,
4901                    "tapered_chain_miter",
4902                    format!(
4903                        "{entry}: the tapered blends across the selected chain's shared corners \
4904                         did not compose to a valid solid (the fitted blend boundaries could not \
4905                         be mitered); fillet fewer edges per operation or reduce the taper"
4906                    ),
4907                ));
4908            }
4909            let mut sequential = solid.clone();
4910            for (index, point) in edge_points.iter().enumerate() {
4911                let edge_id = resolve_edge_by_point(&sequential, *point)?;
4912                let edge_name = per_edge_name(edge_names, name, index);
4913                sequential = crate::blend::blend_edge_variable(
4914                    &sequential,
4915                    edge_id,
4916                    &per_edge_stops[index],
4917                    chamfer,
4918                    edge_name,
4919                )?;
4920            }
4921            sequential
4922        }
4923    };
4924    // Heal §6.9 surgery so re-trimmed edges meet their vertices exactly; scale
4925    // the heal bound by the largest radius stop in the taper profile.
4926    heal_edge_vertex_gaps(&mut result, max_radius)?;
4927    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4928    // Final honesty gate: a genuinely TAPERED chain (different radii at the
4929    // shared corner) has mismatched trim stations there — the blends cannot
4930    // meet without a transition patch (not implemented), and the sequential
4931    // surgery silently left broken topology before this gate existed.
4932    let issues = result.validate();
4933    if !issues.is_empty() {
4934        // Two verdicts share the text's shape: the legacy entry names the
4935        // transition patch it does not build (a deferral); the law entries,
4936        // whose taper is continuous through the corner, report the
4937        // composition failing its own validation (a check that tripped).
4938        let (detail, class) = if allow_tapered_sequential {
4939            (
4940                "tapered blends meet at a shared chain vertex with \
4941                 mismatched radii — the radius-transition corner patch is not implemented; \
4942                 fillet the edges in separate operations or use matching stop radii",
4943                RefusalClass::UnsupportedGeometry {
4944                    what: "taper_transition_patch".into(),
4945                },
4946            )
4947        } else {
4948            (
4949                "the composed radius-law blend produced invalid topology — the blends \
4950                 across a shared chain corner failed to reassemble",
4951                RefusalClass::Internal {
4952                    what: "law_chain_topology".into(),
4953                },
4954            )
4955        };
4956        return Err(KernelRefusal::new(
4957            class,
4958            KernelStage::Validate,
4959            format!(
4960                "{entry}: {detail} ({} validation issues, first: {})",
4961                issues.len(),
4962                issues
4963                    .first()
4964                    .map(|issue| issue.message.clone())
4965                    .unwrap_or_default()
4966            ),
4967        ));
4968    }
4969    // The variable-radius lane's own soundness acceptance, the same one the
4970    // constant-radius group exit takes. `validate()` above is an INCIDENCE
4971    // test: a tapered wall that passes through a neighbour, or through itself,
4972    // satisfies every check it makes and still measures a volume.
4973    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
4974    crate::accept_sound(result, entry)
4975}
4976
4977/// `Ok(None)` is "not this lane" — the network refused, or its result
4978/// failed the same acceptance the constant group holds the network to —
4979/// and the caller composes as before; `Err` is a refusal nothing below
4980/// can answer.
4981#[allow(clippy::too_many_arguments)]
4982fn fillet_variable_network(
4983    solid: &BrepSolid,
4984    edge_points: &[Vec3],
4985    edge_names: Option<&[String]>,
4986    per_edge_stops: &[Vec<(f64, f64)>],
4987    chamfer: bool,
4988    name: Option<&str>,
4989    entry: &str,
4990    max_radius: f64,
4991) -> Result<Result<BrepSolid, KernelRefusal>, KernelRefusal> {
4992    let mut edge_ids = Vec::with_capacity(edge_points.len());
4993    for point in edge_points {
4994        edge_ids.push(resolve_edge_by_point(solid, *point)?);
4995    }
4996    let laws: Vec<crate::blend::StripeRadius> =
4997        per_edge_stops.iter().map(|stops| crate::blend::StripeRadius::from_stops(stops)).collect();
4998    let network_names: Vec<Option<String>> = (0..edge_points.len())
4999        .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
5000        .collect();
5001    let network_corner_name = |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
5002    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
5003    // A support pcurve off the floor is re-run ONCE with the knot-aware
5004    // support fit, as the constant group's network is; a re-run that also
5005    // fails keeps the first refusal. A radius relief's law crowds the
5006    // march's stations into its ramp, and the rail's knot spans there are
5007    // finer than the uniform track can follow (a reported model: r 1.4 on
5008    // the outline of a cut through a sub-D body, its relieved rail spans
5009    // 7.7e-5 against a track spacing of 2.4e-4, 1.5e-6 off at 4097
5010    // samples).
5011    let law_network = || {
5012        crate::blend::blend_star_network_laws(solid, &edge_ids, &laws, chamfer, &network_names, &network_corner_name, true)
5013    };
5014    let network_result = law_network().or_else(|first| {
5015        if crate::blend::is_pcurve_floor_refusal(&first) {
5016            crate::blend::with_pcurve_knot_retry(law_network).map_err(|_| first)
5017        } else {
5018            Err(first)
5019        }
5020    });
5021    let mut network = match network_result {
5022        Ok(network) => network,
5023        Err(refusal) => {
5024            if debug {
5025                eprintln!("law network refused: {refusal}");
5026            }
5027            return Ok(Err(refusal));
5028        }
5029    };
5030    // The constant group's acceptance of a network result, in its order:
5031    // the vertex-gap heal, the planar charts, validation, the interference
5032    // classifier and the bowtie scan; then the soundness acceptance the
5033    // variable lane's exit takes.
5034    let healed = heal_edge_vertex_gaps(&mut network, max_radius);
5035    crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
5036    let issues = network.validate();
5037    let interference = check_blend_interference(solid, &network, &edge_ids, entry);
5038    let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
5039    if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
5040        crate::soundness::census::profile_operation(&network, &[solid], None, entry);
5041        match crate::accept_sound(network, entry) {
5042            Ok(sound) => return Ok(Ok(sound)),
5043            Err(refusal) => {
5044                if debug {
5045                    eprintln!("law network result unsound: {refusal}");
5046                }
5047                return Ok(Err(refusal));
5048            }
5049        }
5050    }
5051    if debug {
5052        eprintln!(
5053            "law network result rejected: heal={healed:?} issues={issues:?} \
5054             interference={interference:?} bowtie={bowtie:?}"
5055        );
5056    }
5057    Ok(Err(KernelRefusal::unsupported(
5058        KernelStage::Validate,
5059        "law_network_rejected",
5060        format!(
5061            "{entry}: the tapered network's result was rejected (heal {}, {} validation issues, interference {}, loops {})",
5062            if healed.is_ok() { "ok" } else { "failed" },
5063            issues.len(),
5064            if interference.is_ok() { "ok" } else { "found" },
5065            if bowtie.is_ok() { "ok" } else { "found" },
5066        ),
5067    )))
5068}
5069
5070
5071/// One selected edge placed on the ordered chain, with its arc-length
5072/// parameterization (the caller-side mapping from chain abscissa to the
5073/// `blend_edge_variable` per-edge parameter-fraction stop seam).
5074struct ChainLink {
5075    /// Position of this edge in the caller's `edge_points` selection.
5076    input_index: usize,
5077    /// True when the edge's own t0→t1 parameter direction runs WITH the chain.
5078    forward: bool,
5079    /// Cumulative chord-length table from the edge's t0 end:
5080    /// `(parameter fraction, arc length)`, uniformly spaced in fraction.
5081    arc: Vec<(f64, f64)>,
5082    /// Total arc length of the edge.
5083    length: f64,
5084    /// Chain abscissa at the link's ENTRY vertex (the end reached first when
5085    /// walking the chain from its start).
5086    abscissa: f64,
5087}
5088
5089/// Cumulative chord-length table of one edge, `(parameter fraction, arc
5090/// length)` at uniform fractions.  The sample count doubles until two
5091/// successive total-length estimates agree within `tol` (chord length
5092/// converges O(N⁻²) for smooth curves, so the agreement of the N and 2N
5093/// estimates bounds the remaining error at the same order); straight edges
5094/// converge on the first doubling.  The 16-sample start resolves any
5095/// single-span arc of up to half a turn to sub-percent before refinement; the
5096/// 4096 cap (8 doublings) guards adversarial curves — beyond it the table is
5097/// two orders denser than the blend march's station grid, so finer chords
5098/// cannot move any station's sampled radius meaningfully.
5099fn edge_arc_table(
5100    curve: &NurbsCurve,
5101    t0: f64,
5102    t1: f64,
5103    tol: f64,
5104) -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5105    let evaluate = |t: f64| curve.evaluate(t).or_refuse(KernelStage::Collect, "arc_table");
5106    let build = |n: usize| -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5107        let mut table = Vec::with_capacity(n + 1);
5108        let mut cumulative = 0.0;
5109        let mut previous = evaluate(t0)?;
5110        table.push((0.0, 0.0));
5111        for j in 1..=n {
5112            let fraction = j as f64 / n as f64;
5113            let point = evaluate(t0 + (t1 - t0) * fraction)?;
5114            cumulative += point.sub(previous).length();
5115            previous = point;
5116            table.push((fraction, cumulative));
5117        }
5118        Ok((table, cumulative))
5119    };
5120    let mut n = 16usize;
5121    let (mut table, mut length) = build(n)?;
5122    while n < 4096 {
5123        n *= 2;
5124        let (next_table, next_length) = build(n)?;
5125        let converged = (next_length - length).abs() <= tol;
5126        table = next_table;
5127        length = next_length;
5128        if converged {
5129            break;
5130        }
5131    }
5132    Ok((table, length))
5133}
5134
5135/// Arc length from the edge's t0 end at `fraction` of its parameter span,
5136/// linearly interpolated in the uniform chord table.
5137fn arc_length_at_fraction(table: &[(f64, f64)], fraction: f64) -> f64 {
5138    let fraction = fraction.clamp(0.0, 1.0);
5139    let intervals = table.len() - 1;
5140    let scaled = fraction * intervals as f64;
5141    let index = (scaled.floor() as usize).min(intervals - 1);
5142    let local = scaled - index as f64;
5143    let (_, a) = table[index];
5144    let (_, b) = table[index + 1];
5145    a + (b - a) * local
5146}
5147
5148/// Resolve the selected edges and order them into ONE OPEN CHAIN with
5149/// cumulative arc-length abscissas.  The chain starts at the free endpoint
5150/// belonging to the EARLIEST-selected end edge (so users get the natural
5151/// "first pick carries the law start" orientation); a single selected edge is
5152/// its own chain oriented t0→t1 (which also admits a closed edge — the law's
5153/// end radii must then match, enforced downstream by `blend_edge_variable`).
5154/// Branching (a vertex shared by 3+ selected edges), closed rings of several
5155/// edges, and disconnected selections refuse with named errors.
5156fn resolve_selected_chain(
5157    solid: &BrepSolid,
5158    edge_points: &[Vec3],
5159    entry: &str,
5160    tol: f64,
5161) -> Result<Vec<ChainLink>, KernelRefusal> {
5162    // Endpoint identity uses the kernel-wide COINCIDENCE_DISTANCE_FLOOR — the
5163    // same band the constant-radius group's corner detector applies.
5164    let band = crate::tolerance::COINCIDENCE_DISTANCE_FLOOR;
5165
5166    struct Resolved {
5167        edge_id: u64,
5168        start: Vec3,
5169        end: Vec3,
5170        arc: Vec<(f64, f64)>,
5171        length: f64,
5172    }
5173    let mut resolved: Vec<Resolved> = Vec::with_capacity(edge_points.len());
5174    for point in edge_points {
5175        let edge_id = resolve_edge_by_point(solid, *point)?;
5176        if resolved.iter().any(|r| r.edge_id == edge_id) {
5177            return Err(KernelRefusal::input(
5178                KernelStage::Collect,
5179                "duplicate_edge",
5180                format!("{entry}: the same edge was selected more than once"),
5181            ));
5182        }
5183        let edge = solid
5184            .edges
5185            .iter()
5186            .find(|e| e.id == edge_id)
5187            .ok_or_else(|| {
5188                KernelRefusal::internal(
5189                    KernelStage::Collect,
5190                    "chain_resolved_edge",
5191                    format!("{entry}: resolved edge vanished"),
5192                )
5193            })?;
5194        let (arc, length) = edge_arc_table(&edge.curve, edge.t0, edge.t1, tol)?;
5195        if !(length > 0.0) {
5196            return Err(KernelRefusal::input(
5197                KernelStage::Collect,
5198                "zero_length_edge",
5199                format!("{entry}: selected edge has zero length"),
5200            ));
5201        }
5202        resolved.push(Resolved {
5203            edge_id,
5204            start: edge
5205                .curve
5206                .evaluate(edge.t0)
5207                .or_refuse(KernelStage::Collect, "chain_edge_start")?,
5208            end: edge
5209                .curve
5210                .evaluate(edge.t1)
5211                .or_refuse(KernelStage::Collect, "chain_edge_end")?,
5212            arc,
5213            length,
5214        });
5215    }
5216    let n = resolved.len();
5217    if n == 1 {
5218        let only = resolved.remove(0);
5219        return Ok(vec![ChainLink {
5220            input_index: 0,
5221            forward: true,
5222            arc: only.arc,
5223            length: only.length,
5224            abscissa: 0.0,
5225        }]);
5226    }
5227
5228    // Cluster the 2n endpoints; each entry is (edge index, is_start_end).
5229    let mut clusters: Vec<(Vec3, Vec<(usize, bool)>)> = Vec::new();
5230    for (i, r) in resolved.iter().enumerate() {
5231        for (point, is_start) in [(r.start, true), (r.end, false)] {
5232            match clusters
5233                .iter_mut()
5234                .find(|(anchor, _)| anchor.sub(point).length() < band)
5235            {
5236                Some((_, members)) => members.push((i, is_start)),
5237                None => clusters.push((point, vec![(i, is_start)])),
5238            }
5239        }
5240    }
5241    if clusters.iter().any(|(_, members)| members.len() > 2) {
5242        return Err(KernelRefusal::input(
5243            KernelStage::Collect,
5244            "chain_branching",
5245            format!(
5246                "{entry}: selected edges must form one open chain \
5247                 (a vertex is shared by three or more selected edges)"
5248            ),
5249        ));
5250    }
5251    let free: Vec<usize> = clusters
5252        .iter()
5253        .enumerate()
5254        .filter(|(_, (_, members))| members.len() == 1)
5255        .map(|(c, _)| c)
5256        .collect();
5257    if free.len() != 2 {
5258        return Err(KernelRefusal::input(
5259            KernelStage::Collect,
5260            "chain_open",
5261            format!(
5262                "{entry}: selected edges must form one OPEN chain \
5263                 (closed rings and disconnected selections are not supported)"
5264            ),
5265        ));
5266    }
5267    // Start at the free end whose edge appears EARLIEST in the selection.
5268    let start_cluster = *free
5269        .iter()
5270        .min_by_key(|&&c| clusters[c].1[0].0)
5271        .expect("two free ends");
5272
5273    // Walk the chain.
5274    let mut links: Vec<ChainLink> = Vec::with_capacity(n);
5275    let mut visited = vec![false; n];
5276    let mut abscissa = 0.0_f64;
5277    let mut cluster = start_cluster;
5278    for _ in 0..n {
5279        let Some(&(edge_index, entered_at_start)) = clusters[cluster]
5280            .1
5281            .iter()
5282            .find(|(edge_index, _)| !visited[*edge_index])
5283        else {
5284            return Err(KernelRefusal::input(
5285                KernelStage::Collect,
5286                "chain_walk",
5287                format!(
5288                    "{entry}: selected edges are not connected into one chain"
5289                ),
5290            ));
5291        };
5292        visited[edge_index] = true;
5293        let r = &resolved[edge_index];
5294        links.push(ChainLink {
5295            input_index: edge_index,
5296            forward: entered_at_start,
5297            arc: r.arc.clone(),
5298            length: r.length,
5299            abscissa,
5300        });
5301        abscissa += r.length;
5302        let exit_point = if entered_at_start { r.end } else { r.start };
5303        cluster = clusters
5304            .iter()
5305            .position(|(anchor, _)| anchor.sub(exit_point).length() < band)
5306            .ok_or_else(|| {
5307                KernelRefusal::internal(
5308                    KernelStage::Collect,
5309                    "chain_cluster",
5310                    format!("{entry}: chain walk lost an endpoint cluster"),
5311                )
5312            })?;
5313    }
5314    if visited.iter().any(|v| !v) {
5315        return Err(KernelRefusal::input(
5316            KernelStage::Collect,
5317            "chain_connected",
5318            format!(
5319                "{entry}: selected edges are not connected into one chain"
5320            ),
5321        ));
5322    }
5323    Ok(links)
5324}
5325
5326/// Sample the law into one edge's `(parameter fraction, radius)` stop list —
5327/// the caller-side bridge from chain abscissa into the `radius_at` closure
5328/// seam that `blend_edge_variable` builds over its stops.
5329///
5330/// `scale` maps chain abscissa into the law's own abscissa units
5331/// (`law.total_length() / chain_length` — proportional, so a law built from
5332/// the measured chain lengths maps 1:1).  The base stop count derives from
5333/// the law's curvature: piecewise-linear sampling of a C1, piecewise-C2
5334/// function over step `h` errs at most `h²·max|r''|/8`, so
5335/// `h = sqrt(8·tol/max|r''|)` holds the sampling error under the SSI fit
5336/// tolerance the variable lane is built to.  That bound is exact for
5337/// arc-length-linear (straight) edges; curved edges bend the
5338/// parameter→abscissa map, so each interval is additionally midpoint-checked
5339/// against the law and bisected on violation (up to 8 halvings — a 4⁸ ≈ 6·10⁴
5340/// error reduction, decisive for any C1 law).  The base count is capped at
5341/// 256 intervals: 4× the blend march's 64-station density
5342/// (blend/stations.rs), beyond which denser stops cannot move any station's
5343/// sampled radius by more than the fit tolerance.
5344fn law_stops_for_link(
5345    link: &ChainLink,
5346    law: &crate::law::RadiusLaw,
5347    scale: f64,
5348    tol: f64,
5349) -> Vec<(f64, f64)> {
5350    let radius_at_fraction = |fraction: f64| -> f64 {
5351        let arc = arc_length_at_fraction(&link.arc, fraction);
5352        let chain_s = if link.forward {
5353            link.abscissa + arc
5354        } else {
5355            link.abscissa + (link.length - arc)
5356        };
5357        law.radius_at(chain_s * scale)
5358    };
5359    // Curvature of the law in edge-fraction units: d²r/df² ≤
5360    // max|r''|·(scale·length)² for the arc-length-linear map.
5361    let curvature = law
5362        .max_second_derivative(link.abscissa * scale, (link.abscissa + link.length) * scale)
5363        * (scale * link.length).powi(2);
5364    let base = if curvature * 0.125 <= tol {
5365        1usize
5366    } else {
5367        ((curvature / (8.0 * tol)).sqrt().ceil() as usize).clamp(1, 256)
5368    };
5369    let mut stops: Vec<(f64, f64)> = (0..=base)
5370        .map(|j| {
5371            let fraction = j as f64 / base as f64;
5372            (fraction, radius_at_fraction(fraction))
5373        })
5374        .collect();
5375    // Midpoint refinement for curved parameter→abscissa maps.
5376    let mut depth = 0usize;
5377    while depth < 8 {
5378        let mut refined: Vec<(f64, f64)> = Vec::with_capacity(stops.len());
5379        let mut inserted = false;
5380        for pair in stops.windows(2) {
5381            refined.push(pair[0]);
5382            let mid_fraction = 0.5 * (pair[0].0 + pair[1].0);
5383            let law_mid = radius_at_fraction(mid_fraction);
5384            let linear_mid = 0.5 * (pair[0].1 + pair[1].1);
5385            if (law_mid - linear_mid).abs() > tol {
5386                refined.push((mid_fraction, law_mid));
5387                inserted = true;
5388            }
5389        }
5390        refined.push(*stops.last().expect("at least two stops"));
5391        stops = refined;
5392        if !inserted {
5393            break;
5394        }
5395        depth += 1;
5396    }
5397    stops
5398}
5399
5400/// Fillet (or chamfer) a chain of edges under a composable radius law
5401/// evaluated on the chain's cumulative arc-length abscissa (the OCCT
5402/// `Law_Composite` model; see [`crate::law::RadiusLaw`]).  The selected edges
5403/// must form ONE OPEN CHAIN (or be a single edge); the chain starts at the
5404/// free end of the earliest-selected end edge, and the law's abscissa maps
5405/// proportionally onto the chain's measured arc length (a law built with the
5406/// chain's own lengths — e.g. [`crate::law::RadiusLaw::from_vertex_radii`] —
5407/// maps 1:1).  Endpoint radii are met exactly; radii at shared chain vertices
5408/// match by the law's continuity, so the per-edge blends miter through the
5409/// corners; a chain whose blends cannot be mitered REFUSES rather than
5410/// distorting the law through the sequential rebuild.
5411pub fn fillet_edges_variable_law(
5412    solid: &BrepSolid,
5413    edge_points: &[Vec3],
5414    edge_names: Option<&[String]>,
5415    law: &crate::law::RadiusLaw,
5416    chamfer: bool,
5417    name: Option<&str>,
5418) -> Result<BrepSolid, KernelRefusal> {
5419    // One blend operation: the reports of an earlier one, never consumed, are
5420    // dropped as it starts (nested calls keep this operation's).
5421    let _operation = crate::blend::BlendOperation::enter();
5422    const ENTRY: &str = "fillet_edges_variable_law";
5423    if edge_points.is_empty() {
5424        return Err(KernelRefusal::input(
5425            KernelStage::Collect,
5426            "law_selection",
5427            format!("{ENTRY}: no edges selected"),
5428        ));
5429    }
5430    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5431    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5432    fillet_variable_law_on_chain(
5433        solid,
5434        edge_points,
5435        edge_names,
5436        &chain,
5437        law,
5438        chamfer,
5439        name,
5440        ENTRY,
5441        tolerances.intersection_fit,
5442    )
5443}
5444
5445/// The natural per-vertex user model: radius `vertex_radii[i]` at chain
5446/// vertex `i` (in CHAIN order, starting at the free end of the
5447/// earliest-selected edge), smoothly interpolated along the chain
5448/// (monotone C1 — every vertex radius met exactly, no overshoot).  Requires
5449/// exactly one radius per chain vertex (`edges + 1`).
5450pub fn fillet_edges_variable_vertex_radii(
5451    solid: &BrepSolid,
5452    edge_points: &[Vec3],
5453    edge_names: Option<&[String]>,
5454    vertex_radii: &[f64],
5455    chamfer: bool,
5456    name: Option<&str>,
5457) -> Result<BrepSolid, KernelRefusal> {
5458    // One blend operation: the reports of an earlier one, never consumed, are
5459    // dropped as it starts (nested calls keep this operation's).
5460    let _operation = crate::blend::BlendOperation::enter();
5461    const ENTRY: &str = "fillet_edges_variable_vertex_radii";
5462    if edge_points.is_empty() {
5463        return Err(KernelRefusal::input(
5464            KernelStage::Collect,
5465            "vertex_radii_selection",
5466            format!("{ENTRY}: no edges selected"),
5467        ));
5468    }
5469    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5470    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5471    let lengths: Vec<f64> = chain.iter().map(|link| link.length).collect();
5472    let law = crate::law::RadiusLaw::from_vertex_radii(&lengths, vertex_radii)
5473        .map_err(|error| error.with_message(|error| format!("{ENTRY}: {error}")))?;
5474    fillet_variable_law_on_chain(
5475        solid,
5476        edge_points,
5477        edge_names,
5478        &chain,
5479        &law,
5480        chamfer,
5481        name,
5482        ENTRY,
5483        tolerances.intersection_fit,
5484    )
5485}
5486
5487/// Shared law-entry tail: sample per-edge stop lists from the law over the
5488/// resolved chain and run the variable group core (miter-or-refuse: no
5489/// sequential fallback for tapered chains — see `fillet_edges_variable_impl`).
5490#[allow(clippy::too_many_arguments)]
5491fn fillet_variable_law_on_chain(
5492    solid: &BrepSolid,
5493    edge_points: &[Vec3],
5494    edge_names: Option<&[String]>,
5495    chain: &[ChainLink],
5496    law: &crate::law::RadiusLaw,
5497    chamfer: bool,
5498    name: Option<&str>,
5499    entry: &str,
5500    tol: f64,
5501) -> Result<BrepSolid, KernelRefusal> {
5502    let chain_length: f64 = chain.iter().map(|link| link.length).sum();
5503    let scale = law.total_length() / chain_length;
5504    let mut per_edge_stops: Vec<Vec<(f64, f64)>> = vec![Vec::new(); edge_points.len()];
5505    for link in chain {
5506        per_edge_stops[link.input_index] = law_stops_for_link(link, law, scale, tol);
5507    }
5508    fillet_edges_variable_impl(
5509        solid,
5510        edge_points,
5511        edge_names,
5512        &per_edge_stops,
5513        chamfer,
5514        name,
5515        entry,
5516        false,
5517    )
5518}
5519
5520/// Asymmetric (two-distance) chamfer of a GROUP of edges, the app entry: each
5521/// selected edge (resolved by a point on it) gets a `d1 × d2` bevel (§6.11).
5522/// Edges are chamfered independently — asymmetric chamfers keep sharp vertices,
5523/// so there is no shared-corner blending.
5524pub fn chamfer_edges_asymmetric(
5525    solid: &BrepSolid,
5526    edge_points: &[Vec3],
5527    edge_names: Option<&[String]>,
5528    d1: f64,
5529    d2: f64,
5530    name: Option<&str>,
5531) -> Result<BrepSolid, KernelRefusal> {
5532    // One blend operation: the reports of an earlier one, never consumed, are
5533    // dropped as it starts (nested calls keep this operation's).
5534    let _operation = crate::blend::BlendOperation::enter();
5535    if edge_points.is_empty() {
5536        return Err(KernelRefusal::input(
5537            KernelStage::Collect,
5538            "asymmetric_selection",
5539            "chamfer_edges_asymmetric: no edges selected",
5540        ));
5541    }
5542    let mut result = solid.clone();
5543    let mut done = vec![false; edge_points.len()];
5544    // `edge_names[index]` is keyed by INPUT position; the loop resolves each
5545    // point on the EVOLVING `result`, but enumerates the input points in order,
5546    // so the index alignment holds.
5547    for (index, point) in edge_points.iter().enumerate() {
5548        if done[index] {
5549            continue;
5550        }
5551        let edge_id = resolve_edge_by_point(&result, *point)?;
5552        let edge_name = per_edge_name(edge_names, name, index);
5553        // A smooth chain the selection covers whole is chamfered as one unit
5554        // (its setbacks run on through the tangent joins).
5555        if chamfer_asym_curved_on() {
5556            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5557                let faces = setback_faces(&result, edge_id)?;
5558                let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
5559                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_asymmetric", true)?;
5560                for member in members {
5561                    done[member] = true;
5562                }
5563                continue;
5564            }
5565        }
5566        result = chamfer_edge_asymmetric(&result, edge_id, d1, d2, edge_name)?;
5567        done[index] = true;
5568    }
5569    refuse_invalid_result(&result, "chamfer_edges_asymmetric")?;
5570    Ok(result)
5571}
5572
5573/// Distance-angle chamfer of a GROUP of edges, the app entry: each selected
5574/// edge (resolved by a point on it) gets a setback `d1` on face 1 and a chamfer
5575/// face at `angle_rad` from face 1 (§6.11); `d2` is constructed per edge.
5576pub fn chamfer_edges_angle(
5577    solid: &BrepSolid,
5578    edge_points: &[Vec3],
5579    edge_names: Option<&[String]>,
5580    d1: f64,
5581    angle_rad: f64,
5582    name: Option<&str>,
5583) -> Result<BrepSolid, KernelRefusal> {
5584    // One blend operation: the reports of an earlier one, never consumed, are
5585    // dropped as it starts (nested calls keep this operation's).
5586    let _operation = crate::blend::BlendOperation::enter();
5587    if edge_points.is_empty() {
5588        return Err(KernelRefusal::input(
5589            KernelStage::Collect,
5590            "angle_selection",
5591            "chamfer_edges_angle: no edges selected",
5592        ));
5593    }
5594    let mut result = solid.clone();
5595    let mut done = vec![false; edge_points.len()];
5596    for (index, point) in edge_points.iter().enumerate() {
5597        if done[index] {
5598            continue;
5599        }
5600        let edge_id = resolve_edge_by_point(&result, *point)?;
5601        let edge_name = per_edge_name(edge_names, name, index);
5602        // A smooth chain the selection covers whole is chamfered as one unit,
5603        // as `chamfer_edges_asymmetric` does.
5604        if chamfer_asym_curved_on() && d1 > 0.0 && d1.is_finite() && angle_rad > 1e-9 && angle_rad < std::f64::consts::PI {
5605            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5606                let [first, _] = setback_faces(&result, edge_id)?;
5607                let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
5608                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_angle", true)?;
5609                for member in members {
5610                    done[member] = true;
5611                }
5612                continue;
5613            }
5614        }
5615        result = chamfer_edge_angle(&result, edge_id, d1, angle_rad, edge_name)?;
5616        done[index] = true;
5617    }
5618    refuse_invalid_result(&result, "chamfer_edges_angle")?;
5619    Ok(result)
5620}
5621
5622/// Debug aid (`BREP_DEBUG_NETWORK`): every face loop as its coedge walk, with
5623/// each edge's stored vertices, so a loop the surgery left open can be read
5624/// against the input it was built from.
5625fn dump_loops_debug(label: &str, solid: &BrepSolid) {
5626    for shell in &solid.shells {
5627        for face in &shell.faces {
5628            for (index, loop_record) in face.loops.iter().enumerate() {
5629                let walk: Vec<String> = loop_record
5630                    .coedges
5631                    .iter()
5632                    .map(|coedge| {
5633                        // The pcurve's walk endpoints in the face's (u, v), so a
5634                        // loop that closes in space but not in parameter space
5635                        // (a periodic carrier's seam) is visible in the dump.
5636                        let uv = coedge
5637                            .pcurve
5638                            .domain()
5639                            .ok()
5640                            .and_then(|[q0, q1]| {
5641                                let a = coedge.pcurve.evaluate(q0).ok()?;
5642                                let b = coedge.pcurve.evaluate(q1).ok()?;
5643                                Some(format!("uv[({:.4},{:.4})->({:.4},{:.4})]", a.x, a.y, b.x, b.y))
5644                            })
5645                            .unwrap_or_default();
5646                        match solid.edges.iter().find(|e| e.id == coedge.edge_id) {
5647                            Some(edge) => format!(
5648                                "c{}:e{}{}({}->{}){uv}",
5649                                coedge.id,
5650                                edge.id,
5651                                if coedge.forward { "+" } else { "-" },
5652                                edge.start_vertex_id,
5653                                edge.end_vertex_id
5654                            ),
5655                            None => format!("c{}:e{}?MISSING", coedge.id, coedge.edge_id),
5656                        }
5657                    })
5658                    .collect();
5659                eprintln!(
5660                    "{label} face {} ({:?}) loop {index}: {}",
5661                    face.id,
5662                    face.name,
5663                    walk.join(" ")
5664                );
5665            }
5666        }
5667    }
5668}
5669
5670