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;
45mod tessellated;
46pub(crate) use bodies::import_lean;
47/// The projected-foot refinement's body face cap (`0` = uncapped); the
48/// soundness fixture sweep reads it to know which trims the import refined.
49#[cfg_attr(not(test), allow(unused_imports))]
50pub(crate) use builder::loops::projected_foot_refine_body_faces;
51
52use crate::appearance::{BodyAppearance, ImportedColor};
53use parse::*;
54use supplied::*;
55use bodies::*;
56use mapped::*;
57use builder::*;
58use geometry::*;
59use styles::*;
60pub use assembly::{
61 read_step_assembly, read_step_assembly_outline, StepAssembly, StepAssemblyOutline, StepOccurrence,
62 StepProduct,
63};
64pub use assembly_pmi::{occurrence_ref_parts, rewrite_occurrence_refs, OCCURRENCE_REF_PREFIX};
65pub use mapped::StepMappedItemError;
66pub use pmi::read_step_pmi;
67pub use precision::STATED_PRECISION_INCONSISTENCY_RATIO;
68pub use trim_readings::{
69 import_step_trim_readings, StepBodyTrimReadings, StepEdgeReading, StepFaceReading,
70 StepSuppliedTrim, StepTrimReadings,
71};
72pub(crate) use pmi::decode_step_text as decode_step_text_for_tests;
73
74
75// ---------------------------------------------------------------------------
76// Topology assembly
77// ---------------------------------------------------------------------------
78
79/// Why one body did not import: the builders' legacy text, or a TYPED refusal
80/// from the one gate that mints one today, the shell-closure gate
81/// (`builder/closure.rs`). The class rides to the feature boundary through
82/// [`import_step_bodies`]; every other producer inside the importer still
83/// returns text and is preserved verbatim (typed-refusal plan, item 1).
84#[derive(Clone, Debug, PartialEq)]
85pub enum StepBodyError {
86 Text(String),
87 Refused(crate::KernelRefusal),
88}
89
90impl StepBodyError {
91 /// The human text either way — the refusal's own message, verbatim.
92 pub fn message(&self) -> &str {
93 match self {
94 Self::Text(text) => text,
95 Self::Refused(refusal) => &refusal.message,
96 }
97 }
98
99 /// Whether this is the shell-closure gate's refusal
100 /// (`RefusalClass::UnsoundResult { defect: SoundnessDefect::VectorArea }`,
101 /// `builder/closure.rs`): the one typed class the body lanes treat as a
102 /// REFUSED body rather than a body that failed to build. Every other
103 /// producer that went typed on 2026-10-03 (the pinched-vertex split, the
104 /// `BREP_WITH_VOIDS` certifications, the post-build validation) keeps the
105 /// outcome its text had: counted in `failed`, skipped on an opportunistic
106 /// surface-model sheet, never a whole-file refusal.
107 pub fn closure_refusal(&self) -> bool {
108 matches!(
109 self,
110 Self::Refused(crate::KernelRefusal {
111 class: crate::RefusalClass::UnsoundResult {
112 defect: crate::SoundnessDefect::VectorArea,
113 ..
114 },
115 ..
116 })
117 )
118 }
119
120 /// The same error with its text rewritten by `f`, the class untouched.
121 pub fn with_context(self, f: impl FnOnce(&str) -> String) -> Self {
122 match self {
123 Self::Text(text) => Self::Text(f(&text)),
124 Self::Refused(refusal) => Self::Refused(refusal.with_message(f)),
125 }
126 }
127}
128
129impl From<String> for StepBodyError {
130 fn from(text: String) -> Self {
131 Self::Text(text)
132 }
133}
134
135impl From<&str> for StepBodyError {
136 fn from(text: &str) -> Self {
137 Self::Text(text.to_string())
138 }
139}
140
141impl From<crate::KernelRefusal> for StepBodyError {
142 fn from(refusal: crate::KernelRefusal) -> Self {
143 Self::Refused(refusal)
144 }
145}
146
147impl std::fmt::Display for StepBodyError {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.write_str(self.message())
150 }
151}
152
153/// Public entry: parse a STEP Part 21 document and return one `BrepSolid` per
154/// MANIFOLD_SOLID_BREP, FACETED_BREP, or certified BREP_WITH_VOIDS. Every
155/// returned solid passes `validate()` and closes its shells' vector area to
156/// the import's bar; a file with a body the closure gate refuses is refused
157/// as a whole (see [`import_step_bodies`]).
158pub fn import_step(text: &str) -> Result<Vec<BrepSolid>, String> {
159 Ok(import_step_with_appearance(text)?.0)
160}
161
162/// [`import_step_with_appearance`] with the error TYPED: the lane the IMPORT3D
163/// feature uses, so a refused body reaches the app as a class and not only as
164/// text.
165///
166/// **A refused body refuses the import.** `collect_step_solids` skips a body
167/// that failed to build and returns the rest, counting it in `failed`, and
168/// until 2026-09-30 this entry point returned those bodies as a success —
169/// the count and the first error never left `ImportedBodies`, so a file with
170/// a body the importer could not build imported SILENTLY short. A body the
171/// closure gate refuses is a body the file describes and the kernel declines
172/// to certify, and returning the others as the file's contents would be the
173/// partial result the typed-refusal plan rules out ("partial geometry is not a
174/// successful result"). The feature has no per-body typed slot to say "five
175/// of seven" (`Fulfilment::rejected` is a closed selection-resolution kind),
176/// so the whole import is refused with the first body's class and a message
177/// naming every refused body; the report lane ([`import_step_report`]) keeps
178/// returning the bodies that did build beside the refusals, for tools that
179/// want to read them. Bodies that fail with TEXT keep the pre-2026-09-30
180/// behaviour (skipped, the rest returned) — changing that is the plan's
181/// migration of the builder boundary, not this gate's.
182pub fn import_step_bodies(text: &str) -> Result<ImportedStep, StepBodyError> {
183 // The trim readings feed only the report's diagnostics, which this lane
184 // never builds.
185 let imported = bodies::collect_step_solids_dropping_readings(text)?;
186 if let Some(first) = imported.refused_bodies.first() {
187 let others = imported.refused_bodies.len() - 1;
188 let refusal = if others == 0 {
189 first.clone()
190 } else {
191 let rest: Vec<String> = imported.refused_bodies[1..]
192 .iter()
193 .map(|refusal| refusal.message.clone())
194 .collect();
195 first.clone().with_message(|message| {
196 format!("{message} And {others} more: {}", rest.join(" "))
197 })
198 };
199 return Err(StepBodyError::Refused(refusal.with_message(|message| {
200 format!(
201 "{} of {} bodies refused as open; {}",
202 imported.refused_bodies.len(),
203 imported.solids.len() + imported.failed,
204 message
205 )
206 })));
207 }
208 if imported.solids.is_empty() {
209 // A SURFACE MODEL and nothing else (`BREP_STEP_SURFACE_MODEL_SHEETS`,
210 // default on, =0 restores the refusal): a file whose only bodies are
211 // open SHELL_BASED_SURFACE_MODEL shells, which the solid lane skips,
212 // reads as those sheets (`BodyKind::Sheet`), as the Parasolid and IGES
213 // lanes already read theirs. Until 2026-11-26 such a file was refused as
214 // having no body (step-conformance's bowl_01: five faces of a revolved
215 // bowl, written by Open CASCADE). A file with any solid, or any body
216 // that failed, is unchanged; so is a sheet read that fails or refuses.
217 if imported.failed == 0
218 && imported.sheets_skipped > 0
219 && crate::switch!("BREP_STEP_SURFACE_MODEL_SHEETS", true)
220 {
221 if let Ok(sheets) = bodies::collect_step_solids_with(text, true, false) {
222 if sheets.failed == 0 && sheets.refused_bodies.is_empty() && !sheets.solids.is_empty() {
223 return Ok(ImportedStep { solids: sheets.solids, appearances: sheets.appearances, approximations: Vec::new() });
224 }
225 }
226 }
227 // A file of AP242 tessellated solids and no B-rep body at all reads as
228 // polyhedra; a B-rep body that failed keeps its own error.
229 let entities = parse_data_section(text).map_err(StepBodyError::Text)?;
230 let brep = entities.values().any(|e| e.has("MANIFOLD_SOLID_BREP") || e.has("FACETED_BREP") || e.has("BREP_WITH_VOIDS"));
231 let solids = if brep || imported.failed > 0 {
232 Vec::new()
233 } else {
234 tessellated::tessellated_solids(&entities, derive_length_scale_mm(&entities)).map_err(StepBodyError::Text)?
235 };
236 if !solids.is_empty() {
237 let appearances = solids.iter().map(|_| BodyAppearance::default()).collect();
238 return Ok(ImportedStep { solids, appearances, approximations: Vec::new() });
239 }
240 return Err(StepBodyError::Text(imported.first_error.unwrap_or_else(|| {
241 "step_import: no MANIFOLD_SOLID_BREP/FACETED_BREP/BREP_WITH_VOIDS body imported (unsupported or invalid representation)"
242 .into()
243 })));
244 }
245 let approximations = imported
246 .closure_notes
247 .iter()
248 .enumerate()
249 .filter_map(|(index, note)| note.approximation().map(|a| (index, a.clone())))
250 .collect();
251 Ok(ImportedStep {
252 solids: imported.solids,
253 appearances: imported.appearances,
254 approximations,
255 })
256}
257
258/// What [`import_step_bodies`] returns: the bodies, their colours, and the
259/// typed approximations the closure gate attached to some of them.
260#[derive(Clone, Debug)]
261pub struct ImportedStep {
262 /// One solid per body that reconstructed, in file order.
263 pub solids: Vec<BrepSolid>,
264 /// One per solid, in the same order (default when the file has none).
265 pub appearances: Vec<BodyAppearance>,
266 /// `(index into solids, approximation)` for every body the closure gate
267 /// imported over its bar (`builder/closure.rs`): a typed statement that
268 /// the body's volume is determined only to the bound the approximation
269 /// carries. Empty on a file whose every body closes.
270 pub approximations: Vec<(usize, crate::Approximation)>,
271}
272
273/// [`import_step`] plus the file's PRESENTATION colours: one
274/// [`BodyAppearance`] per returned solid, in the same order.
275///
276/// This is the lane the IMPORT3D feature uses, because colour is stamped as
277/// scene metadata on the names IT chooses — see
278/// `feature_pipeline::features::import3d` and `io/appearance.rs` for the record
279/// shape. A file with no presentation entities returns default (empty)
280/// appearances, never a short vector, so callers can `zip` unconditionally.
281pub fn import_step_with_appearance(
282 text: &str,
283) -> Result<(Vec<BrepSolid>, Vec<BodyAppearance>), String> {
284 import_step_bodies(text)
285 .map(|imported| (imported.solids, imported.appearances))
286 .map_err(|error| error.to_string())
287}
288
289/// What [`import_step_report`] returns: the bodies, how gracefully the file
290/// imported, and the import's diagnostics.
291#[derive(Clone, Debug)]
292pub struct StepImportReport {
293 /// One solid per body that reconstructed, in file order.
294 pub solids: Vec<BrepSolid>,
295 /// The file's presentation colours, one per solid in the same order
296 /// (default where the file styles nothing), as
297 /// [`import_step_with_appearance`] returns them.
298 pub appearances: Vec<BodyAppearance>,
299 /// Things that did not come in (skipped, not fatal): a body that failed to
300 /// reconstruct, an occurrence whose transform failed, or a mapping that was
301 /// refused (`mapped::StepMappedItemError`).
302 pub failed: usize,
303 /// The first such failure's text, when `failed > 0`.
304 pub first_error: Option<String>,
305 /// The bodies the shell-closure gate refused, typed
306 /// (`RefusalClass::UnsoundResult { defect: SoundnessDefect::VectorArea }`),
307 /// in file order. Each is counted in `failed`. [`import_step`] and the
308 /// feature lane refuse the whole file on any of these; this lane returns
309 /// the bodies that did import beside them.
310 pub refused: Vec<crate::KernelRefusal>,
311 /// The bodies that FAILED to build with a typed cause that is not the
312 /// closure gate's, in file order: the pinched-vertex split, a
313 /// `BREP_WITH_VOIDS` certification, the post-build validation
314 /// (2026-10-03). Each is counted in `failed`, and the first is
315 /// `first_error`'s text; none refuses the whole file on any lane, which
316 /// is the outcome their text had.
317 pub failed_refusals: Vec<crate::KernelRefusal>,
318 /// Open surface-model sheets skipped (not solids, so not in `failed`);
319 /// also the counter `SHEETS_SKIPPED` in `diagnostics`.
320 pub sheets_skipped: usize,
321 /// `(index into solids, approximation)` for every imported body whose
322 /// shell closes over its bar (`import.shell_closure`); see
323 /// [`ImportedStep::approximations`].
324 pub approximations: Vec<(usize, crate::Approximation)>,
325 /// Every precision the file states, in millimetres, ascending — see
326 /// `parse::stated_precisions_mm`. Empty when it states none.
327 pub stated_precisions_mm: Vec<f64>,
328 /// The import's diagnostics: measurements always, plus one
329 /// `import.stated_precision_inconsistent` warning when the file's stated
330 /// precision is far under the deviation its own geometry shows
331 /// (`precision::stated_precision_diagnostics`). Informational only —
332 /// acceptance never depends on it.
333 pub diagnostics: crate::KernelDiagnostics,
334}
335
336/// The event code for a body that carries a derived trim off the fit bar (the
337/// 1e-7 floor plus its stations' standoff) after the refit at the floor, which
338/// the importer accepts as it did every fit before the bar, and the counters
339/// and measure beside it. The residual
340/// is the band `EntityTolerances` measures for that edge; the event names how
341/// many are the file's residual and how many the fitter's miss, and the worst
342/// with its numbers, so what the importer accepted before the bar silently is
343/// visible (2026-09-26). Since 2026-10-03 both numbers are read BETWEEN the
344/// fit's stations too (`geometry::trim_floor_reading`) and the class is the
345/// corrected bar's: a trim within the floor of the file curve's standoff is
346/// the file's residual whatever its image does along the carrier.
347pub const TRIM_BOUNDED: &str = "import.trim_bounded";
348pub const TRIMS_BOUNDED: &str = "import.trims_bounded";
349pub const TRIMS_FITTER_MISS: &str = "import.trims_fitter_miss";
350pub const TRIM_BOUND_MM: &str = "import.trim_bound_mm";
351/// Bounded trims whose fit was CLAMPED into the carrier's chart, and the worst
352/// 3D distance that clamp corresponds to (2026-09-30; a report, not a bar).
353pub const TRIMS_CLAMPED: &str = "import.trims_clamped";
354pub const TRIM_CLAMP_MM: &str = "import.trim_clamp_mm";
355
356/// The shell-closure gate's readings on the bodies it ACCEPTED
357/// (`builder/closure.rs`): the worst residual-to-bar ratio over the accepted
358/// bodies, how many bodies the scan could not judge (span budget or an
359/// unreadable face — accepted unjudged, one Degraded event each), and how
360/// many bodies it refused (also in [`StepImportReport::refused`]).
361pub const CLOSURE_RATIO_MAX: &str = "import.closure_ratio_max";
362pub const CLOSURE_APPROXIMATE: &str = "import.closure_approximate";
363pub const CLOSURE_UNJUDGED: &str = "import.closure_unjudged";
364pub const CLOSURE_REFUSED: &str = "import.closure_refused";
365
366/// Open `SHELL_BASED_SURFACE_MODEL` sheets the importer SKIPPED, counted
367/// where it drops them (the flat lane, the occurrence lane once per part, and
368/// [`import_step_assembly`] once per product body). A sheet is not a solid,
369/// so it is neither `failed` nor `refused`; before 2026-10-12 it vanished
370/// uncounted (table 3: ten in `BIMExample-Site.step`).
371pub const SHEETS_SKIPPED: &str = "import.sheets_skipped";
372
373fn closure_diagnostics(
374 notes: &[builder::ClosureNote],
375 refused: &[crate::KernelRefusal],
376 diagnostics: &mut crate::KernelDiagnostics,
377) {
378 for (index, note) in notes.iter().enumerate() {
379 match note {
380 builder::ClosureNote::Closed { residual, bar } => {
381 diagnostics.measure_max(CLOSURE_RATIO_MAX, residual / bar);
382 }
383 builder::ClosureNote::Approximate(approximation) => {
384 diagnostics.measure_max(CLOSURE_RATIO_MAX, approximation.measured / approximation.bar);
385 diagnostics.count(CLOSURE_APPROXIMATE);
386 diagnostics.event(
387 crate::DiagnosticSeverity::Degraded,
388 crate::KernelStage::Validate,
389 CLOSURE_APPROXIMATE,
390 format!("body {index}: {}", approximation.message),
391 );
392 }
393 builder::ClosureNote::Unmeasured { reason, spans } => {
394 diagnostics.count(CLOSURE_UNJUDGED);
395 diagnostics.event(
396 crate::DiagnosticSeverity::Degraded,
397 crate::KernelStage::Validate,
398 CLOSURE_UNJUDGED,
399 format!("body {index}: shell closure not judged — {reason} ({spans} spans); the body is accepted unjudged, not certified closed."),
400 );
401 }
402 builder::ClosureNote::Unreadable { first, count } => {
403 diagnostics.count(CLOSURE_UNJUDGED);
404 diagnostics.event(
405 crate::DiagnosticSeverity::Degraded,
406 crate::KernelStage::Validate,
407 CLOSURE_UNJUDGED,
408 format!("body {index}: shell closure not judged — {count} face(s) unreadable by the scan, first: {first}; the body is accepted unjudged, not certified closed."),
409 );
410 }
411 builder::ClosureNote::Unjudged => {
412 diagnostics.count(CLOSURE_UNJUDGED);
413 }
414 builder::ClosureNote::Overridden(refusal) => {
415 diagnostics.count(CLOSURE_UNJUDGED);
416 diagnostics.event(
417 crate::DiagnosticSeverity::Degraded,
418 crate::KernelStage::Validate,
419 CLOSURE_UNJUDGED,
420 format!("body {index}: the closure guard is OFF (BREP_IMPORT_CLOSURE_GUARD=0); it would have refused: {}", refusal.message),
421 );
422 }
423 }
424 }
425 diagnostics.count_n(CLOSURE_REFUSED, refused.len() as u64);
426}
427
428fn bounded_trim_diagnostics(
429 bounded: &[Vec<builder::readings::BoundedTrim>],
430 diagnostics: &mut crate::KernelDiagnostics,
431) {
432 for (index, trims) in bounded.iter().enumerate() {
433 let Some(worst) = trims
434 .iter()
435 .max_by(|a, b| a.residual.partial_cmp(&b.residual).unwrap_or(std::cmp::Ordering::Equal))
436 else {
437 continue;
438 };
439 let fitters = trims.iter().filter(|trim| trim.fitter).count();
440 let clamped = trims.iter().filter(|trim| trim.clamped_excursion > 0.0).count();
441 let worst_clamp = trims.iter().map(|trim| trim.clamped_distance).fold(0.0f64, f64::max);
442 diagnostics.count_n(TRIMS_BOUNDED, trims.len() as u64);
443 diagnostics.count_n(TRIMS_FITTER_MISS, fitters as u64);
444 diagnostics.measure_max(TRIM_BOUND_MM, worst.residual);
445 diagnostics.count_n(TRIMS_CLAMPED, clamped as u64);
446 diagnostics.measure_max(TRIM_CLAMP_MM, worst_clamp);
447 diagnostics.event(
448 crate::DiagnosticSeverity::Degraded,
449 crate::KernelStage::Collect,
450 TRIM_BOUNDED,
451 format!(
452 "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).{}",
453 trims.len(),
454 crate::PCURVE_REFINEMENT_TOLERANCE,
455 trims.len() - fitters,
456 fitters,
457 worst.face_ref,
458 worst.surface_ref,
459 worst.edge_id,
460 worst.residual,
461 worst.standoff,
462 worst.image_to_foot,
463 if worst.fitter { "the fitter's miss" } else { "the file's residual" },
464 worst.exit,
465 worst.samples,
466 if clamped > 0 {
467 format!(" {clamped} of them were clamped into their chart, by up to {worst_clamp:.3e} mm.")
468 } else {
469 String::new()
470 }
471 ),
472 );
473 }
474}
475
476/// Like [`import_step`] but reports how many bodies failed and the first error,
477/// so callers can distinguish a fully- from a partially-imported assembly —
478/// and runs the stated-precision consistency check over the imported bodies,
479/// whose result rides in [`StepImportReport::diagnostics`].
480///
481/// The check measures every edge and vertex of every body (the same
482/// `EntityTolerances` reading the per-entity-tolerance census took), which is
483/// why it lives on this lane and not on [`import_step_with_appearance`]: the
484/// feature pipeline has no diagnostics channel to carry the answer, and a
485/// measurement nobody reads is not worth its cost on every IMPORT3D.
486pub fn import_step_report(text: &str) -> Result<StepImportReport, String> {
487 import_step_report_with(text, false, true)
488}
489
490/// [`import_step_report`] building every OPEN_SHELL as a sheet body
491/// (`BodyKind::Sheet`) among its solids, not skipping it: the Parasolid
492/// lane's, whose translation writes a sheet body as an open shell.
493pub(crate) fn import_step_report_with_sheets(text: &str) -> Result<StepImportReport, String> {
494 import_step_report_with(text, true, true)
495}
496
497/// The faces of a STEP file sewn into one solid where their edges lie within
498/// `tolerance` (mm) of each other: every body the file holds, an open shell or a
499/// face set read as a sheet, joined and sewn by [`crate::solid_from_sheets`].
500/// Refuses a file with nothing to sew, a body that did not reconstruct, and
501/// sheets that leave an edge open (saying how many) or do not close a valid
502/// solid.
503pub fn sew_step(text: &str, tolerance: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
504 use crate::{KernelRefusal, KernelStage};
505 if !(tolerance.is_finite() && tolerance > 0.0) {
506 return Err(KernelRefusal::input(KernelStage::Collect, "sew_step_tolerance", format!("sew_step: tolerance {tolerance} must be positive")));
507 }
508 let report = import_step_report_with_sheets(text).map_err(|e| KernelRefusal::input(KernelStage::Collect, "sew_step_read", format!("sew_step: {e}")))?;
509 if report.failed > 0 {
510 return Err(KernelRefusal::input(
511 KernelStage::Collect,
512 "sew_step_body",
513 format!("sew_step: {} bodies did not reconstruct: {}", report.failed, report.first_error.unwrap_or_default()),
514 ));
515 }
516 if report.solids.is_empty() {
517 return Err(KernelRefusal::input(KernelStage::Collect, "sew_step_empty", "sew_step: the file holds no faces".to_string()));
518 }
519 crate::solid_from_sheets(&report.solids, tolerance)
520}
521
522/// [`import_step_report`] (with `sheets` as [`import_step_report_with_sheets`])
523/// for a caller that drops the report's trim-reading diagnostics: under
524/// `BREP_IMPORT_LEAN` the build skips them.
525pub(crate) fn import_step_report_dropping_readings(text: &str, sheets: bool) -> Result<StepImportReport, String> {
526 import_step_report_with(text, sheets, !bodies::import_lean())
527}
528
529/// Every `EDGE_BASED_WIREFRAME_MODEL` of a Part 21 document, in file order,
530/// as wire bodies (`BodyKind::Wire`, plan 3.3): the Parasolid lane's, whose
531/// translation writes a wire body as one. Ordinary STEP import does not read
532/// wireframes yet.
533pub(crate) fn import_step_wires(text: &str) -> Result<Vec<BrepSolid>, String> {
534 let entities = parse_data_section(text)?;
535 let resolver = Resolver::new(&entities, derive_length_scale_mm(&entities));
536 let mut models: Vec<usize> =
537 entities.iter().filter(|(_, e)| e.has("EDGE_BASED_WIREFRAME_MODEL")).map(|(&id, _)| id).collect();
538 models.sort_unstable();
539 models.into_iter().map(|id| build_wire(&resolver, id)).collect()
540}
541
542fn import_step_report_with(text: &str, sheets: bool, readings: bool) -> Result<StepImportReport, String> {
543 let imported = bodies::collect_step_solids_with(text, sheets, readings)?;
544 let mut diagnostics =
545 precision::stated_precision_diagnostics(&imported.stated_precisions_mm, &imported.solids);
546 bounded_trim_diagnostics(&imported.bounded_trims, &mut diagnostics);
547 closure_diagnostics(&imported.closure_notes, &imported.refused_bodies, &mut diagnostics);
548 diagnostics.count_n(SHEETS_SKIPPED, imported.sheets_skipped as u64);
549 if let Some(band) = imported.unstated_identity_band_mm {
550 diagnostics.measure_max(precision::UNSTATED_IDENTITY_BAND_MM, band);
551 }
552 Ok(StepImportReport {
553 solids: imported.solids,
554 appearances: imported.appearances,
555 failed: imported.failed,
556 first_error: imported.first_error,
557 refused: imported.refused_bodies,
558 failed_refusals: imported.failed_refusals,
559 sheets_skipped: imported.sheets_skipped,
560 approximations: imported
561 .closure_notes
562 .iter()
563 .enumerate()
564 .filter_map(|(index, note)| note.approximation().map(|a| (index, a.clone())))
565 .collect(),
566 stated_precisions_mm: imported.stated_precisions_mm,
567 diagnostics,
568 })
569}