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