Skip to main content

brep_kernel/feature_pipeline/features/
common.rs

1//! Shared feature parameters, reference resolution, and solid operations.
2
3use rustc_hash::FxHashSet;
4
5use crate::feature_pipeline::{
6    FeatureRefusal,
7    AddedSolid, Axis, EdgeRef, FaceRef, FeatureContext, FeatureResult, Frame, SketchProfile,
8};
9use crate::{AffineTransform, BooleanOperation, BooleanOptions, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, OrRefuse, Vec3, transform_brep};
10
11/// The one sentence every direction-reference field's hint carries (Pattern
12/// and Pattern Component `directionRef`, Waypoint `directionRef`), so the
13/// dialogs and the docs say the same thing about what a pick means. It
14/// matches the resolvers: a plane or planar face resolves to its normal, an
15/// edge to its start-to-end chord.
16pub const DIRECTION_FROM_REFERENCE: &str =
17    "A plane or planar face gives its normal; an edge or sketch line gives the direction from its start to its end.";
18
19/// Rotate a solid a half turn (180°) about the local X axis. This is a PROPER
20/// rotation (determinant +1), so `transform_brep` preserves face winding and every
21/// stamped face name. It realizes a NEGATIVE directional dimension: a primitive
22/// built along +Y with the value's MAGNITUDE is spun to occupy the -Y side, and a
23/// partial revolve/torus sweep is spun to the opposite side — exactly the geometry
24/// a signed value implies. `(x, y, z) -> (x, -y, -z)`.
25pub fn rotate_half_turn_about_x(solid: BrepSolid) -> Result<BrepSolid, String> {
26    let half_turn = AffineTransform::new([
27        1.0, 0.0, 0.0, 0.0,
28        0.0, -1.0, 0.0, 0.0,
29        0.0, 0.0, -1.0, 0.0,
30        0.0, 0.0, 0.0, 1.0,
31    ])?;
32    transform_brep(&solid, half_turn, false)
33}
34
35/// Collect `(face_id, name)` for every NAMED face, in shell/face order.
36pub fn collect_face_names(solid: &BrepSolid) -> Vec<(u64, String)> {
37    let mut names = Vec::new();
38    for shell in &solid.shells {
39        for face in &shell.faces {
40            if let Some(name) = &face.name {
41                names.push((face.id, name.clone()));
42            }
43        }
44    }
45    names
46}
47
48/// Collect `(edge_id, name)` for every NAMED edge.
49pub fn collect_edge_names(solid: &BrepSolid) -> Vec<(u64, String)> {
50    solid
51        .edges
52        .iter()
53        .filter_map(|edge| edge.name.as_ref().map(|name| (edge.id, name.clone())))
54        .collect()
55}
56
57/// Stamp one face's operation-role metadata (`faceRole` + `operationFaceType`,
58/// the established Sweep/Revolve convention the PMI dimension UI and tests read) into the
59/// kernel scene-metadata store, keyed by face NAME so it follows the face
60/// through booleans. Only the role keys are stamped — geometric metadata
61/// (`faceType`/`surfaceType`) stays inferred from the surface on the read side.
62pub fn stamp_face_role(face_name: &str, role: &str, op_type: &str) {
63    let mut record = serde_json::Map::new();
64    record.insert("faceRole".into(), serde_json::Value::String(role.into()));
65    record.insert(
66        "operationFaceType".into(),
67        serde_json::Value::String(op_type.into()),
68    );
69    crate::feature_pipeline::scene_metadata::merge_record(face_name, &record, true);
70}
71
72/// Stamp the whole sweep-family role convention on a BUILT solid's named faces:
73/// a name in `start_names`/`end_names` → `start_cap`/`STARTCAP` +
74/// `end_cap`/`ENDCAP`, any other name ending in `wall_suffix` →
75/// `sidewall`/`SIDEWALL`. Walking the actual faces (not the intended name list)
76/// means an absent cap (full revolve) or a skipped axis wall never leaves a
77/// phantom record in the store.
78///
79/// The lists are per-loop: each region of a multi-loop profile names its own
80/// caps (`{cap_base}:L{loopId}_START`), so the role pass takes the whole list
81/// rather than one name per end. A single-loop profile passes a one-element
82/// slice — there was a `stamp_sweep_roles` wrapper for that, and every caller
83/// went through this function instead, so it is gone.
84pub fn stamp_sweep_roles_multi(
85    solid: &BrepSolid,
86    wall_suffix: &str,
87    start_names: &[String],
88    end_names: &[String],
89) {
90    for face in solid.shells.iter().flat_map(|shell| shell.faces.iter()) {
91        let Some(name) = face.name.as_deref() else {
92            continue;
93        };
94        if start_names.iter().any(|start| start == name) {
95            stamp_face_role(name, "start_cap", "STARTCAP");
96        } else if end_names.iter().any(|end| end == name) {
97            stamp_face_role(name, "end_cap", "ENDCAP");
98        } else if name.ends_with(wall_suffix) {
99            stamp_face_role(name, "sidewall", "SIDEWALL");
100        }
101    }
102}
103
104/// The per-loop cap names of one profile-swept feature, plus the CONTAINER names
105/// they roll up into — the single place the per-loop cap convention is spelled,
106/// shared by extrude/sweep/revolve/path-sweep/loft so the five stay byte-identical.
107///
108/// `{cap_base}:{loop key}_START` / `_END` per region (see [`ProfileLoop::key`]),
109/// with `{cap_base}_START` / `_END` as the containers standing for all of them.
110/// A SINGLE-loop profile is the special case that matters most for compatibility:
111/// its one cap keys off its loop like any other, and its container has exactly one
112/// member, so every reference stored before per-loop naming resolves to exactly
113/// the face it always meant.
114pub struct CapNames {
115    /// Per region, in region order: `(start, end)`.
116    pub per_loop: Vec<(String, String)>,
117    pub start_container: String,
118    pub end_container: String,
119}
120
121impl CapNames {
122    /// Build the cap names for `regions` under `cap_base`.
123    ///
124    /// A region whose loop has no identity to key on (a FACE profile, a
125    /// hand-built profile) keeps the un-keyed `{cap_base}_START/_END` spelling it
126    /// has always had — such a profile is single-region, so there is nothing to
127    /// disambiguate and every saved reference to it stays exact.
128    pub fn new(cap_base: &str, regions: &[Vec<crate::feature_pipeline::ProfileLoop>]) -> Self {
129        let per_loop = regions
130            .iter()
131            .map(|region| {
132                match region.first().and_then(|outer| outer.key()) {
133                    Some(key) => (
134                        format!("{cap_base}:{key}_START"),
135                        format!("{cap_base}:{key}_END"),
136                    ),
137                    None => (format!("{cap_base}_START"), format!("{cap_base}_END")),
138                }
139            })
140            .collect();
141        Self {
142            per_loop,
143            start_container: format!("{cap_base}_START"),
144            end_container: format!("{cap_base}_END"),
145        }
146    }
147
148    /// This feature's `(container, members)` pairs for [`register_added_grouped`].
149    /// A container whose only member IS the container name (the un-keyed
150    /// single-region case) is dropped — the face is reachable exactly, so there is
151    /// no group to register.
152    pub fn containers(&self) -> Vec<(String, Vec<String>)> {
153        [
154            (self.start_container.clone(), self.starts()),
155            (self.end_container.clone(), self.ends()),
156        ]
157        .into_iter()
158        .filter(|(container, members)| members.as_slice() != [container.clone()])
159        .collect()
160    }
161
162    /// The INTERIOR cap names of a multi-segment sweep: one path SEGMENT's own
163    /// pair for `region_index`, spelled `{cap_base}:{loop key}:{segment}_START/_END`.
164    ///
165    /// A sweep along several path segments builds one portion per segment, and
166    /// every portion has two caps. The chain's own two ends keep the plain
167    /// per-loop spelling ([`Self::per_loop`]); every cap BETWEEN two portions is
168    /// a copy of the profile that the neighbouring portion's opposite cap cancels
169    /// in the union, so it normally does not reach the result at all. Naming it
170    /// after its segment anyway means that if a path ever leaves one standing
171    /// (a chain that doubles back), it arrives with a name tied to the segment
172    /// that built it instead of a positional `[n]` disambiguation.
173    pub fn interior(&self, region_index: usize, segment: &str) -> (String, String) {
174        let (start, end) = &self.per_loop[region_index];
175        let start_base = start.strip_suffix("_START").unwrap_or(start);
176        let end_base = end.strip_suffix("_END").unwrap_or(end);
177        (
178            format!("{start_base}:{segment}_START"),
179            format!("{end_base}:{segment}_END"),
180        )
181    }
182
183    /// All per-loop START names, for [`stamp_sweep_roles_multi`].
184    pub fn starts(&self) -> Vec<String> {
185        self.per_loop.iter().map(|(start, _)| start.clone()).collect()
186    }
187
188    /// All per-loop END names, for [`stamp_sweep_roles_multi`].
189    pub fn ends(&self) -> Vec<String> {
190        self.per_loop.iter().map(|(_, end)| end.clone()).collect()
191    }
192}
193
194pub(super) fn parse_boolean_operation(operation: &str) -> Result<BooleanOperation, String> {
195    match operation {
196        "UNION" => Ok(BooleanOperation::Union),
197        "SUBTRACT" => Ok(BooleanOperation::Subtract),
198        "INTERSECT" => Ok(BooleanOperation::Intersect),
199        other => Err(format!("unsupported boolean operation '{other}'")),
200    }
201}
202
203/// The optional `boolean` param, parsed from `inputParams.boolean`.
204struct BooleanParam {
205    operation: String,
206    targets: Vec<String>,
207    merge_coplanar_faces: bool,
208}
209
210fn read_boolean_param(ctx: &FeatureContext) -> BooleanParam {
211    let boolean = ctx.param("boolean");
212    let operation = boolean
213        .and_then(|value| value.get("operation"))
214        .and_then(|value| value.as_str())
215        .unwrap_or("NONE")
216        .to_uppercase();
217    let targets = boolean
218        .and_then(|value| value.get("targets"))
219        .and_then(|value| value.as_array())
220        .map(|array| {
221            array
222                .iter()
223                .filter_map(|entry| entry.as_str())
224                .map(|name| name.trim().to_string())
225                .filter(|name| !name.is_empty())
226                .collect()
227        })
228        .unwrap_or_default();
229    let merge_coplanar_faces = boolean
230        .and_then(|value| value.get("mergeCoplanarFaces"))
231        .and_then(|value| value.as_bool())
232        .unwrap_or(true);
233    BooleanParam {
234        operation,
235        targets,
236        merge_coplanar_faces,
237    }
238}
239
240/// What a boolean with an operation and NO picked target acts on (owner
241/// 2026-11-07): "If there is only one solid body in a part … it should
242/// automatically use the one existing solid … In cases where multiple solids
243/// are in the part the user would have to pick the target."
244#[derive(Debug, Clone, PartialEq, Eq)]
245pub(crate) enum ImplicitTarget {
246    /// The part holds no solid: the body stands alone, as it always has.
247    NoSolid,
248    /// The part's only solid, used exactly as if the user had picked it.
249    Sole(String),
250    /// Two or more solids, sorted by name: nothing is guessed. The body stands
251    /// alone and the feature reports that the user must pick the target.
252    Several(Vec<String>),
253}
254
255/// The solids "in the part" that a no-target boolean may fall back to, sorted
256/// by name: every solid the scene holds BEFORE this feature (the feature's own
257/// body is never scene-resident while it finalizes), except the members of an
258/// inserted assembly COMPONENT — component geometry is another part, fenced off
259/// as modeling-feature input (`enforce_reference_fence`), so an implicit pick
260/// must not reach it either. The kernel scene has no visibility or
261/// construction state: a body hidden in the viewport is still in the part and
262/// counts, so what a feature builds never depends on a display toggle.
263pub(crate) fn implicit_target_candidates(scene: &crate::feature_pipeline::SceneMap) -> Vec<String> {
264    let mut names: Vec<String> = scene
265        .solids
266        .keys()
267        .filter(|name| !scene.is_component_owned(name))
268        .cloned()
269        .collect();
270    names.sort();
271    names
272}
273
274/// Classify the scene for a no-target boolean ([`ImplicitTarget`]).
275pub(crate) fn implicit_boolean_target(scene: &crate::feature_pipeline::SceneMap) -> ImplicitTarget {
276    let mut names = implicit_target_candidates(scene);
277    match names.len() {
278        0 => ImplicitTarget::NoSolid,
279        1 => ImplicitTarget::Sole(names.remove(0)),
280        _ => ImplicitTarget::Several(names),
281    }
282}
283
284/// Whether a feature descriptor asks for the implicit target: its `boolean`
285/// carries an operation (UNION/SUBTRACT/INTERSECT, or anything but NONE) and
286/// no target name. Read by the history loop so the cache keys such a feature
287/// on the part's solids — it names none of them, so the descriptor scan alone
288/// would replay it after its implicit target changed, was renamed, or gained a
289/// sibling. A HOLE's absent operation means SUBTRACT (its own default) and its
290/// target entries may be `{ name }` objects; the BOOLEAN feature's `targets`
291/// are its TOOLS, so it never asks.
292pub(crate) fn wants_implicit_target(feature_type: &str, input_params: &serde_json::Value) -> bool {
293    // A sheet-metal feature with no `sheet` works on the sole sheet body
294    // (`sheet_body_name`), which its descriptor never names either: the
295    // history-cache read trace found an auto-targeted cutout replayed against
296    // a sheet that had since changed.
297    if matches!(feature_type, "SM.CUTOUT" | "SM.MIRROR" | "SM.FILLET" | "SM.CHAMFER") {
298        return single_reference_name(input_params.get("sheet")).is_none();
299    }
300    let is_hole = matches!(feature_type, "H" | "HOLE");
301    if matches!(feature_type, "B" | "BOOLEAN") {
302        return false;
303    }
304    let boolean = input_params.get("boolean");
305    if boolean.is_none() && !is_hole {
306        return false;
307    }
308    let operation = boolean
309        .and_then(|value| value.get("operation"))
310        .and_then(|value| value.as_str())
311        .unwrap_or(if is_hole { "SUBTRACT" } else { "NONE" });
312    if operation.eq_ignore_ascii_case("NONE") {
313        return false;
314    }
315    let named = boolean
316        .and_then(|value| value.get("targets"))
317        .and_then(|value| value.as_array())
318        .is_some_and(|array| {
319            array.iter().any(|entry| {
320                entry
321                    .as_str()
322                    .or_else(|| if is_hole { entry.get("name").and_then(|name| name.as_str()) } else { None })
323                    .is_some_and(|name| !name.trim().is_empty())
324            })
325        });
326    !named
327}
328
329/// The `fulfilment` a no-target boolean reports when the part holds several
330/// solids: the body was built and stands alone, and the user must pick which
331/// solid it booleans into. Shown as the feature's banner and tree leaf.
332pub(crate) fn several_targets_fulfilment(operation: &str, solids: &[String]) -> crate::feature_pipeline::Fulfilment {
333    let listed: Vec<String> = solids.iter().map(|name| format!("`{name}`")).collect();
334    crate::feature_pipeline::Fulfilment {
335        requested: Vec::new(),
336        applied: Vec::new(),
337        rejected: vec![crate::feature_pipeline::Rejected {
338            name: "boolean".to_string(),
339            kind: crate::feature_pipeline::RejectedKind::NothingSelected,
340            reason: format!(
341                "{} names no target and the part holds {} solids ({}): pick the target solid; the body stands alone until you do",
342                operation.to_lowercase(),
343                solids.len(),
344                listed.join(", ")
345            ),
346        }],
347        extended: Vec::new(),
348        followed: Vec::new(),
349    }
350}
351
352/// Resolve a no-target boolean in place: the sole solid becomes `targets`
353/// (recorded on `result.boolean_auto_target`), several solids record the
354/// pick-a-target fulfilment. Returns `false` when the body must stand alone.
355fn apply_implicit_target(ctx: &FeatureContext, boolean: &mut BooleanParam, result: &mut FeatureResult) -> bool {
356    match implicit_boolean_target(ctx.scene) {
357        ImplicitTarget::NoSolid => false,
358        ImplicitTarget::Sole(name) => {
359            result.boolean_auto_target = Some(name.clone());
360            boolean.targets = vec![name];
361            true
362        }
363        ImplicitTarget::Several(names) => {
364            result.fulfilment = Some(several_targets_fulfilment(&boolean.operation, &names));
365            false
366        }
367    }
368}
369pub use crate::face_names::{ensure_unique_face_names, stamp_derived_edge_names};
370#[allow(unused_imports)]
371use crate::face_names::collect_edge_face_names;
372
373
374/// Suffix copied face and authored-edge names with `::{suffix}`, then regenerate
375/// topology-edge names from the renamed faces. This keeps copies distinct from
376/// their sources in the scene's name lookup. Empty names are skipped.
377pub fn namespace_copy_names(solid: &mut BrepSolid, suffix: &str) {
378    for shell in &mut solid.shells {
379        for face in &mut shell.faces {
380            if let Some(name) = face.name.as_ref() {
381                let trimmed = name.trim();
382                if !trimmed.is_empty() {
383                    face.name = Some(format!("{trimmed}::{suffix}"));
384                }
385            }
386        }
387    }
388    for edge in &mut solid.edges {
389        if let Some(name) = edge.name.as_ref() {
390            let trimmed = name.trim();
391            // Topology edges (`|`) are re-derived below from the retagged faces;
392            // authored edges take the suffix directly.
393            if !trimmed.is_empty() && !trimmed.contains('|') {
394                edge.name = Some(format!("{trimmed}::{suffix}"));
395            }
396        }
397    }
398    stamp_derived_edge_names(solid);
399}
400
401/// Register a freshly built base solid as a single `AddedSolid` under `name`.
402/// Deduplicates FACE names, then stamps the derived `{faceA}|{faceB}[n]` names
403/// onto the edges (which embed the now-unique face names), so face AND edge
404/// reference_selections both resolve uniquely against the scene.
405pub fn register_added(base: BrepSolid, name: &str) -> AddedSolid {
406    register_added_grouped(base, name, &[])
407}
408
409/// [`register_added`] plus CONTAINER groups: `containers` is
410/// `(container_name, member_face_names)`, the un-keyed name a profile-swept
411/// feature publishes for all of its per-loop faces at once (`{cap_base}_START`
412/// standing for every `{cap_base}:L{id}_START`).
413///
414/// Members are resolved against the FINAL solid, so a face a boolean merged or
415/// consumed simply drops out of its group, and a container whose members all
416/// vanished registers nothing. Each container also gets the EDGE group implied by
417/// it — see [`collect_edge_group_aliases`].
418pub fn register_added_grouped(
419    mut base: BrepSolid,
420    name: &str,
421    containers: &[(String, Vec<String>)],
422) -> AddedSolid {
423    ensure_unique_face_names(&mut base);
424    stamp_derived_edge_names(&mut base);
425    let face_names = collect_face_names(&base);
426    let edge_names = collect_edge_names(&base);
427    let face_groups = collect_face_groups(&face_names, containers);
428    let mut edge_groups = collect_edge_group_aliases(&base, containers);
429    collect_derived_edge_bases(&edge_names, &mut edge_groups);
430    let handle = crate::register_solid_value(base);
431    AddedSolid {
432        handle,
433        name: name.to_string(),
434        face_names,
435        edge_names,
436        face_groups,
437        edge_groups,
438    }
439}
440
441/// Publish each derived edge name's BASE — `{faceA}|{faceB}` without the `[n]`
442/// — as a group standing for every edge that carries it.
443///
444/// [`stamp_derived_edge_names`] always appends the index, even where a face
445/// pair meets along a single edge, so the bare base is never an edge name and a
446/// reference stored as one resolves to nothing on its own. Bare bases are
447/// exactly what a model saved against an UNSTAMPED solid holds — the standalone
448/// Boolean feature published the imprint's raw `{faceA}|{faceB}` until it
449/// started stamping like every other feature — so they must keep naming the
450/// edges they always named.
451///
452/// The group carries every member, which is what [`SceneMap::resolve_edge`]
453/// (single) and [`SceneMap::resolve_edge_group`] (fan-out) already read
454/// correctly: a base one edge carries resolves everywhere, one several edges
455/// carry stays ambiguous for a single-edge consumer and fans out for a
456/// selection. A base an EXACT edge name already spells is left alone (both
457/// resolvers try the exact map first, so it could never be reached), and so is
458/// one a container alias already claims.
459fn collect_derived_edge_bases(
460    edge_names: &[(u64, String)],
461    groups: &mut Vec<(String, Vec<String>)>,
462) {
463    use std::collections::HashSet;
464    let taken: HashSet<&str> = groups.iter().map(|(name, _)| name.as_str()).collect();
465    let exact: HashSet<&str> = edge_names.iter().map(|(_, name)| name.as_str()).collect();
466    let mut bases: Vec<(String, Vec<String>)> = Vec::new();
467    for (_, name) in edge_names {
468        // `{base}[{index}]`: the index is the trailing bracketed run of digits.
469        let Some(base) = name.strip_suffix(']').and_then(|head| {
470            let at = head.rfind('[')?;
471            let (base, index) = (&head[..at], &head[at + 1..]);
472            (!index.is_empty() && index.bytes().all(|byte| byte.is_ascii_digit()))
473                .then_some(base)
474        }) else {
475            continue;
476        };
477        if base.is_empty() || !base.contains('|') {
478            continue;
479        }
480        if taken.contains(base) || exact.contains(base) {
481            continue;
482        }
483        match bases.iter_mut().find(|(existing, _)| existing == base) {
484            Some((_, members)) => members.push(name.clone()),
485            None => bases.push((base.to_string(), vec![name.clone()])),
486        }
487    }
488    groups.append(&mut bases);
489}
490
491/// Keep each container's member NAMES that actually survived onto the final
492/// solid. Containers with no surviving member are dropped.
493fn collect_face_groups(
494    face_names: &[(u64, String)],
495    containers: &[(String, Vec<String>)],
496) -> Vec<(String, Vec<String>)> {
497    let mut groups = Vec::new();
498    for (container, members) in containers {
499        let live: Vec<String> = members
500            .iter()
501            .filter(|member| face_names.iter().any(|(_, name)| name == *member))
502            .cloned()
503            .collect();
504        if !live.is_empty() {
505            groups.push((container.clone(), live));
506        }
507    }
508    groups
509}
510
511/// The CONTAINER-name spelling of each derived edge name.
512///
513/// Derived edge names embed face names (`{faceA}|{faceB}[n]`), so keying the caps
514/// renamed every cap-adjacent edge along with them — a saved fillet on the top
515/// edge of a box references a name no face pair spells any more. This recomputes
516/// each edge's derived name with every member face name replaced by its container
517/// name, and registers THAT as an alias for the edge.
518///
519/// It mirrors [`stamp_derived_edge_names`] step for step — same adjacency, same
520/// encounter order, same per-base counter, substitution applied BEFORE the pair is
521/// sorted (a substituted name can sort differently from the one it replaced). So
522/// when the mapping is 1:1 — every model with a single-loop profile, i.e. every
523/// model saved before per-loop naming — the alias is byte-identical to the name
524/// that solid's edges used to carry.
525fn collect_edge_group_aliases(
526    solid: &BrepSolid,
527    containers: &[(String, Vec<String>)],
528) -> Vec<(String, Vec<String>)> {
529    use std::collections::HashMap;
530    if containers.is_empty() {
531        return Vec::new();
532    }
533    // member face name -> its container name.
534    let mut container_of: HashMap<&str, &str> = HashMap::new();
535    for (container, members) in containers {
536        for member in members {
537            container_of.insert(member.as_str(), container.as_str());
538        }
539    }
540
541    let (edge_faces, encounter_order) = collect_edge_face_names(solid);
542
543    let solid_name_fallback = "Solid".to_string();
544    let mut base_counts: HashMap<String, usize> = HashMap::new();
545    let mut aliases: HashMap<String, Vec<String>> = HashMap::new();
546    let mut order: Vec<String> = Vec::new();
547    for edge_id in encounter_order {
548        let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else {
549            continue;
550        };
551        if edge.degenerate {
552            continue;
553        }
554        // Only edges `stamp_derived_edge_names` actually named advance its
555        // counter, so only those advance this one.
556        if !edge.name.as_deref().is_none_or(|name| name.contains('|')) {
557            continue;
558        }
559        let mut faces: Vec<String> = edge_faces
560            .get(&edge_id)
561            .map(|list| list.iter().filter(|name| !name.is_empty()).cloned().collect())
562            .unwrap_or_default();
563        // Substitute BEFORE sorting — a container name need not sort where the
564        // member name it replaces did.
565        let substituted = faces.iter().any(|name| container_of.contains_key(name.as_str()));
566        for face in &mut faces {
567            if let Some(container) = container_of.get(face.as_str()) {
568                *face = (*container).to_string();
569            }
570        }
571        faces.sort();
572        let base = if faces.len() >= 2 {
573            format!("{}|{}", faces[0], faces[1])
574        } else {
575            format!("{}|BOUNDARY", faces.first().unwrap_or(&solid_name_fallback))
576        };
577        let index = base_counts.entry(base.clone()).or_insert(0);
578        let alias = format!("{base}[{index}]");
579        *index += 1;
580        // An edge touching no member face spells its own name — nothing to alias.
581        // An edge whose alias IS its own name needs none either.
582        let Some(live) = edge.name.clone() else { continue };
583        if !substituted || live == alias {
584            continue;
585        }
586        if aliases.entry(alias.clone()).or_default().is_empty() {
587            order.push(alias.clone());
588        }
589        aliases.get_mut(&alias).expect("just inserted").push(live);
590    }
591    order
592        .into_iter()
593        .map(|alias| {
594            let ids = aliases.remove(&alias).unwrap_or_default();
595            (alias, ids)
596        })
597        .filter(|(_, ids)| !ids.is_empty())
598        .collect()
599}
600
601/// Finalize several bodies using the optional boolean operation. An operation
602/// with no picked target uses the part's only solid ([`ImplicitTarget`]).
603/// Without an operation or resolved targets, register each body separately. Otherwise fold
604/// bodies into the targets in order and use the first target's name. Missing
605/// targets are reported in `unresolved` for the caller to repair.
606pub fn finalize_solids(ctx: &FeatureContext, bodies: Vec<(String, BrepSolid)>) -> FeatureResult {
607    let mut boolean = read_boolean_param(ctx);
608    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
609
610    let separate = |mut result: FeatureResult, bodies: Vec<(String, BrepSolid)>| {
611        for (name, solid) in bodies {
612            result.added.push(register_added(solid, &name));
613        }
614        result
615    };
616
617    if boolean.operation == "NONE" {
618        return separate(result, bodies);
619    }
620    // No target picked: the part's only solid, or nothing (see `ImplicitTarget`).
621    if boolean.targets.is_empty() && !apply_implicit_target(ctx, &mut boolean, &mut result) {
622        return separate(result, bodies);
623    }
624    let operation = match parse_boolean_operation(&boolean.operation) {
625        Ok(operation) => operation,
626        Err(error) => return ctx.fail(error),
627    };
628    let resolved = resolve_solid_names(ctx.scene, &boolean.targets, &mut result.unresolved);
629    if resolved.is_empty() {
630        return separate(result, bodies);
631    }
632    let options = BooleanOptions {
633        merge_coplanar_faces: boolean.merge_coplanar_faces,
634        seam_rejoin_later_references: ctx.rejoin_references.map(<[String]>::to_vec),
635        ..BooleanOptions::default()
636    };
637    let mut bodies = bodies.into_iter();
638    let Some((_, first)) = bodies.next() else {
639        return result; // no bodies at all (shouldn't happen; callers gate)
640    };
641    // Fold the first body through every target (mirrors `finalize_solid`), then
642    // fold each remaining body into the running result (targets already merged in).
643    let mut current = first;
644    for (_, target_handle) in &resolved {
645        let operand = crate::register_solid_value(current);
646        let folded = crate::with_two_registered_solids(*target_handle, operand, |target, op_solid| {
647            crate::boolean_operation(target, op_solid, operation, &options)
648        });
649        crate::free_registered_solid(operand);
650        match folded {
651            Ok(solid) => current = solid,
652            Err(error) => return ctx.fail(format!("boolean {} failed: {error}", boolean.operation)),
653        }
654    }
655    for (_, body) in bodies {
656        match crate::boolean_operation(&current, &body, operation, &options) {
657            Ok(solid) => current = solid,
658            Err(error) => return ctx.fail(format!("boolean {} failed: {error}", boolean.operation)),
659        }
660    }
661    result.added.push(register_added(current, &resolved[0].0));
662    result.removed = resolved.into_iter().map(|(name, _)| name).collect();
663    result
664}
665
666pub fn finalize_solid(ctx: &FeatureContext, base: BrepSolid, base_name: &str) -> FeatureResult {
667    finalize_solid_grouped(ctx, base, base_name, &[])
668}
669
670/// [`finalize_solid`] carrying CONTAINER groups (the profile-swept features'
671/// per-loop cap roll-ups) onto whichever solid ends up registered — the base
672/// itself, or the boolean's result when one is folded. Members that the boolean
673/// consumed drop out of their group on their own (`register_added_grouped`
674/// resolves members against the FINAL solid).
675pub fn finalize_solid_grouped(
676    ctx: &FeatureContext,
677    base: BrepSolid,
678    base_name: &str,
679    containers: &[(String, Vec<String>)],
680) -> FeatureResult {
681    let mut boolean = read_boolean_param(ctx);
682    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
683
684    let stands_alone = boolean.operation == "NONE"
685        || (boolean.targets.is_empty() && !apply_implicit_target(ctx, &mut boolean, &mut result));
686    if stands_alone {
687        result.added.push(register_added_grouped(base, base_name, containers));
688        return result;
689    }
690
691    let operation = match parse_boolean_operation(&boolean.operation) {
692        Ok(operation) => operation,
693        Err(error) => return ctx.fail(error),
694    };
695
696    let resolved = resolve_solid_names(ctx.scene, &boolean.targets, &mut result.unresolved);
697
698    // Nothing resolved: emit the base un-booleaned; `unresolved` signals the caller to
699    // repair + re-dispatch (NOT a hard error — Stage 5 gate).
700    if resolved.is_empty() {
701        result.added.push(register_added_grouped(base, base_name, containers));
702        return result;
703    }
704
705    let options = BooleanOptions {
706        merge_coplanar_faces: boolean.merge_coplanar_faces,
707        seam_rejoin_later_references: ctx.rejoin_references.map(<[String]>::to_vec),
708        ..BooleanOptions::default()
709    };
710    // Fold, keeping the running result as a LOCAL owned BrepSolid: register only
711    // the operand needed for the two-solid borrow, fold, free that operand — no
712    // leaked intermediates. The base primitive is never itself scene-resident.
713    let mut current = base;
714    for (_, target_handle) in &resolved {
715        let operand_handle = crate::register_solid_value(current);
716        let folded = crate::with_two_registered_solids(*target_handle, operand_handle, |target, operand| {
717            crate::boolean_operation(target, operand, operation, &options)
718        });
719        crate::free_registered_solid(operand_handle);
720        match folded {
721            Ok(solid) => current = solid,
722            Err(error) => return ctx.fail(format!("boolean {} failed: {error}", boolean.operation)),
723        }
724    }
725
726    let result_name = resolved[0].0.clone();
727    result
728        .added
729        .push(register_added_grouped(current, &result_name, containers));
730    result.removed = resolved.into_iter().map(|(name, _)| name).collect();
731    result
732}
733
734// ===========================================================================
735// Dressup edge/face selection — shared by fillet.rs (F) and chamfer.rs (CH)
736// ===========================================================================
737//
738// Fillet and chamfer share selection resolution; chamfer alone validates its
739// `direction`.
740// Each feature owns its numeric parameters, kernel call, and abort policy.
741
742/// One solid and sampled edge points for a fillet or chamfer operation.
743pub struct BlendTarget {
744    pub handle: u32,
745    pub name: String,
746    pub edge_points: Vec<Vec3>,
747    /// Canonical names parallel to `edge_points`, used to name generated faces.
748    /// Unnamed edges fall back to `E{edge_id}`.
749    pub edge_names: Vec<String>,
750    /// The selected edges' ids on the target solid, parallel to `edge_points`.
751    pub edge_ids: Vec<u64>,
752    /// The ids among `edge_ids` that were picked AS EDGES (not gathered from
753    /// a picked face's boundary): what the fillet's "Follow tangent" grows.
754    pub picked_edge_ids: Vec<u64>,
755}
756
757/// Resolved blend selection; callers decide how to handle cross-solid input.
758pub struct BlendSelection {
759    /// Present when at least one reference resolves, all to the same solid.
760    pub target: Option<BlendTarget>,
761    pub multi_solid: bool,
762    /// Missing edge/face names for the caller to repair and redispatch.
763    pub unresolved: Vec<String>,
764}
765
766/// One resolved ref: which topology entity of the owning solid it names.
767enum ResolvedRef {
768    Edge(u64),
769    Face(u64),
770}
771
772/// A `reference_selection` entry -> its name: a plain string, or an object with a
773/// `name` field. No token-splitting / `[N]`-index /
774/// snapshot-scoring — exact match only (contract rule 1 forbids the heuristic).
775pub(crate) fn reference_name(value: &serde_json::Value) -> Option<String> {
776    let raw = match value {
777        serde_json::Value::String(text) => Some(text.as_str()),
778        serde_json::Value::Object(map) => map.get("name").and_then(|value| value.as_str()),
779        _ => None,
780    }?;
781    let trimmed = raw.trim();
782    (!trimmed.is_empty()).then(|| trimmed.to_string())
783}
784
785/// The canonical scene name of an edge (`{faceA}|{faceB}[n]`, stamped by
786/// `stamp_derived_edge_names`), used to name the blend face grown from it. An
787/// unnamed / empty edge (e.g. a hand-built test solid never run through the
788/// canonical pass) falls back to a deterministic `E{edge_id}` so parallel blend
789/// faces still get DISTINCT, stable names.
790fn edge_name_or_id(solid: &BrepSolid, edge_id: u64) -> String {
791    solid
792        .edges
793        .iter()
794        .find(|edge| edge.id == edge_id)
795        .and_then(|edge| edge.name.clone())
796        .filter(|name| !name.is_empty())
797        .unwrap_or_else(|| format!("E{edge_id}"))
798}
799
800/// Midpoint of an edge's curve (`evaluate((t0 + t1) / 2)`) — the sample the kernel
801/// decodes back to the edge.
802fn sample_edge_midpoint(solid: &BrepSolid, edge_id: u64) -> Result<Vec3, String> {
803    let edge = solid
804        .edges
805        .iter()
806        .find(|edge| edge.id == edge_id)
807        .ok_or_else(|| format!("dressup: edge {edge_id} not found on target solid"))?;
808    let mid = (edge.t0 + edge.t1) * 0.5;
809    edge.curve
810        .evaluate(mid)
811        .map_err(|error| format!("dressup: edge {edge_id} midpoint sample failed: {error}"))
812}
813
814/// Boundary edge ids of a face (its loops' coedges), deduped, skipping DEGENERATE
815/// (pole) edges — "fillet a face" means "fillet all its real shared edges".
816///
817/// The SEAM of a cylindrical or conical face (an edge both of whose coedges lie
818/// on that face) is skipped too: the surface runs on smoothly across it, so
819/// there is no corner to blend, and picking the side of a cylinder means its
820/// rims. Only the face expansion skips it; a seam picked as an edge is kept.
821fn face_boundary_edges(solid: &BrepSolid, face_id: u64) -> Result<Vec<u64>, String> {
822    let face = solid
823        .shells
824        .iter()
825        .flat_map(|shell| &shell.faces)
826        .find(|face| face.id == face_id)
827        .ok_or_else(|| format!("dressup: face {face_id} not found on target solid"))?;
828    let ruled_revolution = matches!(
829        face.surface.analytic(),
830        Some(crate::AnalyticSurface::RuledRevolution { .. })
831    );
832    let mut seams = FxHashSet::default();
833    if ruled_revolution {
834        let mut uses = FxHashSet::default();
835        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
836            if !uses.insert(coedge.edge_id) {
837                seams.insert(coedge.edge_id);
838            }
839        }
840    }
841    let mut ids = Vec::new();
842    let mut seen = FxHashSet::default();
843    for loop_record in &face.loops {
844        for coedge in &loop_record.coedges {
845            if seams.contains(&coedge.edge_id) {
846                continue;
847            }
848            let degenerate = solid
849                .edges
850                .iter()
851                .find(|edge| edge.id == coedge.edge_id)
852                .map(|edge| edge.degenerate)
853                .unwrap_or(false);
854            if degenerate {
855                continue;
856            }
857            if seen.insert(coedge.edge_id) {
858                ids.push(coedge.edge_id);
859            }
860        }
861    }
862    Ok(ids)
863}
864
865/// Resolve the `edges` `reference_selection` (EDGE and/or FACE names) against the
866/// live scene-map and sample one 3D point per selected edge. Exact-match only;
867/// misses accumulate into `unresolved`. Errs only on a genuine geometry/lookup
868/// failure while sampling the resolved solid.
869pub fn resolve_blend_selection(ctx: &FeatureContext) -> Result<BlendSelection, String> {
870    let names = reference_names(ctx.param("edges"));
871
872    let mut unresolved = Vec::new();
873    let mut resolved: Vec<(u32, ResolvedRef)> = Vec::new();
874    for name in names {
875        // Exact edge, exact face, then the CONTAINER groups — a name a model
876        // stored before per-loop cap naming stands for every face (or edge) the
877        // feature built from that profile, so a fillet on "the end cap" of a
878        // 3-loop extrude blends all three, and one on a single-loop extrude
879        // blends the one face it always meant.
880        let edges = ctx.scene.resolve_edge_group(&name);
881        let faces = ctx.scene.resolve_face_group(&name);
882        if edges.is_empty() && faces.is_empty() {
883            unresolved.push(name);
884            continue;
885        }
886        for edge in edges {
887            resolved.push((edge.handle, ResolvedRef::Edge(edge.edge_id)));
888        }
889        for face in faces {
890            resolved.push((face.handle, ResolvedRef::Face(face.face_id)));
891        }
892    }
893
894    // Distinct owning handles among the resolved refs.
895    let mut handles: Vec<u32> = resolved.iter().map(|(handle, _)| *handle).collect();
896    handles.sort_unstable();
897    handles.dedup();
898    if handles.len() > 1 {
899        return Ok(BlendSelection {
900            target: None,
901            multi_solid: true,
902            unresolved,
903        });
904    }
905    let Some(&handle) = handles.first() else {
906        // Nothing resolved: `unresolved` carries the misses (rule 1); no target.
907        return Ok(BlendSelection {
908            target: None,
909            multi_solid: false,
910            unresolved,
911        });
912    };
913
914    // Reverse-lookup the target's scene name — the result reuses it (loop
915    // removes-then-adds, freeing the consumed handle), matching the established dressup naming
916    // (`new Solid(kernel, { name: targetSolid.name })`).
917    let name = ctx
918        .scene
919        .solids
920        .iter()
921        .find(|(_, &registered)| registered == handle)
922        .map(|(name, _)| name.clone())
923        .ok_or_else(|| format!("dressup: target handle {handle} has no scene name"))?;
924
925    // Sample one point per selected edge; dedup edge ids GLOBALLY across all refs
926    // (dedup spans the whole selection, not per-face) in a single short borrow.
927    // The originating edge NAME is captured PARALLEL to each point so the grown
928    // blend face can be named after the edge it came from.
929    let (edge_points, edge_names, edge_ids, picked_edge_ids) = crate::with_registered_solid_str(handle, |solid| {
930        let mut seen = FxHashSet::default();
931        let mut picked = Vec::new();
932        let mut points = Vec::new();
933        let mut names = Vec::new();
934        let mut ids = Vec::new();
935        for (_, entity) in &resolved {
936            match entity {
937                ResolvedRef::Edge(edge_id) => {
938                    if !picked.contains(edge_id) {
939                        picked.push(*edge_id);
940                    }
941                    if seen.insert(*edge_id) {
942                        points.push(sample_edge_midpoint(solid, *edge_id)?);
943                        names.push(edge_name_or_id(solid, *edge_id));
944                        ids.push(*edge_id);
945                    }
946                }
947                ResolvedRef::Face(face_id) => {
948                    for edge_id in face_boundary_edges(solid, *face_id)? {
949                        if seen.insert(edge_id) {
950                            points.push(sample_edge_midpoint(solid, edge_id)?);
951                            names.push(edge_name_or_id(solid, edge_id));
952                            ids.push(edge_id);
953                        }
954                    }
955                }
956            }
957        }
958        Ok((points, names, ids, picked))
959    })?;
960
961    Ok(BlendSelection {
962        target: Some(BlendTarget {
963            handle,
964            name,
965            edge_points,
966            edge_names,
967            edge_ids,
968            picked_edge_ids,
969        }),
970        multi_solid: false,
971        unresolved,
972    })
973}
974
975/// The unselected edges that continue `selected` along OPEN tangent chains:
976/// from each end vertex of each selected edge, walk the single other edge
977/// whose tangent there continues the chain's (unit tangents within 1e-6 of
978/// parallel, the blend's own conjugacy bar), until a vertex has no such edge
979/// or more than one, the walk reaches a selected edge, or it closes. Returns
980/// each added edge's `(id, midpoint sample, name)` in walk order; empty when
981/// no selected edge ends inside a tangent chain.
982///
983/// A fillet that stops at a vertex where its edge runs on smoothly has no
984/// clean end there when a mate's CARRIER changes across that vertex — the
985/// cap plane normal to the edge can cross the mate's tangent seam with the
986/// next surface (the 2026-10-14 bore-wall reports) — and every mainstream
987/// kernel blends such a chain whole. So a walk starts only from a selected
988/// end where the continuation's mates are not both on the selected edge's
989/// own carriers: an end at a mere split of the same two surfaces caps
990/// cleanly and is left as selected — unless nothing else meets that vertex.
991/// There the two edges are one curve the boolean split (the cap-rim report,
992/// 2026-10-25: a sculpted cap's rim in pieces 0.27 and 22.85 long, the user
993/// picking the short one), both mates' next boundary edge is the same edge,
994/// and no cap can be built (`shared_end_boundary`); the chain is walked on.
995/// The fillet feature reads this only after the plain selection has refused,
996/// as a one-time fallback.
997pub fn open_tangent_chain_extension(solid: &BrepSolid, selected: &[u64]) -> Result<Vec<(u64, Vec3, String)>, String> {
998    walk_tangent_chains(solid, selected, selected, false)
999}
1000
1001/// The fillet's "Follow tangent" option: every unselected edge on the G1
1002/// tangent chains through `seeds` (the edges picked as edges), closed loops
1003/// included, as `(id, midpoint sample, name)` in walk order, de-duplicated
1004/// against `selected` (the whole selection, face-gathered edges included)
1005/// and each other.
1006///
1007/// The rule is the open-chain walk's ([`open_tangent_chain_extension`])
1008/// without its first-step carrier guard, which exists only for the refusal
1009/// fallback: from each end vertex of each seed edge, take the single
1010/// other edge whose unit tangent there continues the chain's within 1e-6 of
1011/// parallel (the blend's own conjugacy bar). A walk stops at a sharp junction
1012/// (no tangent continuation), at an ambiguous one (more than one tangent
1013/// continuation), at an edge already taken (a selected edge, or the seed
1014/// again when the chain closes). A closed single-edge loop (a circle rim)
1015/// is its own whole chain and adds nothing.
1016pub fn tangent_chain_expansion(
1017    solid: &BrepSolid,
1018    seeds: &[u64],
1019    selected: &[u64],
1020) -> Result<Vec<(u64, Vec3, String)>, String> {
1021    walk_tangent_chains(solid, seeds, selected, true)
1022}
1023
1024/// The one continuation a tangent walk takes from a vertex: among the
1025/// candidate edges' tangents leaving it, those within 1e-6 of parallel to
1026/// `onward`; `None` when there is none (a sharp junction ends the chain) or
1027/// more than one (an ambiguous junction ends it too).
1028pub(super) fn single_tangent_continuation(candidates: &[(u64, Vec3)], onward: Vec3) -> Option<u64> {
1029    let mut tangent = candidates.iter().filter(|(_, direction)| direction.dot(onward) >= 1.0 - 1e-6);
1030    let first = tangent.next()?;
1031    tangent.next().is_none().then_some(first.0)
1032}
1033
1034fn walk_tangent_chains(
1035    solid: &BrepSolid,
1036    seeds: &[u64],
1037    selected: &[u64],
1038    follow: bool,
1039) -> Result<Vec<(u64, Vec3, String)>, String> {
1040    let tangent_at = |edge: &crate::topology::EdgeRecord, vertex: u64| -> Result<Vec3, String> {
1041        // The tangent pointing AWAY from `vertex`, into the edge.
1042        let at_start = edge.start_vertex_id == vertex;
1043        let t = if at_start { edge.t0 } else { edge.t1 };
1044        let tangent = edge.curve.unit_tangent(t, edge.t0, edge.t1)?;
1045        Ok(if at_start { tangent } else { tangent.scale(-1.0) })
1046    };
1047    let carriers = |edge_id: u64| -> Vec<&crate::NurbsSurface> {
1048        solid
1049            .shells
1050            .iter()
1051            .flat_map(|shell| &shell.faces)
1052            .filter(|face| face.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| coedge.edge_id == edge_id))
1053            .map(|face| &face.surface)
1054            .collect()
1055    };
1056    let changes_carrier = |from: u64, to: u64| -> bool {
1057        let own = carriers(from);
1058        !carriers(to)
1059            .iter()
1060            .all(|next| own.iter().any(|surface| crate::face_merge::same_surface(surface, next, 1e-9)))
1061    };
1062    // Only the chain's two edges meet `vertex` (a periodic face's seam, used
1063    // twice by its one face, does not count): a split of one curve.
1064    let seam = |edge_id: u64| -> bool {
1065        solid.shells.iter().flat_map(|shell| &shell.faces).any(|face| {
1066            face.loops.iter().flat_map(|lp| &lp.coedges).filter(|coedge| coedge.edge_id == edge_id).count() == 2
1067        })
1068    };
1069    let mere_split = |vertex: u64| -> bool {
1070        solid
1071            .edges
1072            .iter()
1073            .filter(|edge| !edge.degenerate && (edge.start_vertex_id == vertex || edge.end_vertex_id == vertex) && !seam(edge.id))
1074            .count()
1075            == 2
1076    };
1077    let mut taken: FxHashSet<u64> = selected.iter().chain(seeds).copied().collect();
1078    let mut added = Vec::new();
1079    for &seed in seeds {
1080        let Some(seed_edge) = solid.edges.iter().find(|edge| edge.id == seed) else { continue };
1081        if seed_edge.start_vertex_id == seed_edge.end_vertex_id || seed_edge.degenerate {
1082            continue;
1083        }
1084        for start in [seed_edge.start_vertex_id, seed_edge.end_vertex_id] {
1085            let mut current = seed_edge;
1086            let mut vertex = start;
1087            for _ in 0..if follow { solid.edges.len().max(128) } else { 128 } {
1088                // The chain's direction leaving `vertex` onward is minus the
1089                // current edge's tangent away from it.
1090                let onward = tangent_at(current, vertex)?.scale(-1.0);
1091                let mut candidates = Vec::new();
1092                for candidate in &solid.edges {
1093                    if candidate.id == current.id
1094                        || candidate.degenerate
1095                        || candidate.start_vertex_id == candidate.end_vertex_id
1096                        || (candidate.start_vertex_id != vertex && candidate.end_vertex_id != vertex)
1097                    {
1098                        continue;
1099                    }
1100                    candidates.push((candidate.id, tangent_at(candidate, vertex)?));
1101                }
1102                let Some(next_id) = single_tangent_continuation(&candidates, onward) else { break };
1103                let Some(next) = solid.edges.iter().find(|edge| edge.id == next_id) else { break };
1104                if !follow && current.id == seed && !changes_carrier(seed, next.id) && !mere_split(vertex) {
1105                    break;
1106                }
1107                if !taken.insert(next.id) {
1108                    break;
1109                }
1110                added.push((next.id, sample_edge_midpoint(solid, next.id)?, edge_name_or_id(solid, next.id)));
1111                vertex = if next.start_vertex_id == vertex { next.end_vertex_id } else { next.start_vertex_id };
1112                current = next;
1113            }
1114        }
1115    }
1116    Ok(added)
1117}
1118
1119/// Shared wall and corner prefix, `{featureID || 'F'}:BLEND`.
1120pub fn blend_face_base(id: &str) -> String {
1121    format!("{}:BLEND", if id.is_empty() { "F" } else { id })
1122}
1123
1124/// Per-edge face name; distinct wall names keep derived blend-edge names stable.
1125pub fn blend_face_name(id: &str, edge_name: &str) -> String {
1126    format!("{}:{}", blend_face_base(id), edge_name)
1127}
1128
1129/// Reject chamfer directions that depended on the removed mesh blend pipeline.
1130/// Fillet has no `direction` param: its blend side is always classified per edge.
1131pub fn require_blend_direction(ctx: &FeatureContext, operation: &str) -> Result<(), String> {
1132    let direction = ctx
1133        .param("direction")
1134        .and_then(|value| value.as_str())
1135        .map(|text| text.trim().to_uppercase())
1136        .filter(|text| !text.is_empty())
1137        .unwrap_or_else(|| "AUTO".to_string());
1138    if direction != "AUTO" && direction != "INSET" {
1139        return Err(format!(
1140            "{operation} direction '{direction}' belonged to the removed legacy mesh pipeline (only AUTO/INSET exist)"
1141        ));
1142    }
1143    Ok(())
1144}
1145
1146/// Read a finite parameter value, falling back for missing/null entries or
1147/// evaluation errors. Used by features whose optional fields are lenient.
1148pub(super) fn number_or_default(ctx: &FeatureContext, key: &str, default: f64) -> f64 {
1149    match ctx.param(key) {
1150        None | Some(serde_json::Value::Null) => default,
1151        Some(_) => match ctx.number(key) {
1152            Ok(value) if value.is_finite() => value,
1153            _ => default,
1154        },
1155    }
1156}
1157
1158/// An OPTIONAL numeric param: `None` when absent, else evaluated via
1159/// [`FeatureContext::number`] (a hard error on a broken expression, like the
1160/// primitive features). Used for the dressup gate/shape params (`inflate`,
1161/// `nudgeFaceDistance`, `radiusEnd`, `distance2`, `angle`).
1162pub fn optional_number(ctx: &FeatureContext, key: &str) -> Result<Option<f64>, String> {
1163    if ctx.param(key).is_some() {
1164        ctx.number(key).map(Some)
1165    } else {
1166        Ok(None)
1167    }
1168}
1169
1170// ===========================================================================
1171// The ONE feature-transform convention (XFORM, ACOMP, gizmo write-back)
1172// ===========================================================================
1173
1174/// Compose the row-major TRS matrix `[ RS | translate + pivot − RS·pivot ]`
1175/// with `R` the intrinsic `XYZ` Euler rotation (= `Rx·Ry·Rz`) and `S =
1176/// diag(scale)` — the SINGLE feature-transform compose. XFORM, the ACOMP
1177/// instance pose, and any solver/gizmo pose write-back must all speak this
1178/// convention; forking it would make the same stored angles place geometry
1179/// differently per consumer.
1180pub fn compose_trs_matrix(
1181    translate: [f64; 3],
1182    rotate_rad: [f64; 3],
1183    scale: [f64; 3],
1184    pivot: [f64; 3],
1185) -> [f64; 16] {
1186    let (a, b) = (rotate_rad[0].cos(), rotate_rad[0].sin());
1187    let (c, d) = (rotate_rad[1].cos(), rotate_rad[1].sin());
1188    let (e, f) = (rotate_rad[2].cos(), rotate_rad[2].sin());
1189    let (ae, af, be, bf) = (a * e, a * f, b * e, b * f);
1190    // Intrinsic 'XYZ' Euler rotation (row-major) = Rx·Ry·Rz.
1191    let r = [
1192        [c * e, -c * f, d],
1193        [af + be * d, ae - bf * d, -b * c],
1194        [bf - ae * d, be + af * d, a * c],
1195    ];
1196    // RS = R·diag(scale): scale each column (matches the standard TRS compose).
1197    let mut rs = [[0.0f64; 3]; 3];
1198    for i in 0..3 {
1199        for j in 0..3 {
1200            rs[i][j] = r[i][j] * scale[j];
1201        }
1202    }
1203    let rs_pivot = [
1204        rs[0][0] * pivot[0] + rs[0][1] * pivot[1] + rs[0][2] * pivot[2],
1205        rs[1][0] * pivot[0] + rs[1][1] * pivot[1] + rs[1][2] * pivot[2],
1206        rs[2][0] * pivot[0] + rs[2][1] * pivot[1] + rs[2][2] * pivot[2],
1207    ];
1208    let tx = translate[0] + pivot[0] - rs_pivot[0];
1209    let ty = translate[1] + pivot[1] - rs_pivot[1];
1210    let tz = translate[2] + pivot[2] - rs_pivot[2];
1211    [
1212        rs[0][0], rs[0][1], rs[0][2], tx, //
1213        rs[1][0], rs[1][1], rs[1][2], ty, //
1214        rs[2][0], rs[2][1], rs[2][2], tz, //
1215        0.0, 0.0, 0.0, 1.0,
1216    ]
1217}
1218
1219/// Read a vec3 VALUE (array `[x,y,z]` or object `{x,y,z}`); each component may
1220/// be a JSON number, an expression string (evaluated against the shared env),
1221/// or null/missing (→ default). `None`/`Null` as the whole value is the
1222/// default. Anything else is a loud error naming `key`. The shared reader for
1223/// TOP-LEVEL vec3 params (via [`FeatureContext::param`]) and NESTED ones (the
1224/// ACOMP `transform.translate` / `transform.rotateEulerDeg`).
1225pub fn vec3_from_value(
1226    env: &crate::feature_pipeline::Env,
1227    value: Option<&serde_json::Value>,
1228    key: &str,
1229    default: [f64; 3],
1230) -> Result<[f64; 3], String> {
1231    let Some(value) = value.filter(|value| !value.is_null()) else {
1232        return Ok(default);
1233    };
1234    let component = |slot: Option<&serde_json::Value>, fallback: f64| -> Result<f64, String> {
1235        match slot {
1236            None | Some(serde_json::Value::Null) => Ok(fallback),
1237            Some(serde_json::Value::Number(number)) => number
1238                .as_f64()
1239                .ok_or_else(|| format!("param `{key}` has a non-finite component")),
1240            Some(serde_json::Value::String(source)) => {
1241                let number = env
1242                    .eval(source)
1243                    .map_err(|error| format!("param `{key}`: {error}"))?;
1244                // An expression may evaluate to a NON-finite number (`1/0`) — that
1245                // must fail HERE, naming the slot, rather than travel on as a
1246                // point coordinate or reach `AffineTransform::new` as a nameless
1247                // "matrix must be finite".
1248                if !number.is_finite() {
1249                    return Err(format!(
1250                        "param `{key}`: `{source}` evaluated to {number}"
1251                    ));
1252                }
1253                Ok(number)
1254            }
1255            Some(other) => Err(format!(
1256                "param `{key}` component must be a number or expression, found {other}"
1257            )),
1258        }
1259    };
1260    if let Some(array) = value.as_array() {
1261        return Ok([
1262            component(array.first(), default[0])?,
1263            component(array.get(1), default[1])?,
1264            component(array.get(2), default[2])?,
1265        ]);
1266    }
1267    if value.is_object() {
1268        return Ok([
1269            component(value.get("x"), default[0])?,
1270            component(value.get("y"), default[1])?,
1271            component(value.get("z"), default[2])?,
1272        ]);
1273    }
1274    Err(format!("param `{key}` must be a vec3 array or object"))
1275}
1276
1277// ===========================================================================
1278// Reference-name + geometric-input resolution shared by profile-consumers
1279// ===========================================================================
1280
1281/// Resolve exact names in selection order, retaining duplicates and appending misses.
1282pub(super) fn resolve_solid_names(
1283    scene: &crate::feature_pipeline::SceneMap,
1284    names: &[String],
1285    unresolved: &mut Vec<String>,
1286) -> Vec<(String, u32)> {
1287    let mut resolved = Vec::new();
1288    for name in names {
1289        match scene.resolve_solid(name) {
1290            Some(handle) => resolved.push((name.clone(), handle)),
1291            None => unresolved.push(name.clone()),
1292        }
1293    }
1294    resolved
1295}
1296
1297/// Use an explicit sheet selection, or the sole sheet-metal body in the scene.
1298/// Missing or ambiguous implicit targets remain unselected.
1299pub(super) fn sheet_body_name(ctx: &FeatureContext) -> Option<String> {
1300    first_reference_name(ctx.param("sheet")).or_else(|| {
1301        let mut bodies = ctx.scene.solids.iter().filter_map(|(name, &handle)| {
1302            crate::feature_pipeline::sheet_metal::get_tree(handle).map(|_| name.clone())
1303        });
1304        match (bodies.next(), bodies.next()) {
1305            (Some(only), None) => Some(only),
1306            _ => None,
1307        }
1308    })
1309}
1310
1311/// Read a single selection without descending into nested arrays.
1312/// An empty first textual entry means no selection; later entries are ignored.
1313pub(super) fn single_reference_name(value: Option<&serde_json::Value>) -> Option<String> {
1314    let name = match value {
1315        Some(serde_json::Value::String(text)) => Some(text.clone()),
1316        Some(serde_json::Value::Array(array)) => array.iter().find_map(|entry| {
1317            entry
1318                .as_str()
1319                .or_else(|| entry.get("name").and_then(|name| name.as_str()))
1320                .map(str::to_string)
1321        }),
1322        Some(object @ serde_json::Value::Object(_)) => {
1323            object.get("name").and_then(|name| name.as_str()).map(str::to_string)
1324        }
1325        _ => None,
1326    }?;
1327    let trimmed = name.trim();
1328    (!trimmed.is_empty()).then(|| trimmed.to_string())
1329}
1330
1331/// The first reference name of a `reference_selection` param value (a plain
1332/// string, a `{name}` object, or an array of either — post-sanitization it is an
1333/// array). Exact match only; no `[N]` index / snapshot scoring.
1334pub fn first_reference_name(value: Option<&serde_json::Value>) -> Option<String> {
1335    fn one(value: &serde_json::Value) -> Option<String> {
1336        match value {
1337            serde_json::Value::Array(items) => items.iter().find_map(one),
1338            other => reference_name(other),
1339        }
1340    }
1341    value.and_then(one)
1342}
1343
1344/// Normalize a PROFILE reference name to the canonical sketch id by THE
1345/// sketch-name rule ([`crate::feature_pipeline::sketch_alias_base`]): a committed
1346/// sketch is picked as `{sketch}:FACE` (its render-side display sheet, which the
1347/// kernel run never materializes) or stored as `{sketch}:PROFILE`; both name the
1348/// profile stored under `{sketch}`, and every profile consumer's resolve +
1349/// cap-naming + sketch-consume then uses that id. Resident SOLID faces are
1350/// `{solid}|{face}[n]` and end in neither suffix, so real faces pass through.
1351pub fn normalize_profile_alias(name: String) -> String {
1352    match crate::feature_pipeline::sketch_alias_base(&name) {
1353        Some(base) => base.to_string(),
1354        None => name,
1355    }
1356}
1357
1358/// Names from an array-valued reference selection, preserving order and duplicates.
1359/// Missing and non-array values are ignored; entries use [`reference_name`].
1360pub(crate) fn reference_name_array(value: Option<&serde_json::Value>) -> Vec<String> {
1361    value
1362        .and_then(serde_json::Value::as_array)
1363        .map(|items| items.iter().filter_map(reference_name).collect())
1364        .unwrap_or_default()
1365}
1366
1367/// ALL reference names of a `reference_selection` param, in order (a `multiple`
1368/// selection). Also accepts a single string or `{name}` object; empties are dropped.
1369pub fn reference_names(value: Option<&serde_json::Value>) -> Vec<String> {
1370    match value {
1371        Some(serde_json::Value::Array(items)) => items.iter().filter_map(reference_name).collect(),
1372        Some(other) => reference_name(other).into_iter().collect(),
1373        None => Vec::new(),
1374    }
1375}
1376
1377/// Reference names with duplicates removed, retaining first-occurrence order.
1378pub(super) fn unique_reference_names(value: Option<&serde_json::Value>) -> Vec<String> {
1379    let mut seen = std::collections::HashSet::new();
1380    reference_names(value)
1381        .into_iter()
1382        .filter(|name| seen.insert(name.clone()))
1383        .collect()
1384}
1385
1386/// `consumeProfileSketch` (default true) — the profile-consumers remove the sketch
1387/// after building, echoing its name into `removed` for the caller's display cleanup.
1388pub fn consume_profile_sketch(ctx: &FeatureContext) -> bool {
1389    !matches!(
1390        ctx.param("consumeProfileSketch"),
1391        Some(serde_json::Value::Bool(false))
1392    )
1393}
1394
1395/// Echo the consumed sketch's base name (`{ref}` with any `:PROFILE` stripped) into
1396/// `result.removed` when `consumeProfileSketch` is set. Sketches register no scene
1397/// solid, so this only signals caller-side display cleanup.
1398pub fn consume_sketch(ctx: &FeatureContext, reference_name: &str, result: &mut FeatureResult) {
1399    if !consume_profile_sketch(ctx) {
1400        return;
1401    }
1402    consume_sketch_always(reference_name, result);
1403}
1404
1405/// Sheet-metal contract: a sketch that fed a generated piece of geometry is
1406/// ALWAYS consumed (removed from the scene) — there is no keep-the-sketch
1407/// switch. Non-sheet-metal profile consumers keep the `consumeProfileSketch`
1408/// gate via `consume_sketch` above.
1409pub fn consume_sketch_always(reference_name: &str, result: &mut FeatureResult) {
1410    let base = crate::feature_pipeline::canonical_sketch_name(reference_name).to_string();
1411    if !result.removed.contains(&base) {
1412        result.removed.push(base);
1413    }
1414}
1415
1416/// Map one profile loop's WORLD-space curves into the profile's own plane as
1417/// local `(u, v, 0)` curves: each control point `p` → `((p−origin)·x, (p−origin)·y, 0)`,
1418/// weights kept. A rigid in-plane change of frame, so rational curves (circles /
1419/// arcs) stay EXACT — the sheet-metal `Flat::holes` contract (hole loops in
1420/// flat-local coordinates at `z = 0`).
1421pub fn profile_loop_uv_curves(
1422    profile: &crate::feature_pipeline::SketchProfile,
1423    profile_loop: &crate::feature_pipeline::ProfileLoop,
1424) -> Result<Vec<NurbsCurve>, String> {
1425    let mut curves = Vec::with_capacity(profile_loop.curves.len());
1426    for curve in &profile_loop.curves {
1427        let mut control_points = Vec::with_capacity(curve.control_points.len());
1428        for cp in &curve.control_points {
1429            let delta = cp.point()?.sub(profile.origin);
1430            control_points.push(crate::Vec4::from_point(
1431                Vec3::new(delta.dot(profile.x_axis), delta.dot(profile.y_axis), 0.0),
1432                cp.w,
1433            ));
1434        }
1435        curves.push(NurbsCurve::new(
1436            curve.degree,
1437            curve.knots.clone(),
1438            control_points,
1439        )?);
1440    }
1441    Ok(curves)
1442}
1443
1444/// Resolve a sweep/rib PATH reference to its ordered world curve chain: a SKETCH
1445/// path (`scene.resolve_path`), a single resident solid EDGE (its curve TRIMMED
1446/// to the edge — [`edge_curve`]), or a sketch GEOMETRY name `{sketchId}:G{gid}`
1447/// → the owning sketch's published chain (the tube.rs convention —
1448/// per-geometry curves are not scene-indexed, and a chain holding more than the
1449/// named segment defers loudly downstream). A consumer wanting one path curve
1450/// uses the chain when it is length 1.
1451pub fn resolve_path(ctx: &FeatureContext, name: &str) -> Result<Vec<NurbsCurve>, String> {
1452    if let Some(chain) = ctx.scene.resolve_path(name) {
1453        return Ok(chain.clone());
1454    }
1455    if let Some(edge) = ctx.scene.resolve_edge(name) {
1456        return Ok(vec![edge_curve(edge)?]);
1457    }
1458    if let Some((owner, geometry)) = name.rsplit_once(':') {
1459        if geometry.len() > 1 && geometry.starts_with('G') {
1460            if let Some(chain) = ctx.scene.resolve_path(owner) {
1461                return Ok(chain.clone());
1462            }
1463        }
1464    }
1465    Err(format!(
1466        "path '{name}' not found (no sketch path or resident edge)"
1467    ))
1468}
1469
1470/// ONE segment of a resolved sweep path: the world curve, plus the SOURCE NAME
1471/// it came from (`{sketchId}:G{gid}` for a sketch geometry, the edge's own scene
1472/// name for a resident solid edge).
1473///
1474/// The name is the whole point: a feature that builds one PORTION per path
1475/// segment names that portion's faces after the segment, so adding, removing or
1476/// re-picking a path edge never renames a face built from a segment that did not
1477/// change. Naming by chain POSITION would renumber every downstream face the
1478/// moment a segment is inserted.
1479#[derive(Debug, Clone)]
1480pub struct PathSegment {
1481    pub name: String,
1482    pub curve: NurbsCurve,
1483    /// The segment's SCREW AXIS direction when its publisher knows it is a helix
1484    /// ([`SceneMap::resolve_path_segment_axes`]). Reversing the segment leaves it
1485    /// valid: a frame referenced to an axis does not depend on the axis' sign.
1486    pub axis: Option<Vec3>,
1487}
1488
1489/// Resolve a `path` `reference_selection` — one name or MANY — to a single
1490/// ordered, head-to-tail connected chain of NAMED segments.
1491///
1492/// Each reference contributes its curves through [`resolve_path`] (a whole
1493/// SKETCH's published chain, a single `{sketchId}:G{gid}` sketch segment, or a
1494/// resident solid EDGE), and each curve carries a name: the publisher's
1495/// per-segment names when it published them
1496/// ([`SceneMap::resolve_path_segment_names`]), else the reference name itself
1497/// (a one-curve reference) or `{reference}[i]` (an unnamed multi-curve chain).
1498/// A curve already contributed under the same name is dropped, so selecting a
1499/// sketch AND one of its own segments is not a duplicate.
1500///
1501/// The segments are then CHAINED by endpoint coincidence: the first reference
1502/// seeds the chain in its natural orientation, the chain grows from its tail and
1503/// then from its head (mirroring the sketch chainer), and a segment that has to
1504/// run backwards to join is reversed. So the picking ORDER does not matter —
1505/// the same set of edges always yields the same chain. Any segment that reaches
1506/// neither end is a disconnected or branching selection, and is reported BY NAME
1507/// rather than silently dropped.
1508/// Resolve a `path` `reference_selection` to the sweep's own PATH TYPE: the
1509/// ordered chain [`resolve_path_chain`] produces, CLASSIFIED once
1510/// ([`crate::SweepPath`]) — open or closed, the plane it lies in if it lies in
1511/// one, and the continuity of every joint including a closed path's closing one.
1512///
1513/// Every sweep refusal that used to answer one of those questions for itself now
1514/// reads this: the builder's corner gate, the closed-path lane, and `SW`'s own
1515/// `translate` fold-back rule, which could previously only report a closed path
1516/// as the consequence it happened to notice (a segment that must reverse).
1517/// Resolution, order and orientation are unchanged — this classifies the chain
1518/// the resolver produced, it does not re-resolve or re-order it.
1519pub fn resolve_sweep_path(
1520    ctx: &FeatureContext,
1521    names: &[String],
1522) -> Result<crate::SweepPath, String> {
1523    let segments = resolve_path_chain(ctx, names)?;
1524    let mut curves = Vec::with_capacity(segments.len());
1525    let mut segment_names = Vec::with_capacity(segments.len());
1526    let mut axes = Vec::with_capacity(segments.len());
1527    for segment in segments {
1528        curves.push(segment.curve);
1529        segment_names.push(segment.name);
1530        axes.push(segment.axis);
1531    }
1532    crate::SweepPath::new(curves, segment_names)?
1533        .with_screw_axes(axes)
1534        .map_err(String::from)
1535}
1536
1537pub fn resolve_path_chain(
1538    ctx: &FeatureContext,
1539    names: &[String],
1540) -> Result<Vec<PathSegment>, String> {
1541    let mut segments: Vec<PathSegment> = Vec::new();
1542    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1543    for reference in names {
1544        let curves = resolve_path(ctx, reference)?;
1545        let published = ctx.scene.resolve_path_segment_names(reference);
1546        let published_axes = ctx.scene.resolve_path_segment_axes(reference);
1547        let single = curves.len() == 1;
1548        for (index, curve) in curves.into_iter().enumerate() {
1549            let name = published
1550                .and_then(|names| names.get(index).cloned().flatten())
1551                .filter(|name| !name.trim().is_empty())
1552                .unwrap_or_else(|| {
1553                    if single {
1554                        reference.clone()
1555                    } else {
1556                        format!("{reference}[{index}]")
1557                    }
1558                });
1559            let axis = published_axes
1560                .and_then(|axes| axes.get(index).copied().flatten())
1561                .map(|axis| axis.direction);
1562            if seen.insert(name.clone()) {
1563                segments.push(PathSegment { name, curve, axis });
1564            }
1565        }
1566    }
1567    if segments.is_empty() {
1568        return Err("path selection resolved to no curves".into());
1569    }
1570    chain_path_segments(segments)
1571}
1572
1573/// Resolve a `reference_selection` of curves to the SEPARATE chains its picks
1574/// form: the picks are gathered as [`resolve_path_chain`] gathers them, grouped
1575/// by which ones touch end to end, and each group is ordered head to tail the
1576/// same way. The chains come in the order of their first pick. A selection that
1577/// forms one chain gives exactly [`resolve_path_chain`]'s result.
1578pub fn resolve_path_chains(
1579    ctx: &FeatureContext,
1580    names: &[String],
1581) -> Result<Vec<Vec<PathSegment>>, String> {
1582    let mut segments: Vec<PathSegment> = Vec::new();
1583    for reference in names {
1584        for segment in resolve_path_chain(ctx, std::slice::from_ref(reference))? {
1585            if !segments.iter().any(|seen| seen.name == segment.name) {
1586                segments.push(segment);
1587            }
1588        }
1589    }
1590    group_path_segments(segments)
1591}
1592
1593/// `segments` grouped into the separate chains they form by touching end to
1594/// end, each chain ordered head to tail ([`resolve_path_chains`]' grouping, for
1595/// a caller that gathers its segments itself). The chains come in the order of
1596/// their first segment.
1597pub(super) fn group_path_segments(segments: Vec<PathSegment>) -> Result<Vec<Vec<PathSegment>>, String> {
1598    if segments.is_empty() {
1599        return Ok(Vec::new());
1600    }
1601    let ends: Vec<(Vec3, Vec3)> = segments
1602        .iter()
1603        .map(|segment| path_endpoints(&segment.curve))
1604        .collect::<Result<_, _>>()?;
1605    let scale = ends
1606        .iter()
1607        .flat_map(|(a, b)| [a, b])
1608        .map(|point| point.sub(ends[0].0).length())
1609        .fold(1.0_f64, f64::max);
1610    let tolerance = 1e-5 * scale;
1611    let touch = |a: &(Vec3, Vec3), b: &(Vec3, Vec3)| {
1612        [a.0, a.1].iter().any(|p| [b.0, b.1].iter().any(|q| p.sub(*q).length() <= tolerance))
1613    };
1614    // group[i]: the chain segment i belongs to, named by its first segment
1615    let mut group: Vec<usize> = (0..segments.len()).collect();
1616    loop {
1617        let mut changed = false;
1618        for i in 0..segments.len() {
1619            for j in 0..i {
1620                if group[i] != group[j] && touch(&ends[i], &ends[j]) {
1621                    let (low, high) = (group[i].min(group[j]), group[i].max(group[j]));
1622                    group.iter_mut().filter(|g| **g == high).for_each(|g| *g = low);
1623                    changed = true;
1624                }
1625            }
1626        }
1627        if !changed {
1628            break;
1629        }
1630    }
1631    let mut chains = Vec::new();
1632    let mut taken: Vec<Option<PathSegment>> = segments.into_iter().map(Some).collect();
1633    for first in 0..taken.len() {
1634        if group[first] != first {
1635            continue;
1636        }
1637        let members: Vec<PathSegment> = (first..taken.len())
1638            .filter(|index| group[*index] == first)
1639            .collect::<Vec<_>>()
1640            .into_iter()
1641            .map(|index| taken[index].take().expect("each segment in one chain"))
1642            .collect();
1643        chains.push(chain_path_segments(members)?);
1644    }
1645    Ok(chains)
1646}
1647
1648/// A path curve's world endpoints (`(start, end)` at its domain ends).
1649fn path_endpoints(curve: &NurbsCurve) -> Result<(Vec3, Vec3), String> {
1650    let [t0, t1] = curve.domain()?;
1651    Ok((curve.evaluate(t0)?, curve.evaluate(t1)?))
1652}
1653
1654/// Order `segments` head-to-tail (see [`resolve_path_chain`]). Segments that join
1655/// nothing are reported by name.
1656fn chain_path_segments(segments: Vec<PathSegment>) -> Result<Vec<PathSegment>, String> {
1657    if segments.len() < 2 {
1658        return Ok(segments);
1659    }
1660    let ends: Vec<(Vec3, Vec3)> = segments
1661        .iter()
1662        .map(|segment| path_endpoints(&segment.curve))
1663        .collect::<Result<_, _>>()?;
1664    // Scale-relative join tolerance, on the same footing as the sketch chainer's
1665    // absolute 1e-5: individually picked solid edges meet only to within the
1666    // tolerance their own builders left behind.
1667    let scale = ends
1668        .iter()
1669        .flat_map(|(a, b)| [a, b])
1670        .map(|point| point.sub(ends[0].0).length())
1671        .fold(1.0_f64, f64::max);
1672    let tolerance = 1e-5 * scale;
1673    let joins = |a: Vec3, b: Vec3| a.sub(b).length() <= tolerance;
1674
1675    let mut used = vec![false; segments.len()];
1676    used[0] = true;
1677    // `(index, reversed)` in head-to-tail order, seeded on the FIRST picked
1678    // segment in its natural orientation.
1679    let mut order: Vec<(usize, bool)> = vec![(0, false)];
1680    let mut head = ends[0].0;
1681    let mut tail = ends[0].1;
1682    loop {
1683        // Closed chain: the tail returned to the head — stop before overshooting
1684        // into a segment attached at the seam (the sketch chainer's rule).
1685        if order.len() > 1 && joins(tail, head) {
1686            break;
1687        }
1688        if let Some((index, reversed, far)) = attach_path_segment(&ends, &used, tail, tolerance) {
1689            used[index] = true;
1690            order.push((index, reversed));
1691            tail = far;
1692            continue;
1693        }
1694        if let Some((index, reversed, far)) = attach_path_segment(&ends, &used, head, tolerance) {
1695            used[index] = true;
1696            // Walking head-ward: `attach_path_segment` orients tail-ward, so flip.
1697            order.insert(0, (index, !reversed));
1698            head = far;
1699            continue;
1700        }
1701        break;
1702    }
1703    let stranded: Vec<&str> = segments
1704        .iter()
1705        .zip(&used)
1706        .filter(|(_, used)| !**used)
1707        .map(|(segment, _)| segment.name.as_str())
1708        .collect();
1709    if !stranded.is_empty() {
1710        return Err(format!(
1711            "the selected path edges do not form ONE connected chain — {} joins neither \
1712             end of the chain the other selections form (a sweep path must be a single \
1713             head-to-tail run; select connected edges, or one branch at a time)",
1714            stranded.join(", ")
1715        ));
1716    }
1717    let mut chained = Vec::with_capacity(segments.len());
1718    let mut taken: Vec<Option<PathSegment>> = segments.into_iter().map(Some).collect();
1719    for (index, reversed) in order {
1720        let mut segment = taken[index].take().expect("each segment placed once");
1721        if reversed {
1722            segment.curve = segment.curve.reversed()?;
1723        }
1724        chained.push(segment);
1725    }
1726    Ok(chained)
1727}
1728
1729/// The first unused segment with an endpoint at `cursor`, oriented to walk AWAY
1730/// from it: `(index, reversed, far_end)`. Index-order scan, deterministic.
1731fn attach_path_segment(
1732    ends: &[(Vec3, Vec3)],
1733    used: &[bool],
1734    cursor: Vec3,
1735    tolerance: f64,
1736) -> Option<(usize, bool, Vec3)> {
1737    for (index, (start, end)) in ends.iter().enumerate() {
1738        if used[index] {
1739            continue;
1740        }
1741        if start.sub(cursor).length() <= tolerance {
1742            return Some((index, false, *end));
1743        }
1744        if end.sub(cursor).length() <= tolerance {
1745            return Some((index, true, *start));
1746        }
1747    }
1748    None
1749}
1750
1751/// Translate every curve of a profile loop by `offset` — the per-portion
1752/// placement a multi-segment sweep needs (each path segment sweeps a COPY of the
1753/// profile, moved to that segment's start).
1754pub fn translate_curves(curves: &[NurbsCurve], offset: Vec3) -> Result<Vec<NurbsCurve>, String> {
1755    curves
1756        .iter()
1757        .map(|curve| translate_curve(curve, offset))
1758        .collect()
1759}
1760
1761/// The SKETCH PLANE governing a path/profile reference, if it has one: the
1762/// reference name itself (a SKETCH publishes its resolved frame under its own id)
1763/// or the owner prefix of a sketch-geometry name (`{sketchId}:G{gid}`,
1764/// `{sketchId}:PROFILE`, `{sketchId}:FACE`). `None` for a non-sketch reference —
1765/// a resident solid EDGE publishes no frame.
1766///
1767/// This is the plane a sketch was AUTHORED on, and it is the answer to every
1768/// "which way is out of this chain?" question a consumer would otherwise re-derive
1769/// from the chain's own bends: the re-derivation is sign-ambiguous (it follows the
1770/// order the segments happen to be drawn in), and for a chain with no bend at all —
1771/// a single straight segment — it does not exist. Consumed by the sheet-metal
1772/// contour flange, and by the rib.
1773pub fn sketch_plane_frame(ctx: &FeatureContext, names: &[String]) -> Option<Frame> {
1774    for name in names {
1775        if let Some(frame) = ctx.scene.resolve_frame(name) {
1776            return Some(frame);
1777        }
1778        if let Some((owner, _)) = name.rsplit_once(':') {
1779            if let Some(frame) = ctx.scene.resolve_frame(owner) {
1780                return Some(frame);
1781            }
1782        }
1783    }
1784    None
1785}
1786
1787/// The base name a sketch-consuming feature should REMOVE for a reference: the
1788/// owning SKETCH for a sketch-geometry pick (`{sketchId}:G{gid}` whose owner
1789/// published a frame), else the raw reference name (`consume_sketch_always` applies
1790/// the sketch-name rule itself; non-sketch names are harmless display no-ops).
1791///
1792/// A viewport pick on a sketch's drawn SEGMENT stores `{sketchId}:G{gid}`, so
1793/// without this the consume would echo a name no display knows and the consumed
1794/// sketch would linger in the scene. Consumed by the sheet-metal contour flange,
1795/// and by the rib.
1796pub fn sketch_base_name(ctx: &FeatureContext, name: &str) -> String {
1797    if let Some((owner, tail)) = name.rsplit_once(':') {
1798        if tail.len() > 1 && tail.starts_with('G') && ctx.scene.resolve_frame(owner).is_some() {
1799            return owner.to_string();
1800        }
1801    }
1802    name.to_string()
1803}
1804pub use crate::trimmed_curve::trimmed_curve;
1805
1806
1807/// The world curve of one resident solid EDGE, TRIMMED to that edge's own
1808/// `[t0, t1]`.
1809///
1810/// An `EdgeRecord` carries a curve plus the subrange of it the edge actually
1811/// spans, and the two disagree constantly: every boolean and every dressup that
1812/// shortens an edge rewrites `t0`/`t1` and leaves the whole underlying curve in
1813/// place (a box edge whose end is eaten by a fillet keeps its full 20mm line and
1814/// records `t=[0, 0.8]`). A consumer that clones `record.curve` and reads its
1815/// DOMAIN therefore builds along a curve that runs past the edge the user picked
1816/// — a tube or a sweep that overshoots into thin air. Everything that turns a
1817/// picked edge into a path goes through here so that cannot happen once per
1818/// feature.
1819pub fn edge_curve(edge: EdgeRef) -> Result<NurbsCurve, String> {
1820    crate::with_registered_solid_str(edge.handle, |solid| {
1821        let record = solid
1822            .edges
1823            .iter()
1824            .find(|candidate| candidate.id == edge.edge_id)
1825            .ok_or_else(|| format!("edge {} not found on solid", edge.edge_id))?;
1826        trimmed_curve(&record.curve, record.t0, record.t1)
1827    })
1828}
1829
1830/// Resolve a revolve/sweep axis from a resident solid EDGE: the axis passes through
1831/// the edge's start and runs along its chord (start → end). A straight edge is
1832/// exact; a curved edge yields its chord (best-effort, matching the established edge-axis use).
1833pub fn edge_axis(edge: EdgeRef) -> Result<Axis, String> {
1834    crate::with_registered_solid_str(edge.handle, |solid| {
1835        let record = solid
1836            .edges
1837            .iter()
1838            .find(|candidate| candidate.id == edge.edge_id)
1839            .ok_or_else(|| format!("edge {} not found on solid", edge.edge_id))?;
1840        let start = record.curve.evaluate(record.t0)?;
1841        let end = record.curve.evaluate(record.t1)?;
1842        let direction = end.sub(start).normalized()?;
1843        Ok(Axis {
1844            point: start,
1845            direction,
1846        })
1847    })
1848}
1849
1850// ===========================================================================
1851// Hole-loop subtraction (multi-loop regions) shared by the profile-consumers
1852// ===========================================================================
1853//
1854// A [`SketchProfile`] region carries `region[0]` = outer boundary,
1855// `region[1..]` = its containment-classified holes. Every profile-consumer
1856// (extrude, sweep, revolve, path sweep, loft) builds each region's OUTER solid
1857// with its own sweep, cuts the region's holes with the SAME sweep via
1858// [`subtract_region_holes`], then unions the region solids
1859// ([`union_region_solids`]). The nesting FOREST machinery below stays general
1860// (a hole group may carry children), though the sketch classifier promotes an
1861// island inside a hole to its own region, so sketch-produced regions are flat.
1862
1863/// Rigid-translate a curve by `offset` (homogeneous-safe: rational weights kept).
1864pub fn translate_curve(curve: &NurbsCurve, offset: Vec3) -> Result<NurbsCurve, String> {
1865    let mut control_points = Vec::with_capacity(curve.control_points.len());
1866    for cp in &curve.control_points {
1867        let cartesian = cp.point()?;
1868        control_points.push(crate::Vec4::from_point(cartesian.add(offset), cp.w));
1869    }
1870    NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
1871}
1872
1873/// One inner loop of a region with its DIRECTLY nested loops: `region[index]`
1874/// cuts material at even-odd `depth` 0; each child is one level deeper.
1875pub struct HoleGroup {
1876    /// Index into the region's loops (>= 1).
1877    pub index: usize,
1878    /// Nesting depth below the outer loop (0 = a direct hole).
1879    pub depth: usize,
1880    pub children: Vec<HoleGroup>,
1881}
1882
1883/// Classify `region[1..]` into a containment FOREST. Loop `i` nests inside loop
1884/// `j` by the shared profile-containment predicate
1885/// ([`crate::feature_pipeline::loop_nesting`]: the exact curves sampled
1886/// adaptively in the profile's plane frame, a vote of interior points, points
1887/// on the other loop's boundary abstaining). Returns the depth-0 groups in loop
1888/// order.
1889pub fn hole_nesting(
1890    profile: &SketchProfile,
1891    region: &[crate::feature_pipeline::ProfileLoop],
1892) -> Result<Vec<HoleGroup>, String> {
1893    use crate::feature_pipeline::loop_nesting::{containment, sample_loops, PlaneFrame};
1894    let count = region.len().saturating_sub(1);
1895    if count == 0 {
1896        return Ok(Vec::new());
1897    }
1898    let curves: Vec<&[NurbsCurve]> = region[1..].iter().map(|l| l.curves.as_slice()).collect();
1899    let sampled = sample_loops(
1900        &curves,
1901        PlaneFrame {
1902            origin: profile.origin,
1903            x_axis: profile.x_axis,
1904            y_axis: profile.y_axis,
1905        },
1906    )?;
1907    // Pairwise containment + per-loop depth (# of loops containing it).
1908    let contains = containment(&sampled);
1909    let depths: Vec<usize> = (0..count)
1910        .map(|i| contains[i].iter().filter(|inside| **inside).count())
1911        .collect();
1912    Ok((0..count)
1913        .filter(|&i| depths[i] == 0)
1914        .map(|i| hole_group(i, &contains, &depths))
1915        .collect())
1916}
1917
1918/// Build the [`HoleGroup`] rooted at inner-loop `i`: its children are the loops
1919/// directly inside it (contained by it, exactly one level deeper).
1920fn hole_group(i: usize, contains: &[Vec<bool>], depths: &[usize]) -> HoleGroup {
1921    let children = (0..depths.len())
1922        .filter(|&k| contains[k][i] && depths[k] == depths[i] + 1)
1923        .map(|k| hole_group(k, contains, depths))
1924        .collect();
1925    HoleGroup {
1926        index: i + 1,
1927        depth: depths[i],
1928        children,
1929    }
1930}
1931
1932/// Stamp `{id}:HOLE:{key}` on every still-unnamed face of a hole cutter — the
1933/// extrude hole-cutter convention every profile-consumer shares (the boolean
1934/// propagates these names onto the cut walls). `key` is the hole loop's STABLE
1935/// identity ([`ProfileLoop::key`]), not its position, so adding or removing one
1936/// hole never renames another's walls. `segment` keys the name further for a
1937/// feature that cuts the SAME hole once per path segment (see [`hole_face_name`]).
1938pub fn name_hole_cutter_faces(cutter: &mut BrepSolid, id: &str, key: &str, segment: Option<&str>) {
1939    let name = hole_face_name(id, key, segment);
1940    for face in cutter
1941        .shells
1942        .iter_mut()
1943        .flat_map(|shell| shell.faces.iter_mut())
1944    {
1945        if face.name.is_none() {
1946            face.name = Some(name.clone());
1947        }
1948    }
1949}
1950
1951/// A hole wall's face name: `{id}:HOLE:{key}`, and `{id}:HOLE:{key}:{segment}`
1952/// when the feature cuts the same hole once PER PATH SEGMENT (the multi-segment
1953/// sweep). The un-keyed spelling is then the CONTAINER standing for all of them,
1954/// exactly as it is for the per-loop caps.
1955pub fn hole_face_name(id: &str, key: &str, segment: Option<&str>) -> String {
1956    match segment {
1957        Some(segment) => format!("{id}:HOLE:{key}:{segment}"),
1958        None => format!("{id}:HOLE:{key}"),
1959    }
1960}
1961
1962/// Boolean-subtract `cutter` from `body` with `merge_coplanar_faces` — the
1963/// hole-cut boolean (register both, subtract, free both).
1964pub fn subtract_solid(body: BrepSolid, cutter: BrepSolid) -> Result<BrepSolid, KernelRefusal> {
1965    let options = BooleanOptions {
1966        merge_coplanar_faces: true,
1967        ..BooleanOptions::default()
1968    };
1969    let body_handle = crate::register_solid_value(body);
1970    let cutter_handle = crate::register_solid_value(cutter);
1971    let cut = crate::with_two_registered_solids(body_handle, cutter_handle, |body, tool| {
1972        crate::boolean_operation(body, tool, BooleanOperation::Subtract, &options)
1973    });
1974    crate::free_registered_solid(body_handle);
1975    crate::free_registered_solid(cutter_handle);
1976    cut
1977}
1978
1979/// Boolean-intersect `tool` with `body` with `merge_coplanar_faces` — the
1980/// [`subtract_solid`] twin (register both, intersect, free both).
1981pub fn intersect_solid(body: BrepSolid, tool: BrepSolid) -> Result<BrepSolid, KernelRefusal> {
1982    let options = BooleanOptions {
1983        merge_coplanar_faces: true,
1984        ..BooleanOptions::default()
1985    };
1986    let body_handle = crate::register_solid_value(body);
1987    let tool_handle = crate::register_solid_value(tool);
1988    let common = crate::with_two_registered_solids(body_handle, tool_handle, |body, tool| {
1989        crate::boolean_operation(body, tool, BooleanOperation::Intersect, &options)
1990    });
1991    crate::free_registered_solid(body_handle);
1992    crate::free_registered_solid(tool_handle);
1993    common
1994}
1995
1996/// The straight-sweep hole cutter: the hole loop extruded into a prism that
1997/// clears BOTH caps (offset `margin` before the start plane, `2*margin`
1998/// over-long — the sheet-metal cutout pattern). `depth` scales the margin so a
1999/// nested island's prism strictly overhangs its parent hole's prism caps (no
2000/// coincident cutter-on-cutter cap faces); depth 0 is extrude's exact margin.
2001pub fn hole_prism(
2002    hole_curves: &[NurbsCurve],
2003    direction: Vec3,
2004    distance: f64,
2005    depth: usize,
2006) -> Result<BrepSolid, KernelRefusal> {
2007    let dir = direction.normalized().or_input(KernelStage::Collect, "direction")?;
2008    let span = distance.abs();
2009    let margin = span.max(1.0) * (depth as f64 + 1.0);
2010    let start_t = distance.min(0.0) - margin;
2011    let length = span + 2.0 * margin;
2012    let offset = dir.scale(start_t);
2013    let mut curves = Vec::with_capacity(hole_curves.len());
2014    for curve in hole_curves {
2015        curves.push(translate_curve(curve, offset).or_refuse(KernelStage::Collect, "translate_curve")?);
2016    }
2017    crate::extrude_profile_brep(&curves, dir, length)
2018}
2019
2020/// Subtract one hole loop from `body` as a through prism — extrude's
2021/// `subtract_hole`, verbatim (build the over-long prism, stamp
2022/// `{id}:HOLE:{index}` on its faces, boolean-subtract with coplanar merge). A
2023/// degenerate (< 2 curve) hole loop is nothing to cut.
2024pub fn subtract_hole_prism(
2025    feature: &str,
2026    body: BrepSolid,
2027    hole_curves: &[NurbsCurve],
2028    direction: Vec3,
2029    distance: f64,
2030    id: &str,
2031    key: &str,
2032) -> Result<BrepSolid, String> {
2033    if hole_curves.len() < 2 {
2034        return Ok(body);
2035    }
2036    let mut cutter = hole_prism(hole_curves, direction, distance, 0)?;
2037    name_hole_cutter_faces(&mut cutter, id, key, None);
2038    subtract_solid(body, cutter)
2039        .map_err(|error| format!("{feature}: hole {key} cut failed: {error}"))
2040}
2041
2042/// Subtract every inner loop of `region` from `body`, nesting-aware: each
2043/// depth-0 hole becomes ONE cutter — its own swept solid minus its children's
2044/// sub-cutters (recursively). `build` sweeps `region[loop_index]` with the
2045/// FEATURE's own sweep (prism / revolve / path / loft); it receives the loop's
2046/// nesting depth for margin scaling. Cutter faces are stamped `{id}:HOLE:{key}`
2047/// with the hole loop's OWN stable identity ([`ProfileLoop::key`]), so the name
2048/// survives another hole being added or removed — the hole-wall sibling of the
2049/// per-loop cap naming (the old stamp counted holes positionally across regions,
2050/// so deleting one renumbered the rest). `segment`, when the feature cuts this
2051/// region once PER PATH SEGMENT (the multi-segment sweep), keys each cut's walls
2052/// by the segment that made them — otherwise adjacent portions' channel walls
2053/// would collide on one name and fall back to a positional `[n]`.
2054pub fn subtract_region_holes(
2055    mut body: BrepSolid,
2056    profile: &SketchProfile,
2057    region: &[crate::feature_pipeline::ProfileLoop],
2058    feature: &str,
2059    id: &str,
2060    segment: Option<&str>,
2061    build: &mut dyn FnMut(usize, usize) -> Result<BrepSolid, KernelRefusal>,
2062) -> Result<BrepSolid, FeatureRefusal> {
2063    for group in hole_nesting(profile, region)? {
2064        let key = hole_key(&region[group.index], group.index);
2065        // The cutter's and the cut's refusals keep their class through the
2066        // feature's wrap.
2067        let Some(cutter) = hole_cutter(region, &group, id, segment, build).map_err(|error| {
2068            error.with_message(|error| format!("{feature}: hole {key} cut failed: {error}"))
2069        })?
2070        else {
2071            continue;
2072        };
2073        body = subtract_solid(body, cutter).map_err(|error| {
2074            error.with_message(|error| format!("{feature}: hole {key} cut failed: {error}"))
2075        })?;
2076    }
2077    Ok(body)
2078}
2079
2080/// A hole loop's naming key: its own stable loop identity, else its POSITION —
2081/// the pre-existing spelling, kept for a profile whose loops have no identity to
2082/// key on (a FACE profile, a hand-built profile), so their names never move.
2083pub fn hole_key(hole: &crate::feature_pipeline::ProfileLoop, index: usize) -> String {
2084    hole.key().unwrap_or_else(|| index.to_string())
2085}
2086
2087/// Build one hole group's CUTTER: the loop's swept solid minus each child's
2088/// cutter. `None` for a degenerate (< 2 curve) loop — nothing to cut.
2089fn hole_cutter(
2090    region: &[crate::feature_pipeline::ProfileLoop],
2091    group: &HoleGroup,
2092    id: &str,
2093    segment: Option<&str>,
2094    build: &mut dyn FnMut(usize, usize) -> Result<BrepSolid, KernelRefusal>,
2095) -> Result<Option<BrepSolid>, KernelRefusal> {
2096    if region[group.index].curves.len() < 2 {
2097        return Ok(None);
2098    }
2099    let mut cutter = build(group.index, group.depth)?;
2100    name_hole_cutter_faces(
2101        &mut cutter,
2102        id,
2103        &hole_key(&region[group.index], group.index),
2104        segment,
2105    );
2106    for child in &group.children {
2107        let Some(child_cutter) = hole_cutter(region, child, id, segment, build)? else {
2108            continue;
2109        };
2110        cutter = subtract_solid(cutter, child_cutter).map_err(|error| {
2111            error.with_message(|error| {
2112                format!("island {} carve from hole {} failed: {error}", child.index, group.index)
2113            })
2114        })?;
2115    }
2116    Ok(Some(cutter))
2117}
2118
2119// ===========================================================================
2120// Face frame — a sketch/plane FRAME from a resident BREP face (planar-only)
2121// ===========================================================================
2122
2123/// A resolved "plane-like" reference — a solid FACE or a datum/construction PLANE
2124/// frame. THE shared resolution for a `["FACE","PLANE"]` reference: a datum plane
2125/// (from a `D`/`P` feature — both emit a scene [`Frame`]) and a planar face are
2126/// the same underlying object here, so every consumer (mirror, split, pattern,
2127/// plane) treats them identically instead of hand-rolling the two-table lookup.
2128/// That duplication was the source of the "picking a datum plane does nothing"
2129/// bug class — a new consumer just calls [`resolve_plane_reference`].
2130pub enum PlaneLikeRef {
2131    /// A solid face — its `(handle, face_id)`.
2132    Face(FaceRef),
2133    /// A datum / construction plane — its scene frame.
2134    Frame(Frame),
2135}
2136
2137impl PlaneLikeRef {
2138    /// The reference's plane as `(point, unit outward normal)`. A datum PLANE is
2139    /// its frame's `(origin, z-axis)`; a FACE is its midpoint tangent plane
2140    /// ([`face_point_normal`], valid for any face — a curved face yields the
2141    /// midpoint tangent, matching the pre-refactor mirror/split behaviour).
2142    pub fn point_normal(&self) -> Result<(Vec3, Vec3), String> {
2143        match self {
2144            PlaneLikeRef::Frame(frame) => Ok((frame.origin, frame.z_axis)),
2145            PlaneLikeRef::Face(face) => face_point_normal(*face),
2146        }
2147    }
2148
2149    /// The reference's full plane BASIS (origin + in-plane axes + normal). A datum
2150    /// PLANE is its frame directly; a FACE is [`face_frame`] (planar faces only).
2151    pub fn frame(&self) -> Result<Frame, String> {
2152        match self {
2153            PlaneLikeRef::Frame(frame) => Ok(*frame),
2154            PlaneLikeRef::Face(face) => face_frame(*face),
2155        }
2156    }
2157}
2158
2159/// Resolve a `["FACE","PLANE"]` reference name against the live scene-map: a solid
2160/// FACE first, else a datum / construction PLANE frame. The two name tables are
2161/// disjoint, so the order is irrelevant. `None` = unresolved (the caller records
2162/// it as an `unresolved` entry, contract rule 1 — never a no-op-with-no-signal).
2163pub fn resolve_plane_reference(ctx: &FeatureContext, name: &str) -> Option<PlaneLikeRef> {
2164    if let Some(face) = ctx.scene.resolve_face(name) {
2165        return Some(PlaneLikeRef::Face(face));
2166    }
2167    ctx.scene.resolve_frame(name).map(PlaneLikeRef::Frame)
2168}
2169
2170/// A face's plane as `(point on it, unit outward normal)`: the surface value +
2171/// normal at its parameter-domain midpoint, oriented by `same_sense`. Works on
2172/// ANY face (a curved face yields its midpoint tangent plane). The shared version
2173/// of the `plane_from_face` helper mirror/split/pattern each carried privately.
2174pub fn face_point_normal(face: FaceRef) -> Result<(Vec3, Vec3), String> {
2175    crate::with_registered_solid_str(face.handle, |solid| {
2176        for shell in &solid.shells {
2177            for record in &shell.faces {
2178                if record.id != face.face_id {
2179                    continue;
2180                }
2181                let [u0, u1] = record.surface.domain_u()?;
2182                let [v0, v1] = record.surface.domain_v()?;
2183                let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
2184                let point = record.surface.evaluate(um, vm)?;
2185                let mut normal = record.surface.normal(um, vm)?;
2186                if !record.same_sense {
2187                    normal = normal.scale(-1.0);
2188                }
2189                return Ok((point, normal));
2190            }
2191        }
2192        Err(format!("face {} not found on solid", face.face_id))
2193    })
2194}
2195
2196/// The world-space BOUNDARY SAMPLES of a face: five points along each
2197/// non-degenerate edge of each of its loops. This is the face EXTENT as this
2198/// kernel measures it — [`face_frame`]'s origin is the AABB centre of exactly
2199/// these points, and the assembly inference lane
2200/// ([`crate::feature_pipeline::assembly::infer`]) decides whether two faces
2201/// overlap by projecting them. Empty when every boundary edge is degenerate.
2202pub fn face_boundary_points(
2203    solid: &BrepSolid,
2204    record: &crate::FaceRecord,
2205) -> Result<Vec<Vec3>, String> {
2206    let mut points = Vec::new();
2207    for loop_record in &record.loops {
2208        for coedge in &loop_record.coedges {
2209            let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else {
2210                continue;
2211            };
2212            if edge.degenerate {
2213                continue;
2214            }
2215            for step in 0..=4 {
2216                let t = edge.t0 + (edge.t1 - edge.t0) * (step as f64 / 4.0);
2217                points.push(edge.curve.evaluate(t)?);
2218            }
2219        }
2220    }
2221    Ok(points)
2222}
2223
2224/// The AABB of a point cloud (`None` when empty).
2225pub fn bounds_of(points: &[Vec3]) -> Option<(Vec3, Vec3)> {
2226    let mut iter = points.iter();
2227    let first = *iter.next()?;
2228    let (mut min, mut max) = (first, first);
2229    for point in iter {
2230        min = Vec3::new(min.x.min(point.x), min.y.min(point.y), min.z.min(point.z));
2231        max = Vec3::new(max.x.max(point.x), max.y.max(point.y), max.z.max(point.z));
2232    }
2233    Some((min, max))
2234}
2235
2236/// Compute a placement [`Frame`] from a resident face, for headless sketch/plane
2237/// resolution against a solid's face. Uses the face-basis convention:
2238/// the normal is the OUTWARD face normal (sense
2239/// respected); in-plane axes come from [`Frame::from_origin_normal`]; the origin is
2240/// the face boundary AABB center projected onto the plane. **Planar faces only** —
2241/// a curved face is not yet migrated (loud error, no-fallback).
2242pub fn face_frame(face: FaceRef) -> Result<Frame, String> {
2243    crate::with_registered_solid_str(face.handle, |solid| {
2244        let record = solid
2245            .shells
2246            .iter()
2247            .flat_map(|shell| &shell.faces)
2248            .find(|candidate| candidate.id == face.face_id)
2249            .ok_or_else(|| format!("face {} not found on solid", face.face_id))?;
2250
2251        let [u0, u1] = record.surface.domain_u()?;
2252        let [v0, v1] = record.surface.domain_v()?;
2253        let (um, vm) = ((u0 + u1) * 0.5, (v0 + v1) * 0.5);
2254
2255        // Planarity: the normal must be constant across the patch.
2256        let center_normal = record.surface.normal(um, vm)?;
2257        for (u, v) in [(u0, v0), (u1, v0), (u1, v1), (u0, v1)] {
2258            let normal = record.surface.normal(u, v)?;
2259            if normal.dot(center_normal).abs() < 1.0 - 1e-6 {
2260                return Err(
2261                    "sketch/plane on a non-planar face is not yet migrated to the Rust pipeline"
2262                        .into(),
2263                );
2264            }
2265        }
2266        // Outward face normal (respect the face sense, like `getAverageNormal`).
2267        let normal = if record.same_sense {
2268            center_normal
2269        } else {
2270            center_normal.scale(-1.0)
2271        };
2272
2273        // Boundary AABB center from the face loops' non-degenerate edges.
2274        let boundary = face_boundary_points(solid, record)?;
2275        let plane_point = record.surface.evaluate(um, vm)?;
2276        let center = match bounds_of(&boundary) {
2277            Some((min, max)) => min.add(max).scale(0.5),
2278            None => plane_point,
2279        };
2280        // Project the AABB center onto the plane so the origin lies exactly on it.
2281        let unit = normal.normalized()?;
2282        let signed = center.sub(plane_point).dot(unit);
2283        let origin = center.sub(unit.scale(signed));
2284        Frame::from_origin_normal(origin, normal)
2285    })
2286}
2287
2288// ===========================================================================
2289// Multi-region profiles — union the per-region solids into ONE result
2290// ===========================================================================
2291
2292/// UNION the per-region solids of a multi-region profile into ONE solid — the
2293/// established multi-region behavior (one solid per region, boolean-unioned). Folds with
2294/// `merge_coplanar_faces` (handle-registered operands, freed after each fold);
2295/// a single region passes through untouched, so single-region consumers are
2296/// byte-identical to the pre-region pipeline.
2297pub fn union_region_solids(solids: Vec<BrepSolid>) -> Result<BrepSolid, String> {
2298    union_solids_keeping(solids, &[])
2299}
2300
2301/// [`union_region_solids`] that PINS the named faces out of the coplanar merge:
2302/// a face whose name contains one of `keep_unmerged` is never coalesced with a
2303/// mergeable neighbour.
2304///
2305/// The multi-segment sweep needs it. Two portions built from CONSECUTIVE path
2306/// segments meet at a shared cap, and their sidewalls are frequently coplanar
2307/// (always so for two collinear segments, and for the walls parallel to the plane
2308/// a turn happens in). Merging those fuses two portions' walls into one face
2309/// carrying ONE of the two names — so which of the two source segments a
2310/// downstream fillet still resolves to would depend on the boolean's internal
2311/// face order, and would move whenever the path is edited. Pinning keeps one wall
2312/// face per (path segment × profile edge), each named after both — the same call
2313/// sheet metal makes to keep a flange attachable to a specific outline segment.
2314pub fn union_solids_keeping(
2315    solids: Vec<BrepSolid>,
2316    keep_unmerged: &[String],
2317) -> Result<BrepSolid, String> {
2318    let mut iter = solids.into_iter();
2319    let mut current = iter
2320        .next()
2321        .ok_or("profile produced no region solids to union")?;
2322    let options = BooleanOptions {
2323        merge_coplanar_faces: true,
2324        keep_unmerged_name_substrs: keep_unmerged.to_vec(),
2325        ..BooleanOptions::default()
2326    };
2327    for next in iter {
2328        let a = crate::register_solid_value(current);
2329        let b = crate::register_solid_value(next);
2330        let unioned = crate::with_two_registered_solids(a, b, |left, right| {
2331            crate::boolean_operation(left, right, BooleanOperation::Union, &options)
2332        });
2333        crate::free_registered_solid(a);
2334        crate::free_registered_solid(b);
2335        current = unioned.map_err(|error| format!("region union failed: {error}"))?;
2336    }
2337    Ok(current)
2338}
2339
2340
2341/// Transform controls shared by primitive solid schemas.
2342pub(super) fn primitive_transform_schema() -> serde_json::Value {
2343    serde_json::json!({
2344        "type": "transform",
2345        "default_value": {
2346            "position": [
2347                0,
2348                0,
2349                0
2350            ],
2351            "rotationEuler": [
2352                0,
2353                0,
2354                0
2355            ],
2356            "scale": [
2357                1,
2358                1,
2359                1
2360            ]
2361        },
2362        "referenceSelectionFilter": [
2363            "FACE",
2364            "EDGE",
2365            "VERTEX",
2366            "PLANE",
2367            "DATUM"
2368        ],
2369        "referenceLabel": "Start Reference",
2370        "referencePlaceholder": "Select point, edge, or face…",
2371        "hint": "Select a start reference, then position, rotate, and scale the solid relative to it."
2372    })
2373}
2374
2375/// Optional Boolean controls shared by solid-producing feature schemas.
2376pub(super) fn optional_boolean_schema() -> serde_json::Value {
2377    serde_json::json!({
2378        "type": "boolean_operation",
2379        "default_value": {
2380            "targets": [],
2381            "operation": "NONE",
2382            "mergeCoplanarFaces": true
2383        },
2384        "hint": "Optional boolean operation with selected solids"
2385    })
2386}
2387
2388
2389
2390