Skip to main content

brep_kernel/io/parasolid/
import.rs

1//! Parasolid part to kernel `BrepSolid`s, by way of the STEP importer.
2//!
3//! Each body is translated to Part 21 ([`super::to_step`]) and imported
4//! there, so it gets the STEP builder, closure gate and refusals. A body that
5//! cannot be read correctly is refused by name; a file never imports short.
6
7use crate::topology::BrepSolid;
8use crate::{BodyAppearance, KernelDiagnostics};
9
10use super::reader::{parse_xt_text, Node, XtFile};
11use super::geometry::MM_PER_METRE;
12use super::to_step::body_to_step;
13
14/// What [`import_parasolid_report`] returns.
15#[derive(Clone, Debug)]
16pub struct ParasolidImportReport {
17    /// The solids, in file order.
18    pub solids: Vec<BrepSolid>,
19    /// Each solid's name (the body's name attribute), parallel to `solids`;
20    /// empty when the file gives none.
21    pub names: Vec<String>,
22    /// Each solid's colours, parallel to `solids`.
23    pub appearances: Vec<BodyAppearance>,
24    /// The writer (`APPL` in the header) and kernel version.
25    pub application: Option<String>,
26    pub modeller_version: String,
27    /// The file's linear resolution in mm (the body's `res_linear`).
28    pub stated_resolution_mm: Option<f64>,
29    /// Edges whose 3D curve was fitted (intersection curves and SP-curves,
30    /// which STEP has no entity for).
31    pub fitted_curves: usize,
32    /// Of those, the intersection curves fitted through their chart alone
33    /// where no point between chart points could be solved (a surface with
34    /// no distance the reader computes, such as a blend boundary, or a
35    /// tangency): their fit is not checked against the true curve.
36    pub unverified_curves: usize,
37    /// Measurements and warnings from the STEP lane, merged over every body.
38    pub diagnostics: KernelDiagnostics,
39}
40
41/// Read a Parasolid text part (`.x_t`, `.xmt_txt`) into solids.
42pub fn import_parasolid(text: &str) -> Result<Vec<BrepSolid>, String> {
43    Ok(import_parasolid_report(text)?.solids)
44}
45
46/// [`import_parasolid`] with names, colours and the import's diagnostics.
47pub fn import_parasolid_report(text: &str) -> Result<ParasolidImportReport, String> {
48    let file = parse_xt_text(text).map_err(|e| format!("parasolid_import: {e}"))?;
49    let bodies = bodies(&file).map_err(|e| format!("parasolid_import: {e}"))?;
50    let mut report = ParasolidImportReport {
51        solids: Vec::new(),
52        names: Vec::new(),
53        appearances: Vec::new(),
54        application: file.header_value("APPL").map(str::to_string),
55        modeller_version: file.modeller_version.trim_start_matches(':').trim().to_string(),
56        stated_resolution_mm: bodies
57            .first()
58            .and_then(|b| b.real("res_linear"))
59            .map(|r| r * MM_PER_METRE)
60            .filter(|r| *r > 0.0),
61        fitted_curves: 0,
62        unverified_curves: 0,
63        diagnostics: KernelDiagnostics::default(),
64    };
65    for (index, body) in bodies.iter().enumerate() {
66        let what = || match bodies.len() {
67            1 => "the body".to_string(),
68            _ => format!("body {}", index + 1),
69        };
70        let translated = body_to_step(&file, body, index).map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
71        let step = crate::import_step_report(&translated.step).map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
72        if step.failed > 0 {
73            return Err(format!(
74                "parasolid_import: {}: {}",
75                what(),
76                step.first_error.as_deref().unwrap_or("the body did not import")
77            ));
78        }
79        if step.sheets_skipped > 0 && !step.solids.is_empty() {
80            // Part of the body did not come in: refuse it whole.
81            return Err(format!(
82                "parasolid_import: {}: {} of its shells are open sheets, which do not bound a solid",
83                what(),
84                step.sheets_skipped
85            ));
86        }
87        if step.solids.is_empty() {
88            return Err(format!(
89                "parasolid_import: {}: {}",
90                what(),
91                if body.int("body_type") == Some(3) {
92                    "the body is an open sheet, which does not bound a solid"
93                } else {
94                    "the body produced no solid"
95                }
96            ));
97        }
98        report.fitted_curves += translated.fitted_curves;
99        report.unverified_curves += translated.unverified_curves;
100        merge_diagnostics(&mut report.diagnostics, step.diagnostics);
101        let count = step.solids.len();
102        for (k, solid) in step.solids.into_iter().enumerate() {
103            let faces = step.appearances.get(k).map(|a| a.faces.clone()).unwrap_or_default();
104            report.appearances.push(BodyAppearance { body: translated.color, faces });
105            let name = match (&translated.name, count) {
106                (Some(name), 1) => name.clone(),
107                (Some(name), _) => format!("{name} ({})", k + 1),
108                (None, _) => String::new(),
109            };
110            report.names.push(name);
111            report.solids.push(solid);
112        }
113    }
114    Ok(report)
115}
116
117/// The bodies a part file holds: its root BODY, or the bodies of a
118/// PART_XMT_BLOCK / POINTER_LIS_BLOCK array of parts (ยง2.1).
119fn bodies(file: &XtFile) -> Result<Vec<&Node>, String> {
120    let root = file.root().ok_or("the file holds no nodes")?;
121    let parts: Vec<&Node> = match root.type_name() {
122        "BODY" => vec![root],
123        "ASSEMBLY" => return Err("the file is an assembly, which is not read yet".into()),
124        "PART_XMT_BLOCK" | "POINTER_LIS_BLOCK" => root
125            .ints("entries")
126            .into_iter()
127            .filter_map(|i| u32::try_from(i).ok())
128            .filter_map(|i| file.node(i))
129            .collect(),
130        other => return Err(format!("the file's root is a {other}, not a body")),
131    };
132    let mut out = Vec::new();
133    for part in parts {
134        match part.type_name() {
135            "BODY" => out.push(part),
136            "ASSEMBLY" => return Err("the file holds an assembly, which is not read yet".into()),
137            other => return Err(format!("the file holds a {other} where a part should be")),
138        }
139    }
140    if out.is_empty() {
141        return Err("the file holds no bodies".into());
142    }
143    Ok(out)
144}
145
146fn merge_diagnostics(into: &mut KernelDiagnostics, from: KernelDiagnostics) {
147    into.events.extend(from.events);
148    for (key, count) in from.counters {
149        *into.counters.entry(key).or_insert(0) += count;
150    }
151    for (key, value) in from.measurements {
152        let slot = into.measurements.entry(key).or_insert(value);
153        if value > *slot {
154            *slot = value;
155        }
156    }
157}