Skip to main content

brep_kernel/feature_pipeline/features/
import3d.rs

1//! IMPORT3D — Import 3D Model (STEP). Ported from the retired `Import3dModelFeature`.
2//!
3//! Three headless sources, tried in order:
4//! 0. **`inputParams.nativeBrep`** — a native [`crate::snapshot_solids`] payload
5//!    (`io/snapshot.rs`): the exact solids of an earlier import, already carrying their
6//!    final IMPORT3D names. Tried FIRST and EXCLUSIVE — a feature carrying it must not
7//!    also carry `stepText`/`igesText`/`xtText` (an error, not a precedence puzzle).
8//!    The solids register VERBATIM under their stored names: re-deriving them would
9//!    break every scene-metadata record and every constraint keyed to a face name. This
10//!    is the lane a STEP-assembly part document rides on, and the reason the snapshot
11//!    container is a DURABLE format, not a cache (§6 there, and the `io/snapshot.rs`
12//!    module doc).
13//! 1. **`inputParams.stepText`** — the raw ISO-10303-21 document, baked in by the
14//!    toolbar Import lane ([`crate`]'s host: `EngineState::import_step_feature`).
15//!    Runs the exact Rust STEP importer
16//!    ([`crate::import_step_with_appearance`] — the colour-carrying form).
17//! 2. **`persistentData.importCache`** (`kind == "step-brep"`) — SUPERSEDED by
18//!    `nativeBrep`. The JS-era persisted EXACT BREP records of a previous import
19//!    (`serializeBrepSolid` was the serde `BrepSolid` JSON, so records deserialize
20//!    directly) — verbose and unversioned. NOTHING in the Rust tree writes it; the
21//!    reader stays only so a JS-era saved model still opens. New payloads go in
22//!    `nativeBrep`.
23//!
24//! Name fidelity (contract rule 2, byte-matching `Import3dModelFeature`):
25//! - Body names (`importedSolidNames`): a single body keeps the feature name;
26//!   several get `{feature}_SOLID_{N}` with N 1-based, zero-padded to
27//!   `max(2, digits(count))`.
28//! - Faces (`importedBodyFaceNames` / the single-body fallback): a MULTI-body
29//!   import names EVERY face `{bodyName}_Face_{f}` positionally (shell/face
30//!   order) so faces stay unique across bodies; a SINGLE body prepends the
31//!   (unique) feature name — `{feature}_{stepName}`, or `{feature}_Face_{f}` where
32//!   the STEP file left the face unnamed — so two separate imports never share a
33//!   face name (the cross-solid name-uniqueness guard's collision class). Edge
34//!   names re-derive from the face names, so the derived edges are namespaced too.
35//!
36//! COLOUR rides the same names. What a STEP file's presentation entities assign
37//! (`io/step_import/styles.rs`) is stamped here as a `{"color": "#RRGGBB"}`
38//! scene-metadata record on the FINAL body/face names — see `io/appearance.rs`
39//! for the convention, [`stamp_appearance`] for the write, and
40//! [`native_import_payload_with_appearance`] for the lane that seals it into a
41//! part payload. The stamp is a NON-overwriting merge, so a colour edited in the
42//! caller's info panel survives a history replay.
43//!
44//! ONE convention, ONE implementation: [`stamp_imported_names`] holds it, and
45//! every lane that names imported bodies goes through it — the live import lanes
46//! (via [`add_named_bodies`]) and the payload encoder [`native_import_payload`].
47//! Names are stamped ONCE, at import, and then frozen in the payload; a later
48//! change here does NOT retro-rename already-imported parts, which is the point
49//! (a constraint keyed to a face name survives reload).
50//!
51//! The failed-import base64 retry lane (`persistentData.failedImportFile`) is
52//! not yet migrated — it errors loudly rather than silently skipping.
53
54use crate::feature_pipeline::features::common;
55use crate::feature_pipeline::{
56    scene_metadata, AddedSolid, FeatureContext, FeatureRefusal, FeatureResult,
57};
58use crate::{
59    import_iges_report, import_step_bodies, restore_solids, BodyAppearance, BrepSolid, ImportedColor,
60    StepBodyError, COLOR_METADATA_KEY,
61};
62
63pub fn execute(ctx: &FeatureContext) -> FeatureResult {
64    match build(ctx) {
65        Ok(result) => result,
66        Err(refusal) => ctx.fail(refusal),
67    }
68}
69
70/// `FeatureRefusal`, not `String`: the STEP lane's shell-closure gate refuses a
71/// body TYPED (`RefusalClass::UnsoundResult { defect: VectorArea }`,
72/// `io/step_import/builder/closure.rs`), and the class has to reach
73/// `FeatureResult::refusal` for the app to show it as more than text. Every
74/// other failure here is still text, and `?` accepts both.
75fn build(ctx: &FeatureContext) -> Result<FeatureResult, FeatureRefusal> {
76    let feature_name = if ctx.id.is_empty() {
77        "IMPORT3D".to_string()
78    } else {
79        ctx.id.clone()
80    };
81
82    // 0. Native payload — the exact solids of an earlier import, names frozen in.
83    //    EXCLUSIVE by design (see the module doc): a document carrying both this
84    //    and a text source is malformed, and answering it with a precedence rule
85    //    would silently drop one of the two. Keyed on PRESENCE, not on a
86    //    successful `as_str`, so a non-string `nativeBrep` errors here instead of
87    //    falling through to a different source.
88    if let Some(native) = ctx.param("nativeBrep").filter(|value| !value.is_null()) {
89        if ctx.param("stepText").is_some() || ctx.param("igesText").is_some() || ctx.param("xtText").is_some() {
90            return Err(
91                "import3d: `nativeBrep` is exclusive — a feature carrying it must not also carry `stepText`/`igesText`/`xtText`"
92                    .into(),
93            );
94        }
95        let payload = native
96            .as_str()
97            .ok_or("import3d: param `nativeBrep` must be a base64 snapshot string")?;
98        return Ok(restore_native_bodies(ctx, payload)?);
99    }
100
101    // 1. Fresh STEP text (baked into `stepText` by the toolbar Import lane).
102    if let Some(step_text) = ctx.param("stepText").and_then(|v| v.as_str()) {
103        if step_text.contains("ISO-10303-21") {
104            let imported = import_step_bodies(step_text).map_err(|error| match error {
105                StepBodyError::Text(text) => {
106                    FeatureRefusal::Text(format!("import3d: STEP import failed: {text}"))
107                }
108                StepBodyError::Refused(refusal) => FeatureRefusal::Typed(
109                    refusal.with_message(|message| format!("import3d: STEP import refused: {message}")),
110                ),
111            })?;
112            if imported.solids.is_empty() {
113                return Err("import3d: STEP file contained no importable solids".into());
114            }
115            let mut result = add_named_bodies(ctx, imported.solids, &imported.appearances, &feature_name);
116            // The closure gate's approximations ride on the feature TYPED,
117            // re-keyed from the file index to the scene name the body was
118            // just given, so the app and the case runner can name the body.
119            for (index, mut approximation) in imported.approximations {
120                if let Some(added) = result.added.get(index) {
121                    approximation.body = added.name.clone();
122                    approximation.message =
123                        format!("{}: {}", added.name, approximation.message);
124                }
125                result.approximations.push(approximation);
126            }
127            return Ok(result);
128        }
129        return Err(
130            "import3d: only STEP (ISO-10303-21) files are supported (STL/3MF mesh import was removed)"
131                .into(),
132        );
133    }
134
135    // 1b. Fresh IGES text (baked into `igesText` by the toolbar Import lane).
136    if let Some(iges_text) = ctx.param("igesText").and_then(|v| v.as_str()) {
137        // The file's colours (314 or the directory colour number) are stamped
138        // as the STEP branch stamps its styled colours.
139        let report = import_iges_report(iges_text)
140            .map_err(|error| format!("import3d: IGES import failed: {error}"))?;
141        if report.solids.is_empty() {
142            return Err("import3d: IGES file contained no importable solids".into());
143        }
144        return Ok(add_named_bodies(ctx, report.solids, &report.appearances, &feature_name));
145    }
146
147    // 1c. Fresh Parasolid text (baked into `xtText` by the toolbar Import lane).
148    if let Some(xt_text) = ctx.param("xtText").and_then(|v| v.as_str()) {
149        let report = crate::parasolid::import_parasolid_report(xt_text)
150            .map_err(|error| format!("import3d: Parasolid import failed: {error}"))?;
151        if report.solids.is_empty() {
152            return Err("import3d: Parasolid file contained no importable solids".into());
153        }
154        return Ok(add_named_bodies(ctx, report.solids, &report.appearances, &feature_name));
155    }
156
157    // 2. Persisted exact-BREP records from a previous import.
158    let cache = ctx.persistent.get("importCache");
159    if let Some(cache) = cache {
160        let kind = cache.get("kind").and_then(|v| v.as_str()).unwrap_or("");
161        if kind == "step-brep" {
162            let records = cache
163                .get("kernelSolidRecords")
164                .and_then(|v| v.as_array())
165                .ok_or("import3d: importCache has no kernelSolidRecords")?;
166            let mut solids = Vec::with_capacity(records.len());
167            for (index, record) in records.iter().enumerate() {
168                let solid: BrepSolid = serde_json::from_value(record.clone()).map_err(|error| {
169                    format!("import3d: kernel record {index} failed to deserialize: {error}")
170                })?;
171                solids.push(solid);
172            }
173            if solids.is_empty() {
174                return Err("import3d: importCache is empty".into());
175            }
176            return Ok(add_named_bodies(ctx, solids, &[], &feature_name));
177        }
178        return Err(format!(
179            "import3d: unsupported importCache kind '{kind}' (only 'step-brep')"
180        )
181        .into());
182    }
183
184    // A failed-import retry payload without a cache is a not-yet-migrated lane.
185    if ctx.persistent.get("failedImportFile").is_some() {
186        return Err(
187            "import3d: the failed-import base64 retry lane is not yet migrated to the Rust pipeline"
188                .into(),
189        );
190    }
191
192    Err(
193        "import3d: no model data (no `nativeBrep`/`stepText` param and no `importCache`)".into(),
194    )
195}
196
197/// Restore a native payload and register its solids VERBATIM — the `nativeBrep`
198/// lane. Nothing about the names is re-derived: they were stamped once, when the
199/// geometry was first imported, and every scene-metadata record and every
200/// constraint attached to a face is keyed to exactly those strings. (This is
201/// `component::create_component`'s phase 2 for the same reason — see its module
202/// doc: "do not `fix` this by routing members through `register_added`".)
203///
204/// The payload's captured metadata records are merged back into the scene store
205/// UN-namespaced, exactly as they were captured: an IMPORT3D feature is not a
206/// component boundary, so there is no instance prefix to apply. The ACOMP lane
207/// namespaces on insert if this document is later used as a part.
208fn restore_native_bodies(ctx: &FeatureContext, payload: &str) -> Result<FeatureResult, String> {
209    let restored = restore_solids(payload)
210        .map_err(|error| format!("import3d: native payload did not decode: {error}"))?;
211    if restored.solids.is_empty() {
212        return Err("import3d: native payload contained no solids".into());
213    }
214    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
215    for solid in restored.solids {
216        let mut body = solid.solid;
217        // Exactly analytic faces in a foreign parametrisation take the
218        // kernel's canonical one (`analytic_surface/canonical.rs`).
219        if crate::canonical_carriers_enabled() {
220            let report = crate::canonicalise_carriers(&mut body);
221            if crate::profile::profile_enabled() && !report.rewritten.is_empty() {
222                profile_line!("import3d.canonical_carriers solid={} rewritten={:?}", solid.name, report.rewritten);
223            }
224        }
225        // A payload encoded straight from `snapshot_solids` (not through
226        // `native_import_payload`) can carry faces the import never named;
227        // those get the import's positional convention under the stored body
228        // name, deterministically from the frozen payload, so picks and CAM
229        // targets resolve and stay the same across save and reopen. Every
230        // name the payload does carry stays verbatim.
231        name_unnamed_native_faces(&mut body, &solid.name);
232        result.added.push(register_verbatim(body, &solid.name));
233    }
234    // Overwriting: the payload's records ARE the part's metadata. The pipeline's
235    // own `sourceFeatureId` seed runs after this feature returns and is
236    // NON-overwriting, so a face keeps the producing-feature id it was imported
237    // with rather than picking up this feature's.
238    for (name, record) in restored.metadata {
239        scene_metadata::merge_record(&name, &record, true);
240    }
241    Ok(result)
242}
243
244/// Name every face of a restored native body that arrived unnamed
245/// `{body}_Face_{f}` (shell / face order, the import's positional fallback),
246/// then re-derive the TOPOLOGY edge names (`{faceA}|{faceB}[n]`, or none) so
247/// the edges along them are named too; an edge the payload named otherwise is
248/// kept. A body whose faces and edges are all named is untouched. Returns
249/// whether anything was named.
250fn name_unnamed_native_faces(solid: &mut BrepSolid, body_name: &str) -> bool {
251    let unnamed = |name: &Option<String>| name.as_deref().is_none_or(|n| n.trim().is_empty());
252    let mut named_any = false;
253    let mut face_index = 0usize;
254    for shell in &mut solid.shells {
255        for face in &mut shell.faces {
256            if unnamed(&face.name) {
257                face.name = Some(format!("{body_name}_Face_{face_index}"));
258                named_any = true;
259            }
260            face_index += 1;
261        }
262    }
263    let edges_unnamed = solid.edges.iter().any(|e| !e.degenerate && unnamed(&e.name));
264    if named_any || edges_unnamed {
265        common::stamp_derived_edge_names(solid);
266    }
267    named_any || edges_unnamed
268}
269
270/// [`common::register_added`] WITHOUT its two name-deriving passes: collect the
271/// names the solid already carries and make it scene-resident.
272///
273/// The container groups are EMPTY, and that is the right answer rather than a
274/// stub: a group is the un-keyed alias a PROFILE-SWEPT feature publishes for its
275/// per-loop face families (`{cap_base}_START` standing for every
276/// `{cap_base}:L{id}_START` — see [`common::register_added_grouped`]). Imported
277/// geometry has no sketch loops behind it, so there is no family to alias; its
278/// names arrived stamped from outside and are already the final, unique ones.
279fn register_verbatim(solid: BrepSolid, name: &str) -> AddedSolid {
280    let face_names = common::collect_face_names(&solid);
281    let edge_names = common::collect_edge_names(&solid);
282    let handle = crate::register_solid_value(solid);
283    AddedSolid {
284        handle,
285        name: name.to_string(),
286        face_names,
287        edge_names,
288        face_groups: Vec::new(),
289        edge_groups: Vec::new(),
290    }
291}
292
293/// Stamp the established naming convention onto the imported bodies, register
294/// them, and stamp whatever COLOUR the file carried onto those same names.
295///
296/// `appearances` is parallel to `solids` (see [`crate::BodyAppearance`]); pass
297/// `&[]` from a lane whose format has no colour, which stamps nothing.
298fn add_named_bodies(
299    ctx: &FeatureContext,
300    mut solids: Vec<BrepSolid>,
301    appearances: &[BodyAppearance],
302    feature_name: &str,
303) -> FeatureResult {
304    let body_names = stamp_imported_names(&mut solids, feature_name);
305    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
306    for (index, (solid, body_name)) in solids.into_iter().zip(body_names).enumerate() {
307        // Colour is stamped AFTER `register_added`, which is where the names
308        // become final (it dedupes face names before deriving the edge names).
309        let added = common::register_added(solid, &body_name);
310        if let Some(appearance) = appearances.get(index) {
311            stamp_appearance(&added.name, &added.face_names, appearance);
312        }
313        result.added.push(added);
314    }
315    result
316}
317
318/// Write an imported body's colours into the scene-metadata store, keyed by the
319/// FINAL names — the one place the `{"color": "#RRGGBB"}` convention of
320/// `io/appearance.rs` is written.
321///
322/// `face_names` is `(face_id, name)` in shell/face order
323/// ([`common::collect_face_names`]), the same order `appearance.faces` is
324/// indexed by. A length disagreement means the two walks have drifted, so
325/// nothing per-face is stamped rather than colouring the wrong faces — the body
326/// colour, which is not positional, still lands.
327///
328/// Merged NON-overwriting: a history replay re-runs this feature, and a colour
329/// the user has since edited in the info panel must survive it.
330fn stamp_appearance(body_name: &str, face_names: &[(u64, String)], appearance: &BodyAppearance) {
331    if let Some(color) = appearance.body {
332        stamp_color(body_name, color);
333    }
334    if appearance.faces.is_empty() || appearance.faces.len() != face_names.len() {
335        return;
336    }
337    for ((_, face_name), color) in face_names.iter().zip(&appearance.faces) {
338        if let Some(color) = color {
339            stamp_color(face_name, *color);
340        }
341    }
342}
343
344fn stamp_color(name: &str, color: ImportedColor) {
345    let mut record = serde_json::Map::new();
346    record.insert(
347        COLOR_METADATA_KEY.to_string(),
348        serde_json::Value::String(color.to_hex()),
349    );
350    scene_metadata::merge_record(name, &record, false);
351}
352
353/// The naming half of [`add_named_bodies`]: stamp body + face names onto `solids`
354/// IN PLACE and return the body name chosen for each, WITHOUT registering
355/// anything. Shared by the live import lanes and the payload encoder
356/// [`native_import_payload`], so an imported part is named identically however it
357/// arrived.
358fn stamp_imported_names(solids: &mut [BrepSolid], feature_name: &str) -> Vec<String> {
359    let body_names = imported_solid_names(solids.len(), feature_name);
360    let multi_body = solids.len() > 1;
361    let mut chosen = Vec::with_capacity(solids.len());
362    for (index, solid) in solids.iter_mut().enumerate() {
363        let body_name = body_names
364            .get(index)
365            .cloned()
366            .unwrap_or_else(|| feature_name.to_string());
367        let mut face_index = 0usize;
368        for shell in &mut solid.shells {
369            for face in &mut shell.faces {
370                if multi_body {
371                    // Multi-body: EVERY face namespaced under its body.
372                    face.name = Some(format!("{body_name}_Face_{face_index}"));
373                } else {
374                    // Single body: prepend the (unique) feature name so faces never
375                    // collide with ANOTHER import's faces — two single-body imports
376                    // both stamped bare `Face_N` before, which the cross-solid
377                    // name-uniqueness guard flags. Keep any STEP-authored name as the
378                    // stem, else the positional `Face_N` fallback. (`body_name` IS the
379                    // feature name here — see `imported_solid_names`.) Edge names are
380                    // re-derived from these face names downstream, so namespacing the
381                    // faces namespaces the derived edges too.
382                    let stem = face
383                        .name
384                        .as_deref()
385                        .map(str::trim)
386                        .filter(|name| !name.is_empty())
387                        .map(str::to_string)
388                        .unwrap_or_else(|| format!("Face_{face_index}"));
389                    face.name = Some(format!("{body_name}_{stem}"));
390                }
391                face_index += 1;
392            }
393        }
394        chosen.push(body_name);
395    }
396    chosen
397}
398
399/// `importedSolidNames` port: 1 body keeps the feature name; several get a
400/// stable, zero-padded `{feature}_SOLID_0N` suffix.
401pub fn imported_solid_names(count: usize, feature_name: &str) -> Vec<String> {
402    if count == 0 {
403        return Vec::new();
404    }
405    if count == 1 {
406        return vec![feature_name.to_string()];
407    }
408    let digits = count.to_string().len().max(2);
409    (1..=count)
410        .map(|index| format!("{feature_name}_SOLID_{index:0width$}", width = digits))
411        .collect()
412}
413
414/// Encode `solids` as a native IMPORT3D payload: stamp the names this feature
415/// would stamp under `feature_name`, then seal them into the `io/snapshot`
416/// container. The result is exactly what the `nativeBrep` source above reads
417/// back, so a part is named identically however it arrived — imported live from
418/// a text source, or restored from a payload built here.
419///
420/// GENERIC, not STEP-specific: any producer of finished `BrepSolid`s that wants
421/// them to become an IMPORT3D part document uses this (the STEP-assembly import
422/// lane is the first caller).
423///
424/// The two passes after the stamping are `register_added`'s name-FINALIZING half
425/// (`common::ensure_unique_face_names` + `common::stamp_derived_edge_names`),
426/// applied HERE rather than at restore time: the `nativeBrep` lane registers
427/// verbatim, so whatever the payload carries IS the final name set. Without them
428/// a payload's edge names would be the importer's raw ones while the `stepText`
429/// lane's are the derived `{faceA}|{faceB}[n]` — the same geometry under two
430/// different name sets, which is exactly what this helper exists to prevent.
431///
432/// The payload is byte-deterministic for identical input (`snapshot_solids`), so
433/// two encodings of the same part collapse to ONE parts-library entry.
434pub fn native_import_payload(feature_name: &str, solids: &[BrepSolid]) -> Result<String, String> {
435    native_import_payload_with_appearance(feature_name, solids, &[])
436}
437
438/// [`native_import_payload`] carrying the import's COLOURS into the payload.
439///
440/// `appearances` is parallel to `solids` (see [`crate::BodyAppearance`]); `&[]`
441/// is the colourless case and makes this identical to [`native_import_payload`].
442///
443/// The colours are stamped into the AMBIENT scene-metadata store just before
444/// `snapshot_solids`, which is exactly how they get INTO the payload — the
445/// snapshot captures each stamped name's own record alongside the geometry. So a
446/// caller that runs this inside a `crate::IsolatedSceneMetadata` bracket (the
447/// STEP-assembly part-document lane does, and must) gets the colours sealed into
448/// the part and discarded from the live document, which is the whole point of
449/// that bracket: the part carries its own metadata, the open document is not
450/// touched.
451pub fn native_import_payload_with_appearance(
452    feature_name: &str,
453    solids: &[BrepSolid],
454    appearances: &[BodyAppearance],
455) -> Result<String, String> {
456    if solids.is_empty() {
457        return Err("import3d: native payload needs at least one solid".into());
458    }
459    let mut bodies = solids.to_vec();
460    let body_names = stamp_imported_names(&mut bodies, feature_name);
461    for solid in &mut bodies {
462        common::ensure_unique_face_names(solid);
463        common::stamp_derived_edge_names(solid);
464    }
465    // Names are FINAL from here, so this is where colour can be keyed to them.
466    for (index, (solid, body_name)) in bodies.iter().zip(&body_names).enumerate() {
467        if let Some(appearance) = appearances.get(index) {
468            stamp_appearance(body_name, &common::collect_face_names(solid), appearance);
469        }
470    }
471    let named: Vec<(&str, &BrepSolid)> = body_names
472        .iter()
473        .map(String::as_str)
474        .zip(bodies.iter())
475        .collect();
476    crate::snapshot_solids(&named)
477}
478
479
480/// Context-bar applicability ([`crate::feature_pipeline::context_offer`]):
481/// never offered from a selection (no reference inputs).
482pub fn context_applicable(_probe: &crate::feature_pipeline::SelectionProbe) -> bool {
483    false
484}
485
486///
487/// Only `id` is exposed: an IMPORT3D feature is created by an import lane that
488/// bakes its payload in — the toolbar Import lane
489/// ([`EngineState::import_step_feature`] / `import_iges_feature` /
490/// `import_xt_feature`) writes the raw document text into
491/// `inputParams.stepText` / `igesText` / `xtText`, and the native lane
492/// ([`native_import_payload`], the STEP-assembly part document) writes
493/// `inputParams.nativeBrep`. None of them is form-editable, so none is
494/// exposed. (The former `fileToImport` "file" param was a JS-era vestige: nothing
495/// produced or consumed it and no form builder rendered it.)
496pub fn schema() -> serde_json::Value {
497    serde_json::json!({
498    "type": "IMPORT3D",
499    "shortName": "IMPORT3D",
500    "longName": "Import 3D Model",
501    "ribbonPath": "Home/Modeling/Import 3D Model",
502    "commandSize": "Compact",
503    "displayBuilder": false,
504    "inputParamsSchema": {
505        "id": {
506            "type": "string",
507            "default_value": null,
508            "hint": "unique identifier for the import feature"
509        }
510    }
511})
512}
513