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, true)
50}
51
52pub fn import_parasolid_bodies(text: &str) -> Result<ParasolidImportReport, String> {
56 let file = parse_xt_text(text).map_err(|e| format!("parasolid_import: {e}"))?;
57 import_file(&file, false)
58}
59
60pub fn import_parasolid_bytes_bodies(bytes: &[u8]) -> Result<ParasolidImportReport, String> {
63 let file = parse_xt(bytes).map_err(|e| format!("parasolid_import: {e}"))?;
64 import_file(&file, false)
65}
66
67pub fn import_parasolid_bytes_report(bytes: &[u8]) -> Result<ParasolidImportReport, String> {
70 let file = parse_xt(bytes).map_err(|e| format!("parasolid_import: {e}"))?;
71 import_file(&file, true)
72}
73
74fn import_file(file: &XtFile, readings: bool) -> Result<ParasolidImportReport, String> {
77 let bodies = bodies(file).map_err(|e| format!("parasolid_import: {e}"))?;
78 let mut report = ParasolidImportReport {
79 solids: Vec::new(),
80 names: Vec::new(),
81 appearances: Vec::new(),
82 application: file.header_value("APPL").map(str::to_string),
83 modeller_version: file.modeller_version.trim_start_matches(':').trim().to_string(),
84 stated_resolution_mm: bodies
85 .first()
86 .and_then(|b| b.body.real("res_linear"))
87 .map(|r| r * MM_PER_METRE)
88 .filter(|r| *r > 0.0),
89 fitted_curves: 0,
90 unverified_curves: 0,
91 diagnostics: KernelDiagnostics::default(),
92 };
93 struct Imported {
96 solids: Vec<BrepSolid>,
97 appearances: Vec<Vec<Option<crate::ImportedColor>>>,
98 name: Option<String>,
99 color: Option<crate::ImportedColor>,
100 }
101 let mut imported: rustc_hash::FxHashMap<u32, Imported> = rustc_hash::FxHashMap::default();
102 let distinct = {
103 let mut seen = rustc_hash::FxHashSet::default();
104 bodies.iter().filter(|p| seen.insert(p.body.index)).count()
105 };
106 let mut occurrences: rustc_hash::FxHashMap<u32, usize> = rustc_hash::FxHashMap::default();
107 for p in &bodies {
108 *occurrences.entry(p.body.index).or_default() += 1;
109 }
110 let mut ordinal = 0;
111 let mut seen_count: rustc_hash::FxHashMap<u32, usize> = rustc_hash::FxHashMap::default();
112 for Placed { body, at } in &bodies {
113 let body = *body;
114 if !imported.contains_key(&body.index) {
115 ordinal += 1;
116 let what = || match distinct {
117 1 => "the body".to_string(),
118 _ => format!("body {ordinal}"),
119 };
120 let translated = body_to_step(file, body, ordinal - 1).map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
121 if body.int("body_type") == Some(2) {
122 let wires = crate::step_import::import_step_wires(&translated.step)
124 .map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
125 if wires.is_empty() {
126 return Err(format!("parasolid_import: {}: the wire body produced no wire", what()));
127 }
128 report.fitted_curves += translated.fitted_curves;
129 report.unverified_curves += translated.unverified_curves;
130 let appearances = vec![Vec::new(); wires.len()];
131 imported.insert(body.index, Imported { solids: wires, appearances, name: translated.name, color: translated.color });
132 } else {
133 let sheet = body.int("body_type") == Some(3);
136 let step = if !readings {
137 crate::step_import::import_step_report_dropping_readings(&translated.step, sheet)
138 } else if sheet {
139 crate::step_import::import_step_report_with_sheets(&translated.step)
140 } else {
141 crate::import_step_report(&translated.step)
142 }
143 .map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
144 if step.failed > 0 {
145 return Err(format!(
146 "parasolid_import: {}: {}",
147 what(),
148 step.first_error.as_deref().unwrap_or("the body did not import")
149 ));
150 }
151 if step.sheets_skipped > 0 && !step.solids.is_empty() {
152 return Err(format!(
154 "parasolid_import: {}: {} of its shells are open sheets, which do not bound a solid",
155 what(),
156 step.sheets_skipped
157 ));
158 }
159 if step.solids.is_empty() {
160 return Err(format!("parasolid_import: {}: the body produced no solid", what()));
161 }
162 report.fitted_curves += translated.fitted_curves;
163 report.unverified_curves += translated.unverified_curves;
164 merge_diagnostics(&mut report.diagnostics, step.diagnostics);
165 let appearances = (0..step.solids.len()).map(|j| step.appearances.get(j).map(|a| a.faces.clone()).unwrap_or_default()).collect();
166 imported.insert(body.index, Imported { solids: step.solids, appearances, name: translated.name, color: translated.color });
167 }
168 }
169 let entry = &imported[&body.index];
170 let count = entry.solids.len() * occurrences[&body.index];
171 let k = seen_count.entry(body.index).or_default();
172 for (j, solid) in entry.solids.iter().enumerate() {
173 let solid = match at {
174 None => solid.clone(),
175 Some(matrix) => {
176 let transform = crate::AffineTransform::new(*matrix)
177 .map_err(|e| format!("parasolid_import: placing an instance: {e}"))?;
178 crate::transform_brep(solid, transform, transform.determinant3() < 0.0)
179 .map_err(|e| format!("parasolid_import: placing an instance: {e}"))?
180 }
181 };
182 report.appearances.push(BodyAppearance { body: entry.color, faces: entry.appearances[j].clone() });
183 *k += 1;
184 let name = match (&entry.name, count) {
185 (Some(name), 1) => name.clone(),
186 (Some(name), _) => format!("{name} ({k})"),
187 (None, _) => String::new(),
188 };
189 report.names.push(name);
190 report.solids.push(solid);
191 }
192 }
193 Ok(report)
194}
195
196struct Placed<'f> {
199 body: &'f Node,
200 at: Option<crate::Mat4>,
201}
202
203fn bodies(file: &XtFile) -> Result<Vec<Placed<'_>>, String> {
208 let root = file.root().ok_or("the file holds no nodes")?;
209 let parts: Vec<&Node> = match root.type_name() {
210 "BODY" | "ASSEMBLY" => vec![root],
211 "WORLD" => {
212 if root.ptr("assembly") != 0 {
216 return Err("the partition holds an assembly, which is not read yet".into());
217 }
218 let mut chain = Vec::new();
219 let mut next = file.follow(root, "body");
220 while let Some(body) = next {
221 if chain.len() >= file.nodes().len() || chain.iter().any(|b: &&Node| b.index == body.index) {
222 return Err("the partition's chain of bodies loops".into());
223 }
224 chain.push(body);
225 next = file.follow(body, "next");
226 }
227 chain
228 }
229 "PART_XMT_BLOCK" | "POINTER_LIS_BLOCK" => root
230 .ints("entries")
231 .into_iter()
232 .filter_map(|i| u32::try_from(i).ok())
233 .filter_map(|i| file.node(i))
234 .collect(),
235 other => return Err(format!("the file's root is a {other}, not a body")),
236 };
237 let mut out: Vec<Placed> = Vec::new();
238 for part in parts {
239 match part.type_name() {
240 "BODY" => out.push(Placed { body: part, at: None }),
241 "ASSEMBLY" => {
242 let mut placed = Vec::new();
243 place_instances(file, part, crate::step_matrix::MAT4_IDENTITY, 0, &mut placed)?;
244 out.extend(placed.into_iter().map(|(body, matrix)| Placed { body, at: Some(matrix) }));
245 }
246 other => return Err(format!("the file holds a {other} where a part should be")),
247 }
248 }
249 let unplaced: rustc_hash::FxHashSet<u32> = out.iter().filter(|p| p.at.is_none()).map(|p| p.body.index).collect();
252 if out.iter().any(|p| p.at.is_some() && unplaced.contains(&p.body.index)) {
253 return Err("the file lists a body both on its own and in an assembly, which is not read yet".into());
254 }
255 if out.is_empty() {
256 return Err("the file holds no bodies".into());
257 }
258 Ok(out)
259}
260
261fn place_instances<'f>(
266 file: &'f XtFile,
267 assembly: &'f Node,
268 parent: crate::Mat4,
269 depth: usize,
270 out: &mut Vec<(&'f Node, crate::Mat4)>,
271) -> Result<(), String> {
272 if depth > 64 {
273 return Err("the assembly nests more than 64 deep".into());
274 }
275 let mut seen = 0usize;
276 let mut next = file.follow(assembly, "sub_instance");
277 while let Some(instance) = next {
278 seen += 1;
279 if seen > file.nodes().len() {
280 return Err("an assembly's chain of instances loops".into());
281 }
282 if instance.int("type") == Some(2) {
283 return Err("the assembly holds a negative instance, which is not read yet".into());
284 }
285 let local = match file.follow(instance, "transform") {
286 None => crate::step_matrix::MAT4_IDENTITY,
287 Some(transform) => transform_matrix(file, transform)?,
288 };
289 let matrix = crate::step_matrix::mat4_mul(&parent, &local);
290 let part = file.follow(instance, "part").ok_or("an instance has no part")?;
291 match part.type_name() {
292 "BODY" => out.push((part, matrix)),
293 "ASSEMBLY" => place_instances(file, part, matrix, depth + 1, out)?,
294 other => return Err(format!("an instance places a {other}, not a body or an assembly")),
295 }
296 next = file.follow(instance, "next_in_part");
297 }
298 Ok(())
299}
300
301fn transform_matrix(file: &XtFile, node: &Node) -> Result<crate::Mat4, String> {
304 let mut r = node.reals("rotation_matrix");
305 let mut t = node.vector("translation_vector").unwrap_or([0.0; 3]);
306 if r.len() != 9 || r.iter().any(|x| !x.is_finite()) {
307 return Err("a transform has no rotation matrix".into());
308 }
309 if let Some(precision) = file.follow(node, "precision") {
310 let dr = precision.reals("rotation_matrix");
311 if dr.len() == 9 && dr.iter().all(|x| x.is_finite()) {
312 for (v, d) in r.iter_mut().zip(&dr) {
313 *v += d;
314 }
315 }
316 if let Some(dt) = precision.vector("translation_vector") {
317 for (v, d) in t.iter_mut().zip(dt) {
318 *v += d;
319 }
320 }
321 }
322 if node.vector("perspective_vector").is_some_and(|p| p.iter().any(|x| *x != 0.0)) {
323 return Err("an instance's transform has a perspective part, which is not read".into());
324 }
325 let s = node.real("scale").unwrap_or(1.0);
326 if !(s.is_finite() && s != 0.0) {
327 return Err(format!("a transform has scale {s}"));
328 }
329 if s.abs().powi(3) <= 1e-14 {
332 return Err(format!("an instance scales its part by {s}, below what the kernel can place (1e-14 in volume)"));
333 }
334 for v in &mut r {
335 *v *= s;
336 }
337 for v in &mut t {
338 *v *= s * MM_PER_METRE;
339 }
340 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])
341}
342
343fn merge_diagnostics(into: &mut KernelDiagnostics, from: KernelDiagnostics) {
344 into.events.extend(from.events);
345 for (key, count) in from.counters {
346 *into.counters.entry(key).or_insert(0) += count;
347 }
348 for (key, value) in from.measurements {
349 let slot = into.measurements.entry(key).or_insert(value);
350 if value > *slot {
351 *slot = value;
352 }
353 }
354}