Skip to main content

brep_kernel/io/step_import/
mod.rs

1//! STEP Part 21 import for NURBS and analytic surfaces, assemblies, and PMI.
2//!
3//! The importer reconstructs and validates BREP topology. Analytic carriers are
4//! converted to NURBS sized to the face bounds. Seam edges occupy opposite
5//! parameter boundaries, and collapsed pole bounds become degenerate edges so
6//! faces close and integrate correctly.
7//!
8//! Pcurves are DERIVED, by projecting each edge onto its carrier; a
9//! `SURFACE_CURVE`/`SEAM_CURVE` bundle contributes only its 3D curve.
10//!
11//! [`supplied`] can read the bundle's `PCURVE` associations instead and seat
12//! the vendor's own stated trim, and does so correctly, but it is OFF unless
13//! `BREP_SUPPLIED_PCURVES=1`. Not caution — measurement. Preferring a supplied
14//! pcurve helps only where the edge's 3D curve has drifted off its own carrier,
15//! and nothing distinguishes that case from the ones where it hurts: our own
16//! exporter writes exact analytic 3D curves with fitted pcurves, so seating the
17//! fit cost a round trip through our writer a factor of 4800 in volume
18//! fidelity. See `supplied::supplied_pcurves_enabled` for the full derivation.
19
20use crate::topology::{
21    BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord,
22};
23use crate::{
24    build_pcurve_on_surface_range, make_arc, make_extrusion, make_hyperbola, make_line,
25    make_parabola, make_plane, make_revolution, offset_surface, transform_brep, AffineTransform,
26    KernelRefusal, NurbsCurve, NurbsSurface, Vec3, Vec4,
27};
28use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
29use std::collections::VecDeque;
30
31const TAU: f64 = std::f64::consts::TAU;
32
33pub(crate) mod parse;
34mod supplied;
35mod bodies;
36mod assembly;
37mod assembly_pmi;
38mod mapped;
39mod builder;
40mod geometry;
41mod styles;
42mod pmi;
43mod precision;
44mod trim_readings;
45/// The projected-foot refinement's body face cap (`0` = uncapped); the
46/// soundness fixture sweep reads it to know which trims the import refined.
47#[cfg_attr(not(test), allow(unused_imports))]
48pub(crate) use builder::loops::projected_foot_refine_body_faces;
49
50use crate::appearance::{BodyAppearance, ImportedColor};
51use parse::*;
52use supplied::*;
53use bodies::*;
54use mapped::*;
55use builder::*;
56use geometry::*;
57use styles::*;
58pub use assembly::{read_step_assembly, StepAssembly, StepOccurrence, StepProduct};
59pub use assembly_pmi::{occurrence_ref_parts, rewrite_occurrence_refs, OCCURRENCE_REF_PREFIX};
60pub use mapped::StepMappedItemError;
61pub use pmi::read_step_pmi;
62pub use precision::STATED_PRECISION_INCONSISTENCY_RATIO;
63pub use trim_readings::{
64    import_step_trim_readings, StepBodyTrimReadings, StepEdgeReading, StepFaceReading,
65    StepSuppliedTrim, StepTrimReadings,
66};
67pub(crate) use pmi::decode_step_text as decode_step_text_for_tests;
68
69
70// ---------------------------------------------------------------------------
71// Topology assembly
72// ---------------------------------------------------------------------------
73
74/// Why one body did not import: the builders' legacy text, or a TYPED refusal
75/// from the one gate that mints one today, the shell-closure gate
76/// (`builder/closure.rs`). The class rides to the feature boundary through
77/// [`import_step_bodies`]; every other producer inside the importer still
78/// returns text and is preserved verbatim (typed-refusal plan, item 1).
79#[derive(Clone, Debug, PartialEq)]
80pub enum StepBodyError {
81    Text(String),
82    Refused(crate::KernelRefusal),
83}
84
85impl StepBodyError {
86    /// The human text either way — the refusal's own message, verbatim.
87    pub fn message(&self) -> &str {
88        match self {
89            Self::Text(text) => text,
90            Self::Refused(refusal) => &refusal.message,
91        }
92    }
93
94    /// Whether this is the shell-closure gate's refusal
95    /// (`RefusalClass::UnsoundResult { defect: SoundnessDefect::VectorArea }`,
96    /// `builder/closure.rs`): the one typed class the body lanes treat as a
97    /// REFUSED body rather than a body that failed to build. Every other
98    /// producer that went typed on 2026-10-03 (the pinched-vertex split, the
99    /// `BREP_WITH_VOIDS` certifications, the post-build validation) keeps the
100    /// outcome its text had: counted in `failed`, skipped on an opportunistic
101    /// surface-model sheet, never a whole-file refusal.
102    pub fn closure_refusal(&self) -> bool {
103        matches!(
104            self,
105            Self::Refused(crate::KernelRefusal {
106                class: crate::RefusalClass::UnsoundResult {
107                    defect: crate::SoundnessDefect::VectorArea,
108                    ..
109                },
110                ..
111            })
112        )
113    }
114
115    /// The same error with its text rewritten by `f`, the class untouched.
116    pub fn with_context(self, f: impl FnOnce(&str) -> String) -> Self {
117        match self {
118            Self::Text(text) => Self::Text(f(&text)),
119            Self::Refused(refusal) => Self::Refused(refusal.with_message(f)),
120        }
121    }
122}
123
124impl From<String> for StepBodyError {
125    fn from(text: String) -> Self {
126        Self::Text(text)
127    }
128}
129
130impl From<&str> for StepBodyError {
131    fn from(text: &str) -> Self {
132        Self::Text(text.to_string())
133    }
134}
135
136impl From<crate::KernelRefusal> for StepBodyError {
137    fn from(refusal: crate::KernelRefusal) -> Self {
138        Self::Refused(refusal)
139    }
140}
141
142impl std::fmt::Display for StepBodyError {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.write_str(self.message())
145    }
146}
147
148/// Public entry: parse a STEP Part 21 document and return one `BrepSolid` per
149/// MANIFOLD_SOLID_BREP, FACETED_BREP, or certified BREP_WITH_VOIDS. Every
150/// returned solid passes `validate()` and closes its shells' vector area to
151/// the import's bar; a file with a body the closure gate refuses is refused
152/// as a whole (see [`import_step_bodies`]).
153pub fn import_step(text: &str) -> Result<Vec<BrepSolid>, String> {
154    Ok(import_step_with_appearance(text)?.0)
155}
156
157/// [`import_step_with_appearance`] with the error TYPED: the lane the IMPORT3D
158/// feature uses, so a refused body reaches the app as a class and not only as
159/// text.
160///
161/// **A refused body refuses the import.** `collect_step_solids` skips a body
162/// that failed to build and returns the rest, counting it in `failed`, and
163/// until 2026-09-30 this entry point returned those bodies as a success —
164/// the count and the first error never left `ImportedBodies`, so a file with
165/// a body the importer could not build imported SILENTLY short. A body the
166/// closure gate refuses is a body the file describes and the kernel declines
167/// to certify, and returning the others as the file's contents would be the
168/// partial result the typed-refusal plan rules out ("partial geometry is not a
169/// successful result"). The feature has no per-body typed slot to say "five
170/// of seven" (`Fulfilment::rejected` is a closed selection-resolution kind),
171/// so the whole import is refused with the first body's class and a message
172/// naming every refused body; the report lane ([`import_step_report`]) keeps
173/// returning the bodies that did build beside the refusals, for tools that
174/// want to read them. Bodies that fail with TEXT keep the pre-2026-09-30
175/// behaviour (skipped, the rest returned) — changing that is the plan's
176/// migration of the builder boundary, not this gate's.
177pub fn import_step_bodies(text: &str) -> Result<ImportedStep, StepBodyError> {
178    let imported = collect_step_solids(text)?;
179    if let Some(first) = imported.refused_bodies.first() {
180        let others = imported.refused_bodies.len() - 1;
181        let refusal = if others == 0 {
182            first.clone()
183        } else {
184            let rest: Vec<String> = imported.refused_bodies[1..]
185                .iter()
186                .map(|refusal| refusal.message.clone())
187                .collect();
188            first.clone().with_message(|message| {
189                format!("{message} And {others} more: {}", rest.join(" "))
190            })
191        };
192        return Err(StepBodyError::Refused(refusal.with_message(|message| {
193            format!(
194                "{} of {} bodies refused as open; {}",
195                imported.refused_bodies.len(),
196                imported.solids.len() + imported.failed,
197                message
198            )
199        })));
200    }
201    if imported.solids.is_empty() {
202        return Err(StepBodyError::Text(imported.first_error.unwrap_or_else(|| {
203            "step_import: no MANIFOLD_SOLID_BREP/FACETED_BREP/BREP_WITH_VOIDS body imported (unsupported or invalid representation)"
204                .into()
205        })));
206    }
207    let approximations = imported
208        .closure_notes
209        .iter()
210        .enumerate()
211        .filter_map(|(index, note)| note.approximation().map(|a| (index, a.clone())))
212        .collect();
213    Ok(ImportedStep {
214        solids: imported.solids,
215        appearances: imported.appearances,
216        approximations,
217    })
218}
219
220/// What [`import_step_bodies`] returns: the bodies, their colours, and the
221/// typed approximations the closure gate attached to some of them.
222#[derive(Clone, Debug)]
223pub struct ImportedStep {
224    /// One solid per body that reconstructed, in file order.
225    pub solids: Vec<BrepSolid>,
226    /// One per solid, in the same order (default when the file has none).
227    pub appearances: Vec<BodyAppearance>,
228    /// `(index into solids, approximation)` for every body the closure gate
229    /// imported over its bar (`builder/closure.rs`): a typed statement that
230    /// the body's volume is determined only to the bound the approximation
231    /// carries. Empty on a file whose every body closes.
232    pub approximations: Vec<(usize, crate::Approximation)>,
233}
234
235/// [`import_step`] plus the file's PRESENTATION colours: one
236/// [`BodyAppearance`] per returned solid, in the same order.
237///
238/// This is the lane the IMPORT3D feature uses, because colour is stamped as
239/// scene metadata on the names IT chooses — see
240/// `feature_pipeline::features::import3d` and `io/appearance.rs` for the record
241/// shape. A file with no presentation entities returns default (empty)
242/// appearances, never a short vector, so callers can `zip` unconditionally.
243pub fn import_step_with_appearance(
244    text: &str,
245) -> Result<(Vec<BrepSolid>, Vec<BodyAppearance>), String> {
246    import_step_bodies(text)
247        .map(|imported| (imported.solids, imported.appearances))
248        .map_err(|error| error.to_string())
249}
250
251/// What [`import_step_report`] returns: the bodies, how gracefully the file
252/// imported, and the import's diagnostics.
253#[derive(Clone, Debug)]
254pub struct StepImportReport {
255    /// One solid per body that reconstructed, in file order.
256    pub solids: Vec<BrepSolid>,
257    /// The file's presentation colours, one per solid in the same order
258    /// (default where the file styles nothing), as
259    /// [`import_step_with_appearance`] returns them.
260    pub appearances: Vec<BodyAppearance>,
261    /// Things that did not come in (skipped, not fatal): a body that failed to
262    /// reconstruct, an occurrence whose transform failed, or a mapping that was
263    /// refused (`mapped::StepMappedItemError`).
264    pub failed: usize,
265    /// The first such failure's text, when `failed > 0`.
266    pub first_error: Option<String>,
267    /// The bodies the shell-closure gate refused, typed
268    /// (`RefusalClass::UnsoundResult { defect: SoundnessDefect::VectorArea }`),
269    /// in file order. Each is counted in `failed`. [`import_step`] and the
270    /// feature lane refuse the whole file on any of these; this lane returns
271    /// the bodies that did import beside them.
272    pub refused: Vec<crate::KernelRefusal>,
273    /// The bodies that FAILED to build with a typed cause that is not the
274    /// closure gate's, in file order: the pinched-vertex split, a
275    /// `BREP_WITH_VOIDS` certification, the post-build validation
276    /// (2026-10-03). Each is counted in `failed`, and the first is
277    /// `first_error`'s text; none refuses the whole file on any lane, which
278    /// is the outcome their text had.
279    pub failed_refusals: Vec<crate::KernelRefusal>,
280    /// Open surface-model sheets skipped (not solids, so not in `failed`);
281    /// also the counter `SHEETS_SKIPPED` in `diagnostics`.
282    pub sheets_skipped: usize,
283    /// `(index into solids, approximation)` for every imported body whose
284    /// shell closes over its bar (`import.shell_closure`); see
285    /// [`ImportedStep::approximations`].
286    pub approximations: Vec<(usize, crate::Approximation)>,
287    /// Every precision the file states, in millimetres, ascending — see
288    /// `parse::stated_precisions_mm`. Empty when it states none.
289    pub stated_precisions_mm: Vec<f64>,
290    /// The import's diagnostics: measurements always, plus one
291    /// `import.stated_precision_inconsistent` warning when the file's stated
292    /// precision is far under the deviation its own geometry shows
293    /// (`precision::stated_precision_diagnostics`). Informational only —
294    /// acceptance never depends on it.
295    pub diagnostics: crate::KernelDiagnostics,
296}
297
298/// The event code for a body that carries a derived trim off the fit bar (the
299/// 1e-7 floor plus its stations' standoff) after the refit at the floor, which
300/// the importer accepts as it did every fit before the bar, and the counters
301/// and measure beside it. The residual
302/// is the band `EntityTolerances` measures for that edge; the event names how
303/// many are the file's residual and how many the fitter's miss, and the worst
304/// with its numbers, so what the importer accepted before the bar silently is
305/// visible (2026-09-26). Since 2026-10-03 both numbers are read BETWEEN the
306/// fit's stations too (`geometry::trim_floor_reading`) and the class is the
307/// corrected bar's: a trim within the floor of the file curve's standoff is
308/// the file's residual whatever its image does along the carrier.
309pub const TRIM_BOUNDED: &str = "import.trim_bounded";
310pub const TRIMS_BOUNDED: &str = "import.trims_bounded";
311pub const TRIMS_FITTER_MISS: &str = "import.trims_fitter_miss";
312pub const TRIM_BOUND_MM: &str = "import.trim_bound_mm";
313/// Bounded trims whose fit was CLAMPED into the carrier's chart, and the worst
314/// 3D distance that clamp corresponds to (2026-09-30; a report, not a bar).
315pub const TRIMS_CLAMPED: &str = "import.trims_clamped";
316pub const TRIM_CLAMP_MM: &str = "import.trim_clamp_mm";
317
318/// The shell-closure gate's readings on the bodies it ACCEPTED
319/// (`builder/closure.rs`): the worst residual-to-bar ratio over the accepted
320/// bodies, how many bodies the scan could not judge (span budget or an
321/// unreadable face — accepted unjudged, one Degraded event each), and how
322/// many bodies it refused (also in [`StepImportReport::refused`]).
323pub const CLOSURE_RATIO_MAX: &str = "import.closure_ratio_max";
324pub const CLOSURE_APPROXIMATE: &str = "import.closure_approximate";
325pub const CLOSURE_UNJUDGED: &str = "import.closure_unjudged";
326pub const CLOSURE_REFUSED: &str = "import.closure_refused";
327
328/// Open `SHELL_BASED_SURFACE_MODEL` sheets the importer SKIPPED, counted
329/// where it drops them (the flat lane, the occurrence lane once per part, and
330/// [`import_step_assembly`] once per product body). A sheet is not a solid,
331/// so it is neither `failed` nor `refused`; before 2026-10-12 it vanished
332/// uncounted (table 3: ten in `BIMExample-Site.step`).
333pub const SHEETS_SKIPPED: &str = "import.sheets_skipped";
334
335fn closure_diagnostics(
336    notes: &[builder::ClosureNote],
337    refused: &[crate::KernelRefusal],
338    diagnostics: &mut crate::KernelDiagnostics,
339) {
340    for (index, note) in notes.iter().enumerate() {
341        match note {
342            builder::ClosureNote::Closed { residual, bar } => {
343                diagnostics.measure_max(CLOSURE_RATIO_MAX, residual / bar);
344            }
345            builder::ClosureNote::Approximate(approximation) => {
346                diagnostics.measure_max(CLOSURE_RATIO_MAX, approximation.measured / approximation.bar);
347                diagnostics.count(CLOSURE_APPROXIMATE);
348                diagnostics.event(
349                    crate::DiagnosticSeverity::Degraded,
350                    crate::KernelStage::Validate,
351                    CLOSURE_APPROXIMATE,
352                    format!("body {index}: {}", approximation.message),
353                );
354            }
355            builder::ClosureNote::Unmeasured { reason, spans } => {
356                diagnostics.count(CLOSURE_UNJUDGED);
357                diagnostics.event(
358                    crate::DiagnosticSeverity::Degraded,
359                    crate::KernelStage::Validate,
360                    CLOSURE_UNJUDGED,
361                    format!("body {index}: shell closure not judged — {reason} ({spans} spans); the body is accepted unjudged, not certified closed."),
362                );
363            }
364            builder::ClosureNote::Unreadable { first, count } => {
365                diagnostics.count(CLOSURE_UNJUDGED);
366                diagnostics.event(
367                    crate::DiagnosticSeverity::Degraded,
368                    crate::KernelStage::Validate,
369                    CLOSURE_UNJUDGED,
370                    format!("body {index}: shell closure not judged — {count} face(s) unreadable by the scan, first: {first}; the body is accepted unjudged, not certified closed."),
371                );
372            }
373            builder::ClosureNote::Unjudged => {
374                diagnostics.count(CLOSURE_UNJUDGED);
375            }
376            builder::ClosureNote::Overridden(refusal) => {
377                diagnostics.count(CLOSURE_UNJUDGED);
378                diagnostics.event(
379                    crate::DiagnosticSeverity::Degraded,
380                    crate::KernelStage::Validate,
381                    CLOSURE_UNJUDGED,
382                    format!("body {index}: the closure guard is OFF (BREP_IMPORT_CLOSURE_GUARD=0); it would have refused: {}", refusal.message),
383                );
384            }
385        }
386    }
387    diagnostics.count_n(CLOSURE_REFUSED, refused.len() as u64);
388}
389
390fn bounded_trim_diagnostics(
391    bounded: &[Vec<builder::readings::BoundedTrim>],
392    diagnostics: &mut crate::KernelDiagnostics,
393) {
394    for (index, trims) in bounded.iter().enumerate() {
395        let Some(worst) = trims
396            .iter()
397            .max_by(|a, b| a.residual.partial_cmp(&b.residual).unwrap_or(std::cmp::Ordering::Equal))
398        else {
399            continue;
400        };
401        let fitters = trims.iter().filter(|trim| trim.fitter).count();
402        let clamped = trims.iter().filter(|trim| trim.clamped_excursion > 0.0).count();
403        let worst_clamp = trims.iter().map(|trim| trim.clamped_distance).fold(0.0f64, f64::max);
404        diagnostics.count_n(TRIMS_BOUNDED, trims.len() as u64);
405        diagnostics.count_n(TRIMS_FITTER_MISS, fitters as u64);
406        diagnostics.measure_max(TRIM_BOUND_MM, worst.residual);
407        diagnostics.count_n(TRIMS_CLAMPED, clamped as u64);
408        diagnostics.measure_max(TRIM_CLAMP_MM, worst_clamp);
409        diagnostics.event(
410            crate::DiagnosticSeverity::Degraded,
411            crate::KernelStage::Collect,
412            TRIM_BOUNDED,
413            format!(
414                "body {index}: {} trim(s) sit off the {:.0e} mm fit bar and carry their measured residual as their band ({} of them the file's residual, within the floor of the curve's standoff read between the stations; {} the fitter's miss); worst ADVANCED_FACE #{} (surface #{}) edge {}: {:.3e} mm, its curve {:.3e} mm off the carrier, the image {:.3e} mm off its feet ({}; {} at {} samples).{}",
415                trims.len(),
416                crate::PCURVE_REFINEMENT_TOLERANCE,
417                trims.len() - fitters,
418                fitters,
419                worst.face_ref,
420                worst.surface_ref,
421                worst.edge_id,
422                worst.residual,
423                worst.standoff,
424                worst.image_to_foot,
425                if worst.fitter { "the fitter's miss" } else { "the file's residual" },
426                worst.exit,
427                worst.samples,
428                if clamped > 0 {
429                    format!(" {clamped} of them were clamped into their chart, by up to {worst_clamp:.3e} mm.")
430                } else {
431                    String::new()
432                }
433            ),
434        );
435    }
436}
437
438/// Like [`import_step`] but reports how many bodies failed and the first error,
439/// so callers can distinguish a fully- from a partially-imported assembly —
440/// and runs the stated-precision consistency check over the imported bodies,
441/// whose result rides in [`StepImportReport::diagnostics`].
442///
443/// The check measures every edge and vertex of every body (the same
444/// `EntityTolerances` reading the per-entity-tolerance census took), which is
445/// why it lives on this lane and not on [`import_step_with_appearance`]: the
446/// feature pipeline has no diagnostics channel to carry the answer, and a
447/// measurement nobody reads is not worth its cost on every IMPORT3D.
448pub fn import_step_report(text: &str) -> Result<StepImportReport, String> {
449    import_step_report_with(text, false)
450}
451
452/// [`import_step_report`] building every OPEN_SHELL as a sheet body
453/// (`BodyKind::Sheet`) among its solids, not skipping it: the Parasolid
454/// lane's, whose translation writes a sheet body as an open shell.
455pub(crate) fn import_step_report_with_sheets(text: &str) -> Result<StepImportReport, String> {
456    import_step_report_with(text, true)
457}
458
459fn import_step_report_with(text: &str, sheets: bool) -> Result<StepImportReport, String> {
460    let imported = bodies::collect_step_solids_with(text, sheets)?;
461    let mut diagnostics =
462        precision::stated_precision_diagnostics(&imported.stated_precisions_mm, &imported.solids);
463    bounded_trim_diagnostics(&imported.bounded_trims, &mut diagnostics);
464    closure_diagnostics(&imported.closure_notes, &imported.refused_bodies, &mut diagnostics);
465    diagnostics.count_n(SHEETS_SKIPPED, imported.sheets_skipped as u64);
466    Ok(StepImportReport {
467        solids: imported.solids,
468        appearances: imported.appearances,
469        failed: imported.failed,
470        first_error: imported.first_error,
471        refused: imported.refused_bodies,
472        failed_refusals: imported.failed_refusals,
473        sheets_skipped: imported.sheets_skipped,
474        approximations: imported
475            .closure_notes
476            .iter()
477            .enumerate()
478            .filter_map(|(index, note)| note.approximation().map(|a| (index, a.clone())))
479            .collect(),
480        stated_precisions_mm: imported.stated_precisions_mm,
481        diagnostics,
482    })
483}