brep_kernel/io/parasolid/
import.rs1use crate::topology::BrepSolid;
8use crate::{BodyAppearance, KernelDiagnostics};
9
10use super::reader::{parse_xt, parse_xt_text, Node, XtFile};
11use super::geometry::MM_PER_METRE;
12use super::to_step::body_to_step;
13
14#[derive(Clone, Debug)]
16pub struct ParasolidImportReport {
17 pub solids: Vec<BrepSolid>,
19 pub names: Vec<String>,
22 pub appearances: Vec<BodyAppearance>,
24 pub application: Option<String>,
26 pub modeller_version: String,
27 pub stated_resolution_mm: Option<f64>,
29 pub fitted_curves: usize,
32 pub unverified_curves: usize,
37 pub diagnostics: KernelDiagnostics,
39}
40
41pub fn import_parasolid(text: &str) -> Result<Vec<BrepSolid>, String> {
43 Ok(import_parasolid_report(text)?.solids)
44}
45
46pub fn import_parasolid_report(text: &str) -> Result<ParasolidImportReport, String> {
48 let file = parse_xt_text(text).map_err(|e| format!("parasolid_import: {e}"))?;
49 import_file(&file)
50}
51
52pub fn import_parasolid_bytes_report(bytes: &[u8]) -> Result<ParasolidImportReport, String> {
55 let file = parse_xt(bytes).map_err(|e| format!("parasolid_import: {e}"))?;
56 import_file(&file)
57}
58
59fn import_file(file: &XtFile) -> Result<ParasolidImportReport, String> {
60 let bodies = bodies(file).map_err(|e| format!("parasolid_import: {e}"))?;
61 let mut report = ParasolidImportReport {
62 solids: Vec::new(),
63 names: Vec::new(),
64 appearances: Vec::new(),
65 application: file.header_value("APPL").map(str::to_string),
66 modeller_version: file.modeller_version.trim_start_matches(':').trim().to_string(),
67 stated_resolution_mm: bodies
68 .first()
69 .and_then(|b| b.body.real("res_linear"))
70 .map(|r| r * MM_PER_METRE)
71 .filter(|r| *r > 0.0),
72 fitted_curves: 0,
73 unverified_curves: 0,
74 diagnostics: KernelDiagnostics::default(),
75 };
76 struct Imported {
79 solids: Vec<BrepSolid>,
80 appearances: Vec<Vec<Option<crate::ImportedColor>>>,
81 name: Option<String>,
82 color: Option<crate::ImportedColor>,
83 }
84 let mut imported: rustc_hash::FxHashMap<u32, Imported> = rustc_hash::FxHashMap::default();
85 let distinct = {
86 let mut seen = rustc_hash::FxHashSet::default();
87 bodies.iter().filter(|p| seen.insert(p.body.index)).count()
88 };
89 let mut occurrences: rustc_hash::FxHashMap<u32, usize> = rustc_hash::FxHashMap::default();
90 for p in &bodies {
91 *occurrences.entry(p.body.index).or_default() += 1;
92 }
93 let mut ordinal = 0;
94 let mut seen_count: rustc_hash::FxHashMap<u32, usize> = rustc_hash::FxHashMap::default();
95 for Placed { body, at } in &bodies {
96 let body = *body;
97 if !imported.contains_key(&body.index) {
98 ordinal += 1;
99 let what = || match distinct {
100 1 => "the body".to_string(),
101 _ => format!("body {ordinal}"),
102 };
103 let translated = body_to_step(file, body, ordinal - 1).map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
104 let sheet = body.int("body_type") == Some(3);
107 let step = if sheet {
108 crate::step_import::import_step_report_with_sheets(&translated.step)
109 } else {
110 crate::import_step_report(&translated.step)
111 }
112 .map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
113 if step.failed > 0 {
114 return Err(format!(
115 "parasolid_import: {}: {}",
116 what(),
117 step.first_error.as_deref().unwrap_or("the body did not import")
118 ));
119 }
120 if step.sheets_skipped > 0 && !step.solids.is_empty() {
121 return Err(format!(
123 "parasolid_import: {}: {} of its shells are open sheets, which do not bound a solid",
124 what(),
125 step.sheets_skipped
126 ));
127 }
128 if step.solids.is_empty() {
129 return Err(format!("parasolid_import: {}: the body produced no solid", what()));
130 }
131 report.fitted_curves += translated.fitted_curves;
132 report.unverified_curves += translated.unverified_curves;
133 merge_diagnostics(&mut report.diagnostics, step.diagnostics);
134 let appearances = (0..step.solids.len()).map(|j| step.appearances.get(j).map(|a| a.faces.clone()).unwrap_or_default()).collect();
135 imported.insert(body.index, Imported { solids: step.solids, appearances, name: translated.name, color: translated.color });
136 }
137 let entry = &imported[&body.index];
138 let count = entry.solids.len() * occurrences[&body.index];
139 let k = seen_count.entry(body.index).or_default();
140 for (j, solid) in entry.solids.iter().enumerate() {
141 let solid = match at {
142 None => solid.clone(),
143 Some(matrix) => {
144 let transform = crate::AffineTransform::new(*matrix)
145 .map_err(|e| format!("parasolid_import: placing an instance: {e}"))?;
146 crate::transform_brep(solid, transform, transform.determinant3() < 0.0)
147 .map_err(|e| format!("parasolid_import: placing an instance: {e}"))?
148 }
149 };
150 report.appearances.push(BodyAppearance { body: entry.color, faces: entry.appearances[j].clone() });
151 *k += 1;
152 let name = match (&entry.name, count) {
153 (Some(name), 1) => name.clone(),
154 (Some(name), _) => format!("{name} ({k})"),
155 (None, _) => String::new(),
156 };
157 report.names.push(name);
158 report.solids.push(solid);
159 }
160 }
161 Ok(report)
162}
163
164struct Placed<'f> {
167 body: &'f Node,
168 at: Option<crate::Mat4>,
169}
170
171fn bodies(file: &XtFile) -> Result<Vec<Placed<'_>>, String> {
176 let root = file.root().ok_or("the file holds no nodes")?;
177 let parts: Vec<&Node> = match root.type_name() {
178 "BODY" | "ASSEMBLY" => vec![root],
179 "WORLD" => {
180 if root.ptr("assembly") != 0 {
184 return Err("the partition holds an assembly, which is not read yet".into());
185 }
186 let mut chain = Vec::new();
187 let mut next = file.follow(root, "body");
188 while let Some(body) = next {
189 if chain.len() >= file.nodes().len() || chain.iter().any(|b: &&Node| b.index == body.index) {
190 return Err("the partition's chain of bodies loops".into());
191 }
192 chain.push(body);
193 next = file.follow(body, "next");
194 }
195 chain
196 }
197 "PART_XMT_BLOCK" | "POINTER_LIS_BLOCK" => root
198 .ints("entries")
199 .into_iter()
200 .filter_map(|i| u32::try_from(i).ok())
201 .filter_map(|i| file.node(i))
202 .collect(),
203 other => return Err(format!("the file's root is a {other}, not a body")),
204 };
205 let mut out: Vec<Placed> = Vec::new();
206 for part in parts {
207 match part.type_name() {
208 "BODY" => out.push(Placed { body: part, at: None }),
209 "ASSEMBLY" => {
210 let mut placed = Vec::new();
211 place_instances(file, part, crate::step_matrix::MAT4_IDENTITY, 0, &mut placed)?;
212 out.extend(placed.into_iter().map(|(body, matrix)| Placed { body, at: Some(matrix) }));
213 }
214 other => return Err(format!("the file holds a {other} where a part should be")),
215 }
216 }
217 let unplaced: rustc_hash::FxHashSet<u32> = out.iter().filter(|p| p.at.is_none()).map(|p| p.body.index).collect();
220 if out.iter().any(|p| p.at.is_some() && unplaced.contains(&p.body.index)) {
221 return Err("the file lists a body both on its own and in an assembly, which is not read yet".into());
222 }
223 if out.is_empty() {
224 return Err("the file holds no bodies".into());
225 }
226 Ok(out)
227}
228
229fn place_instances<'f>(
234 file: &'f XtFile,
235 assembly: &'f Node,
236 parent: crate::Mat4,
237 depth: usize,
238 out: &mut Vec<(&'f Node, crate::Mat4)>,
239) -> Result<(), String> {
240 if depth > 64 {
241 return Err("the assembly nests more than 64 deep".into());
242 }
243 let mut seen = 0usize;
244 let mut next = file.follow(assembly, "sub_instance");
245 while let Some(instance) = next {
246 seen += 1;
247 if seen > file.nodes().len() {
248 return Err("an assembly's chain of instances loops".into());
249 }
250 if instance.int("type") == Some(2) {
251 return Err("the assembly holds a negative instance, which is not read yet".into());
252 }
253 let local = match file.follow(instance, "transform") {
254 None => crate::step_matrix::MAT4_IDENTITY,
255 Some(transform) => transform_matrix(file, transform)?,
256 };
257 let matrix = crate::step_matrix::mat4_mul(&parent, &local);
258 let part = file.follow(instance, "part").ok_or("an instance has no part")?;
259 match part.type_name() {
260 "BODY" => out.push((part, matrix)),
261 "ASSEMBLY" => place_instances(file, part, matrix, depth + 1, out)?,
262 other => return Err(format!("an instance places a {other}, not a body or an assembly")),
263 }
264 next = file.follow(instance, "next_in_part");
265 }
266 Ok(())
267}
268
269fn transform_matrix(file: &XtFile, node: &Node) -> Result<crate::Mat4, String> {
272 let mut r = node.reals("rotation_matrix");
273 let mut t = node.vector("translation_vector").unwrap_or([0.0; 3]);
274 if r.len() != 9 || r.iter().any(|x| !x.is_finite()) {
275 return Err("a transform has no rotation matrix".into());
276 }
277 if let Some(precision) = file.follow(node, "precision") {
278 let dr = precision.reals("rotation_matrix");
279 if dr.len() == 9 && dr.iter().all(|x| x.is_finite()) {
280 for (v, d) in r.iter_mut().zip(&dr) {
281 *v += d;
282 }
283 }
284 if let Some(dt) = precision.vector("translation_vector") {
285 for (v, d) in t.iter_mut().zip(dt) {
286 *v += d;
287 }
288 }
289 }
290 if node.vector("perspective_vector").is_some_and(|p| p.iter().any(|x| *x != 0.0)) {
291 return Err("an instance's transform has a perspective part, which is not read".into());
292 }
293 let s = node.real("scale").unwrap_or(1.0);
294 if !(s.is_finite() && s != 0.0) {
295 return Err(format!("a transform has scale {s}"));
296 }
297 if s.abs().powi(3) <= 1e-14 {
300 return Err(format!("an instance scales its part by {s}, below what the kernel can place (1e-14 in volume)"));
301 }
302 for v in &mut r {
303 *v *= s;
304 }
305 for v in &mut t {
306 *v *= s * MM_PER_METRE;
307 }
308 Ok([r[0], r[1], r[2], t[0], r[3], r[4], r[5], t[1], r[6], r[7], r[8], t[2], 0.0, 0.0, 0.0, 1.0])
309}
310
311fn merge_diagnostics(into: &mut KernelDiagnostics, from: KernelDiagnostics) {
312 into.events.extend(from.events);
313 for (key, count) in from.counters {
314 *into.counters.entry(key).or_insert(0) += count;
315 }
316 for (key, value) in from.measurements {
317 let slot = into.measurements.entry(key).or_insert(value);
318 if value > *slot {
319 *slot = value;
320 }
321 }
322}