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