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