brep_render/engine_state/model_io.rs
1use super::*;
2
3// ===========================================================================
4// Import / export — the file-interchange lane (the ONE platform exception).
5// STEP/IGES are text; STL/OBJ/3MF bytes are submitted to the background runner for
6// RANSAC reconstruction, then return as validated STEP for IMPORT3D. Exports
7// collect the CURRENT model's resident solids and serialize them.
8// ===========================================================================
9impl EngineState {
10 /// Import an STL triangle mesh through topology-aware RANSAC recognition.
11 /// Unsupported regions remain as validated facets, so every repairable
12 /// source triangle reaches the resulting CAD body.
13 pub fn import_stl_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
14 self.submit_mesh_import(crate::runner::MeshImportFormat::Stl, bytes.to_vec())
15 }
16
17 /// Import a Wavefront OBJ mesh through the same RANSAC reconstruction path.
18 pub fn import_obj_feature(&mut self, text: &str) -> Result<String, String> {
19 self.import_obj_bytes_feature(text.as_bytes())
20 }
21
22 /// Byte-oriented OBJ entry used by the picker so decoding also stays on the
23 /// background runner with parsing and reconstruction.
24 pub fn import_obj_bytes_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
25 self.submit_mesh_import(crate::runner::MeshImportFormat::Obj, bytes.to_vec())
26 }
27
28 /// Import a 3MF package (core specification) through the same chain. The
29 /// package is unzipped and its build flattened on the runner, so a large
30 /// model never decompresses on the UI thread.
31 pub fn import_3mf_bytes_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
32 self.submit_mesh_import(crate::runner::MeshImportFormat::ThreeMf, bytes.to_vec())
33 }
34
35 fn submit_mesh_import(
36 &mut self,
37 format: crate::runner::MeshImportFormat,
38 bytes: Vec<u8>,
39 ) -> Result<String, String> {
40 let id = self.submit_mesh_reconstruction(
41 format, bytes, Default::default(), MeshImportDestination::Document,
42 )?;
43 Ok(serde_json::json!({ "meshImport": "submitted", "id": id }).to_string())
44 }
45
46 /// Reconstruct without editing history. The caller owns confirmation and
47 /// can inspect the exact STEP and diagnostics returned by `take_mesh_preview`.
48 pub fn reconstruct_mesh_preview(
49 &mut self,
50 format: crate::runner::MeshImportFormat,
51 bytes: Vec<u8>,
52 options: crate::runner::StlConversionOptions,
53 ) -> Result<u64, String> {
54 self.submit_mesh_reconstruction(format, bytes, options, MeshImportDestination::Preview)
55 }
56
57 pub fn take_mesh_preview(&mut self) -> Option<crate::runner::MeshImportReply> {
58 self.mesh_preview_results.pop_front()
59 }
60
61 fn submit_mesh_reconstruction(
62 &mut self,
63 format: crate::runner::MeshImportFormat,
64 bytes: Vec<u8>,
65 options: crate::runner::StlConversionOptions,
66 destination: MeshImportDestination,
67 ) -> Result<u64, String> {
68 if bytes.is_empty() {
69 return Err("mesh import failed: file is empty".into());
70 }
71 let id = self.next_mesh_import_id;
72 self.next_mesh_import_id = self.next_mesh_import_id.wrapping_add(1);
73 self.pending_mesh_imports.insert(id, destination);
74 self.runner.submit_mesh_import(crate::runner::MeshImportRequest {
75 id, format, bytes, options,
76 });
77 self.pump();
78 Ok(id)
79 }
80
81 /// Import a STEP document into the model: append an `IMPORT3D` feature whose
82 /// `inputParams.stepText` is the raw ISO-10303-21 text (the exact headless
83 /// source the kernel importer reads — no `fileToImport` data-URL marshaling
84 /// needed), mint it a persistent-counter id, roll to it, and rebuild. Returns the
85 /// build report JSON (imported bodies + any per-feature error). A non-STEP
86 /// payload is refused up front so a bad upload never leaves a dead feature.
87 pub fn import_step_feature(&mut self, step_text: &str) -> Result<String, String> {
88 if !step_text.contains("ISO-10303-21") {
89 return Err("not a STEP file (missing the ISO-10303-21 header)".into());
90 }
91 let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
92 let feature = serde_json::json!({
93 "type": "IMPORT3D",
94 "inputParams": { "id": id, "stepText": step_text },
95 "persistentData": {},
96 });
97 // The file's AP242 PMI, lifted ONCE into the document's pmi block with
98 // references naming the faces / edges / vertices the feature will stamp
99 // (the STEP text is never re-read for it). Read BEFORE the add so the
100 // add's undo checkpoint precedes both writes: one undo removes the
101 // feature and its PMI together.
102 let lifted = brep_kernel::read_step_pmi(step_text, &id).unwrap_or(None);
103 // Frame the imported body once the (possibly async) run lands — see
104 // [`EngineState::pending_fit`]. An immediate fit here would frame the still
105 // empty scene under a background runner (native thread / wasm worker).
106 self.pending_fit = true;
107 let report = self.add_feature(&feature.to_string());
108 if let Some(lifted) = lifted {
109 self.pmi_merge_imported(lifted);
110 }
111 report
112 }
113
114 /// Export the CURRENT model's resident solids to an ISO-10303-21 STEP
115 /// document. Collects the resident handles of the rolled-to model (a warm
116 /// re-run of the same prefix the display scene was built from — see
117 /// [`crate::pipeline::resident_solid_handles`]) and hands them to the kernel's
118 /// [`brep_kernel::export_step_handles`], so the exact NURBS topology is
119 /// serialized (never the display mesh). Errs clearly when the model is empty.
120 pub fn export_step_text(&mut self) -> Result<String, String> {
121 self.export_step_text_named("Part")
122 }
123
124 /// [`Self::export_step_text`] with the document's own name, which becomes
125 /// the root `PRODUCT`'s name (and the file's `FILE_NAME`).
126 ///
127 /// A document with ASSEMBLY COMPONENTS takes the STRUCTURED lane: each
128 /// parts-library entry is written once as its own product, in its own local
129 /// frame, and every instance becomes a `NEXT_ASSEMBLY_USAGE_OCCURRENCE`
130 /// carrying its pose — nested sub-assemblies included. Without components
131 /// the flat single-product writer is used, exactly as before.
132 pub fn export_step_text_named(&mut self, document_name: &str) -> Result<String, String> {
133 self.export_step_text_selected(document_name, None)
134 }
135
136 /// [`Self::export_step_text_named`] restricted to the resident solids
137 /// named in `only` (each must be one; none may repeat). A subset is a
138 /// flat part's: a document with assembly components or a board refuses
139 /// it, and its PMI is left out, since the annotations may reference
140 /// solids the file no longer holds.
141 pub fn export_step_text_selected(&mut self, document_name: &str, only: Option<&[String]>) -> Result<String, String> {
142 self.plugin_export_ready()?;
143 // The component projection the structured lane places instances by is
144 // the one the last run shipped (post-solve poses), so nothing has to be
145 // synced here; the resident re-run below registers the geometry.
146 let request: HistoryRequest = serde_json::from_value(self.run_request_value())
147 .map_err(|e| format!("export STEP: history request: {e}"))?;
148 let mut named = self.plugin_resident_handles(&request)?;
149 if let Some(only) = only {
150 if !self.assembly_components.is_empty() {
151 return Err("export STEP: a subset of solids is exported from a part document, not an assembly".into());
152 }
153 for name in only {
154 if !named.iter().any(|(n, _)| n == name) {
155 return Err(format!("export STEP: `{name}` is not a solid of this model"));
156 }
157 }
158 named.retain(|(n, _)| only.contains(n));
159 }
160 // A board document's BOARD — substrate, copper, via barrels — as exact
161 // solids. The viewport's board is display triangles in no registry, so
162 // these are handed to the writer as values, in the ROOT product beside
163 // whatever the history made (`step_solids`).
164 let board = if only.is_some() { Default::default() } else { self.board_step_solids().unwrap_or_default() };
165 for notice in &board.notices {
166 self.push_notice_as(super::NoticeSeverity::Warning, notice.clone());
167 }
168 if let Some(first) = board.skipped.first() {
169 // The file is still written; the user is told what it lacks.
170 self.push_notice(format!(
171 "STEP export: {} board item(s) could not be made as solids and are missing from the file — first: {first}",
172 board.skipped.len()
173 ));
174 }
175 if named.is_empty() && board.bodies.is_empty() {
176 return Err("nothing to export: the model has no solids".into());
177 }
178 // The document's PMI rides along as AP242 semantic PMI + saved views,
179 // resolved against the same resident solids the file is written from
180 // (the warm re-run above left the tail's report on this thread).
181 let report = request
182 .pmi
183 .as_ref()
184 .filter(|_| only.is_none())
185 .map(|_| {
186 let _trace = crate::run_trace::span("export_pmi");
187 self.execute_plugin_history(&request).pmi
188 })
189 .flatten();
190 let annotation_errors = super::plugins::plugin_annotation_errors(report.as_ref());
191 if !annotation_errors.is_empty() {
192 return Err(format!("plugin annotation export replay failed: {}", annotation_errors.join("; ")));
193 }
194 let pmi = match (request.pmi.as_ref().filter(|_| only.is_none()), report.as_ref()) {
195 (Some(state), Some(report)) => Some(brep_kernel::StepPmi { state, report }),
196 _ => None,
197 };
198 let mut colors = self.step_export_colors(&named);
199 for (name, rgb) in &board.colors {
200 // A colour the user stored under a board body's name still wins.
201 if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
202 colors.set(name, *rgb);
203 }
204 }
205 // The resident solids by value — read on THIS thread, where the re-run
206 // above registered them — whenever the handle-taking writers cannot
207 // take the whole file: there is a board to add, or a product id to fix.
208 let resident = |named: &[(String, u32)]| -> Result<Vec<(String, brep_kernel::BrepSolid)>, String> {
209 named
210 .iter()
211 .map(|(name, handle)| Ok((name.clone(), brep_kernel::registered_solid_clone(*handle)?)))
212 .collect()
213 };
214 if self.assembly_components.is_empty() && !board.bodies.is_empty() {
215 let mut solids = resident(&named)?;
216 solids.extend(board.bodies);
217 let borrowed: Vec<(String, &brep_kernel::BrepSolid)> =
218 solids.iter().map(|(name, solid)| (name.clone(), solid)).collect();
219 return brep_kernel::export_step_report_named(
220 &borrowed,
221 document_name,
222 "MM",
223 "",
224 pmi.as_ref(),
225 Some(&colors),
226 )
227 .map(|report| report.text);
228 }
229 if self.assembly_components.is_empty() {
230 return brep_kernel::export_step_named_handles(
231 &named,
232 document_name,
233 "MM",
234 "",
235 pmi.as_ref(),
236 Some(&colors),
237 )
238 .map(|report| report.text);
239 }
240 let components: Vec<(String, String, brep_kernel::Mat4)> = self
241 .assembly_components
242 .iter()
243 .map(|record| {
244 (
245 record.id.clone(),
246 record.part_name.clone(),
247 record.transform,
248 )
249 })
250 .collect();
251 let resident = resident(&named)?;
252 let mut assembly = self.with_plugin_provider(||
253 brep_kernel::assembly_export_tree(document_name, resident, &components))?;
254 // The board is a product of its own, placed in the root at identity,
255 // so a receiving system's tree lists it by name (`PCB`) beside the
256 // parts. As the root's own geometry it read as an unnamed compound
257 // (OpenCascade: `=>[0:1:1:6]`). Its colours are keyed again under the
258 // occurrence's namespace, which is how the writer resolves them.
259 if !board.bodies.is_empty() {
260 for (name, rgb) in &board.colors {
261 if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
262 colors.set(&format!("{BOARD_OCCURRENCE}:{name}"), *rgb);
263 }
264 }
265 for (name, rgb) in self.persisted_export_colors() {
266 if name.starts_with(super::board_geometry::BOARD_SOLID_PREFIX) {
267 colors.set(&format!("{BOARD_OCCURRENCE}:{name}"), rgb);
268 }
269 }
270 assembly.products.push(brep_kernel::StepExportProduct {
271 name: BOARD_OCCURRENCE.to_string(),
272 id: BOARD_OCCURRENCE.to_string(),
273 bodies: board.bodies,
274 pmi: None,
275 });
276 assembly.occurrences.push(brep_kernel::StepExportOccurrence {
277 designator: BOARD_OCCURRENCE.to_string(),
278 parent: 0,
279 child: assembly.products.len() - 1,
280 placement: [
281 1., 0., 0., 0., //
282 0., 1., 0., 0., //
283 0., 0., 1., 0., //
284 0., 0., 0., 1.,
285 ],
286 });
287 }
288 for product in &mut assembly.products {
289 product.id = portable_product_id(&product.id, &product.name);
290 }
291 if self.history.pcb_block().is_some() && pmi.is_none() {
292 self.label_occurrences_by_reference(&mut assembly, &mut colors, &named);
293 }
294 brep_kernel::export_step_assembly_report(&assembly, "MM", "", pmi.as_ref(), Some(&colors))
295 .map(|report| report.text)
296 }
297
298 /// A BOARD document's placed parts, named in the STEP tree by their
299 /// REFERENCE DESIGNATOR (`U1`, `R3`) instead of the component feature id
300 /// (`ACOMP1`) — the name the engineer on the other end knows the part by.
301 ///
302 /// The occurrence label is also the namespace the writer resolves the
303 /// document's names through (`ACOMP1:IMPORT3D1_Face_0` finds its face under
304 /// the `ACOMP1:` occurrence), so every colour keyed under a relabelled
305 /// component is keyed again under its new label, or the KiCad body colours
306 /// would drop out of the file. PMI resolves through the same namespace,
307 /// which is why the caller only relabels a document that carries none.
308 ///
309 /// A reference is used only when it is unambiguous: non-empty, free of the
310 /// `:` namespace separator, carried by exactly one component, and neither
311 /// some other component's id nor the board's own label
312 /// ([`BOARD_OCCURRENCE`]). Anything else keeps its feature id.
313 fn label_occurrences_by_reference(
314 &self,
315 assembly: &mut brep_kernel::StepAssemblyExport,
316 colors: &mut brep_kernel::StepColors,
317 named: &[(String, u32)],
318 ) {
319 let mut references: std::collections::BTreeMap<String, String> = Default::default();
320 let mut seen: std::collections::BTreeMap<String, usize> = Default::default();
321 let mut ids: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
322 for feature in self.history.features() {
323 let is_component = feature["type"]
324 .as_str()
325 .is_some_and(super::components::is_acomp_feature_type);
326 let params = &feature["inputParams"];
327 let Some(id) = params["id"].as_str().filter(|_| is_component) else {
328 continue;
329 };
330 ids.insert(id.to_string());
331 let reference = params["bom"]["Reference_Designator"].as_str().unwrap_or("").trim();
332 if !reference.is_empty() && !reference.contains(':') {
333 references.insert(id.to_string(), reference.to_string());
334 *seen.entry(reference.to_string()).or_default() += 1;
335 }
336 }
337 references.retain(|_, reference| {
338 seen[reference.as_str()] == 1 && !ids.contains(reference.as_str()) && reference != BOARD_OCCURRENCE
339 });
340 if references.is_empty() {
341 return;
342 }
343 for occurrence in assembly.occurrences.iter_mut().filter(|o| o.parent == 0) {
344 if let Some(reference) = references.get(&occurrence.designator) {
345 occurrence.designator = reference.clone();
346 }
347 }
348 // The same colours `step_export_colors` keyed, keyed again under the
349 // new label: the persisted ones, and the name-hash look's.
350 let hashed = self.settings.face_color_mode == crate::style::FaceColorMode::HashedBySolid;
351 let mut keyed: Vec<(String, [u8; 3])> = self.persisted_export_colors();
352 if hashed {
353 for (name, _) in named {
354 if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
355 keyed.push((name.clone(), srgb_bytes(crate::color::solid_color_srgb(name))));
356 }
357 }
358 }
359 for (name, rgb) in keyed {
360 let Some((id, rest)) = name.split_once(':') else {
361 continue;
362 };
363 if let Some(reference) = references.get(id) {
364 colors.set(&format!("{reference}:{rest}"), rgb);
365 }
366 }
367 }
368
369 /// The body/face colours the STEP writer should emit as presentation styles.
370 ///
371 /// The METADATA STORE is the authority, exactly as it is for the viewport
372 /// ([`EngineState::sync_colors_from_metadata`]): every `color` attribute the
373 /// document persists — a STEP import's stamped colours, a colour picked in
374 /// the Info window, a colour restored from a saved file — becomes a style on
375 /// the body or face of that name. Spellings are read through
376 /// [`crate::style::parse_css_hex`], the one parser the display uses, so a
377 /// value the viewport shows is a value the file carries.
378 ///
379 /// `override_model_colors` is deliberately NOT honoured: it is a display
380 /// switch whose own contract is that the store is never touched, so a
381 /// document exported with the box ticked still carries all of its colours.
382 ///
383 /// The NAME-DERIVED fallback is the second half, and it is narrow on
384 /// purpose: a body with no persisted colour gets the stable name-hash
385 /// colour ONLY when the viewport is itself colouring by name hash
386 /// ([`crate::style::FaceColorMode::HashedBySolid`] — the artifact look, not
387 /// the default). In the default `Uniform` mode an uncoloured body gets no
388 /// style at all, so an export from a document nobody coloured is
389 /// byte-for-byte the file this writer produced before colour existed rather
390 /// than a model painted in colours the user never saw.
391 ///
392 /// Faces are never name-derived: the renderer hashes per SOLID, so there is
393 /// no per-face colour to match.
394 fn step_export_colors(&self, named: &[(String, u32)]) -> brep_kernel::StepColors {
395 let mut colors = brep_kernel::StepColors::new();
396 for (name, rgb) in self.persisted_export_colors() {
397 colors.set(&name, rgb);
398 }
399 if self.settings.face_color_mode == crate::style::FaceColorMode::HashedBySolid {
400 for (name, _) in named {
401 if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
402 colors.set(name, srgb_bytes(crate::color::solid_color_srgb(name)));
403 }
404 }
405 }
406 colors
407 }
408
409 /// Resident handle of the part's target sheet-metal body for a flat-pattern
410 /// export. Enumerates the current resident solids (a warm re-run of the same
411 /// prefix the display scene was built from, like the STEP lane) and keeps the
412 /// ones carrying a sheet-metal tree; uses the SELECTED sheet-metal body if the
413 /// selection names exactly one, else the SOLE sheet-metal body (the same
414 /// auto-target SM.CUTOUT uses). Errs with the exact `"no sheet-metal body in
415 /// the part"` when there is none, and loudly when several are ambiguous.
416 fn flat_pattern_target_handle(&self) -> Result<u32, String> {
417 self.plugin_export_ready()?;
418 let request: HistoryRequest = serde_json::from_value(self.run_request_value())
419 .map_err(|e| format!("export flat pattern: history request: {e}"))?;
420 let sheet_metal: Vec<(String, u32)> = self.plugin_resident_handles(&request)?
421 .into_iter()
422 .filter(|(_, handle)| brep_kernel::is_sheet_metal_handle(*handle))
423 .collect();
424 if sheet_metal.is_empty() {
425 return Err("no sheet-metal body in the part".into());
426 }
427 // Prefer a selected sheet-metal body when the selection names exactly one.
428 let selected: Vec<u32> = sheet_metal
429 .iter()
430 .filter(|(name, _)| self.emphasis.selected_solids.contains(name))
431 .map(|(_, handle)| *handle)
432 .collect();
433 if let [handle] = selected.as_slice() {
434 return Ok(*handle);
435 }
436 match sheet_metal.as_slice() {
437 [(_, handle)] => Ok(*handle),
438 _ => Err(
439 "several sheet-metal bodies in the part — select the one to export".into(),
440 ),
441 }
442 }
443
444 /// Export the part's sheet-metal FLAT PATTERN (the unfold) as a DXF (R12
445 /// ASCII) 2D vector document. Runs the unfold TRANSIENTLY off the target
446 /// body's resident tree — no feature is added and history is not mutated. Errs
447 /// (`"no sheet-metal body in the part"`) when the part carries no sheet metal.
448 pub fn export_flat_pattern_dxf(&self) -> Result<String, String> {
449 brep_kernel::flat_pattern_dxf(self.flat_pattern_target_handle()?)
450 }
451
452 /// Export the part's sheet-metal flat pattern as an SVG — the DXF sibling of
453 /// [`Self::export_flat_pattern_dxf`].
454 pub fn export_flat_pattern_svg(&self) -> Result<String, String> {
455 brep_kernel::flat_pattern_svg(self.flat_pattern_target_handle()?)
456 }
457
458 /// Import an IGES document into the model: append an `IMPORT3D` feature whose
459 /// `inputParams.igesText` is the raw IGES text (the kernel importer reads it
460 /// via [`brep_kernel::import_iges`]), mint an id, roll to it, and rebuild.
461 /// Refuses a non-IGES payload up front so a bad upload never leaves a dead
462 /// feature.
463 pub fn import_iges_feature(&mut self, iges_text: &str) -> Result<String, String> {
464 if iges_text.contains("ISO-10303-21") {
465 return Err("not an IGES file (this looks like a STEP document)".into());
466 }
467 // IGES records carry an S/G/D/P/T section letter in column 73.
468 let looks_like_iges = iges_text.lines().any(|line| {
469 matches!(line.chars().nth(72), Some('S' | 'G' | 'D' | 'P' | 'T'))
470 });
471 if !looks_like_iges {
472 return Err("not an IGES file (no S/G/D/P/T section records found)".into());
473 }
474 let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
475 let feature = serde_json::json!({
476 "type": "IMPORT3D",
477 "inputParams": { "id": id, "igesText": iges_text },
478 "persistentData": {},
479 });
480 // Frame the imported body once the (possibly async) run lands — see
481 // [`EngineState::pending_fit`] (mirrors the STEP lane above).
482 self.pending_fit = true;
483 self.add_feature(&feature.to_string())
484 }
485
486 /// Export the CURRENT model's resident solids to an IGES 5.3 document of
487 /// trimmed NURBS surfaces — the IGES analogue of [`Self::export_step_text`],
488 /// handing the resident handles to [`brep_kernel::export_iges_handles`].
489 pub fn export_iges_text(&self) -> Result<String, String> {
490 self.plugin_export_ready()?;
491 let request: HistoryRequest = serde_json::from_value(self.run_request_value())
492 .map_err(|e| format!("export IGES: history request: {e}"))?;
493 let handles: Vec<u32> = self.plugin_resident_handles(&request)?
494 .into_iter()
495 .map(|(_, handle)| handle)
496 .collect();
497 if handles.is_empty() {
498 return Err("nothing to export: the model has no solids".into());
499 }
500 brep_kernel::export_iges_handles(&handles, "Part", "MM", "")
501 }
502
503 /// Export the CURRENT display scene to an ASCII STL string (one `solid` with a
504 /// per-triangle geometric normal for every mesh triangle of every displayed
505 /// solid). STL is a triangle-soup format with no multi-body concept, so all
506 /// solids fold into a single `solid brep … endsolid brep`. String-shaped so it
507 /// crosses the same string `ModelStore` seam the STEP lane uses. Errs when the
508 /// scene has no triangles.
509 pub fn export_stl_text(&self) -> Result<String, String> {
510 self.plugin_export_ready()?;
511 let mut facets = Vec::new();
512 for solid in self.scene.solids() {
513 let positions = &solid.mesh.positions;
514 for tri in solid.mesh.indices.chunks_exact(3) {
515 let a = positions[tri[0] as usize];
516 let b = positions[tri[1] as usize];
517 let c = positions[tri[2] as usize];
518 facets.push((triangle_normal(a, b, c), [a, b, c]));
519 }
520 }
521 if facets.is_empty() {
522 return Err("nothing to export: the scene has no triangles".into());
523 }
524 Ok(brep_kernel::write_ascii_stl("brep", facets))
525 }
526
527 /// Export the CURRENT display scene as Wavefront OBJ text — the same
528 /// triangles [`Self::export_stl_text`] writes, folded into ONE object `brep`
529 /// with the display normals kept per vertex, through the kernel's
530 /// [`brep_kernel::write_obj`]. Millimetres, like every other export lane.
531 /// Errs when the scene has no triangles.
532 pub fn export_obj_text(&self) -> Result<String, String> {
533 self.plugin_export_ready()?;
534 let mut mesh = brep_kernel::Mesh::default();
535 for solid in self.scene.solids() {
536 let base = (mesh.positions.len() / 3) as u32;
537 for (position, normal) in solid.mesh.positions.iter().zip(&solid.mesh.normals) {
538 mesh.positions.extend(position.iter().map(|value| f64::from(*value)));
539 mesh.normals.extend(normal.iter().map(|value| f64::from(*value)));
540 }
541 mesh.indices.extend(solid.mesh.indices.iter().map(|index| base + index));
542 }
543 if mesh.indices.is_empty() {
544 return Err("nothing to export: the scene has no triangles".into());
545 }
546 brep_kernel::write_obj(&mesh, "brep")
547 }
548
549 /// Every `color` attribute the document persists, as 8-bit sRGB keyed by
550 /// scene name. The METADATA STORE is the authority for BOTH export lanes —
551 /// the STEP writer's styles ([`Self::step_export_colors`]) and the GLB
552 /// writer's materials ([`Self::export_glb_bytes`]) — so a colour the Info
553 /// window's Metadata tab shows is the colour either file carries. Spellings
554 /// are read through [`crate::style::parse_css_hex`], the one parser the
555 /// display itself uses.
556 fn persisted_export_colors(&self) -> Vec<(String, [u8; 3])> {
557 self.metadata
558 .all()
559 .iter()
560 .filter_map(|(name, record)| {
561 let value = record.get(brep_kernel::COLOR_METADATA_KEY)?;
562 let rgb = crate::style::parse_css_hex(value)?;
563 Some((name.clone(), srgb_bytes(rgb.map(f64::from))))
564 })
565 .collect()
566 }
567
568 /// The colour the VIEWPORT is showing a body with no persisted colour of
569 /// its own: the uniform `face_color` setting, or the stable name-hash in the
570 /// artifact look. This is the one place the GLB lane parts company with the
571 /// STEP and 3MF lanes, which leave such a body unstyled — glTF has no "no
572 /// style" state, so a primitive with no material renders in the format's
573 /// own default (white, fully metallic), a colour nobody chose.
574 fn display_body_color(&self, name: &str) -> [u8; 3] {
575 match self.settings.face_color_mode {
576 crate::style::FaceColorMode::HashedBySolid => {
577 srgb_bytes(crate::color::solid_color_srgb(name))
578 }
579 crate::style::FaceColorMode::Uniform => {
580 let face = self.settings.face_color;
581 srgb_bytes([f64::from(face[0]), f64::from(face[1]), f64::from(face[2])])
582 }
583 }
584 }
585
586 /// Export the CURRENT display scene as a binary glTF 2.0 (`.glb`) document —
587 /// the same triangles [`Self::export_stl_text`] and [`Self::export_obj_text`]
588 /// write, through the kernel's [`brep_kernel::write_glb`]. Unlike those two,
589 /// glTF HAS a multi-body concept, so each scene solid becomes its own named
590 /// mesh instead of folding into one object.
591 ///
592 /// BINARY, not text: the bytes cross the store's byte-shaped interchange
593 /// (`export_file_named_bytes`), because base64 through the text lane would
594 /// inflate the file by a third for nothing.
595 ///
596 /// The axis convention (+Y up, which is both glTF's and this application's,
597 /// so the identity) and the millimetre-to-metre unit both ride on the root
598 /// NODE's transform — see the kernel module's doc. COLOURS are the metadata
599 /// store's, the same authority the STEP lane reads, with a face's beating its
600 /// body's; a body the store says nothing about takes the colour the viewport
601 /// shows it in (`Self::display_body_color`). `override_model_colors` is not
602 /// honoured, exactly as it is not by the STEP lane: it is a display switch
603 /// whose contract is that the store is never touched.
604 ///
605 /// Errs when the scene has no triangles.
606 pub fn export_glb_bytes(&self, document_name: &str) -> Result<Vec<u8>, String> {
607 self.plugin_export_ready()?;
608 let colors: std::collections::BTreeMap<String, [u8; 3]> =
609 self.persisted_export_colors().into_iter().collect();
610 let solids: Vec<brep_kernel::GlbSolid> = self
611 .scene
612 .solids()
613 .iter()
614 .map(|solid| {
615 let mut mesh = brep_kernel::Mesh::default();
616 for (position, normal) in solid.mesh.positions.iter().zip(&solid.mesh.normals) {
617 mesh.positions.extend(position.iter().map(|value| f64::from(*value)));
618 mesh.normals.extend(normal.iter().map(|value| f64::from(*value)));
619 }
620 mesh.indices = solid.mesh.indices.clone();
621 // The kernel writer groups by the per-TRIANGLE face id, which is
622 // an index into this solid's own `faces` — the same numbering
623 // `face_colors` is keyed by below.
624 mesh.face_ids = solid.mesh.face_ids.clone();
625 let face_colors = solid
626 .faces
627 .iter()
628 .enumerate()
629 .filter_map(|(index, face)| {
630 colors.get(&face.name).map(|rgb| (index as u32, *rgb))
631 })
632 .collect();
633 brep_kernel::GlbSolid {
634 name: solid.name.clone(),
635 mesh,
636 color: Some(
637 colors
638 .get(&solid.name)
639 .copied()
640 .unwrap_or_else(|| self.display_body_color(&solid.name)),
641 ),
642 face_colors,
643 }
644 })
645 .collect();
646 brep_kernel::write_glb(
647 &solids,
648 document_name,
649 brep_kernel::GlbUpAxis::YUp,
650 METRES_PER_MILLIMETRE,
651 )
652 .map(|(bytes, _report)| bytes)
653 }
654 /// Export the CURRENT display scene as a 3MF package (`.3mf`) — the same
655 /// triangles the STL, OBJ and GLB lanes write, through the kernel's
656 /// [`brep_kernel::write_3mf`], one named `<object>` per scene solid with
657 /// its vertices welded (3MF wants a closed manifold, which the per-face
658 /// display soup is not). BINARY, so the bytes cross the store's byte-shaped
659 /// interchange like a GLB's.
660 ///
661 /// COLOURS follow the STEP lane's rule, not the GLB lane's: the metadata
662 /// store is the authority, a face's colour beats its body's, and a body the
663 /// store says nothing about is written with NO material — 3MF, unlike glTF,
664 /// has that state, and it is what a slicer user wants of an unpainted part
665 /// (it prints in the filament's colour, not a grey this app chose). The one
666 /// exception is the same as STEP's: in the `hashedBySolid` face-colour mode
667 /// an uncoloured body is written in the name-derived colour the viewport
668 /// shows. `override_model_colors` is not honoured, as in the other lanes.
669 ///
670 /// Errs when the scene has no triangles.
671 pub fn export_3mf_bytes(&self, document_name: &str) -> Result<Vec<u8>, String> {
672 self.plugin_export_ready()?;
673 let colors: std::collections::BTreeMap<String, [u8; 3]> =
674 self.persisted_export_colors().into_iter().collect();
675 let hashed = self.settings.face_color_mode == crate::style::FaceColorMode::HashedBySolid;
676 let solids: Vec<brep_kernel::ThreeMfSolid> = self
677 .scene
678 .solids()
679 .iter()
680 .map(|solid| {
681 let mut mesh = brep_kernel::Mesh::default();
682 for (position, normal) in solid.mesh.positions.iter().zip(&solid.mesh.normals) {
683 mesh.positions.extend(position.iter().map(|value| f64::from(*value)));
684 mesh.normals.extend(normal.iter().map(|value| f64::from(*value)));
685 }
686 mesh.indices = solid.mesh.indices.clone();
687 mesh.face_ids = solid.mesh.face_ids.clone();
688 let face_colors = solid
689 .faces
690 .iter()
691 .enumerate()
692 .filter_map(|(index, face)| {
693 colors.get(&face.name).map(|rgb| (index as u32, *rgb))
694 })
695 .collect();
696 let color = colors.get(&solid.name).copied().or_else(|| {
697 hashed.then(|| srgb_bytes(crate::color::solid_color_srgb(&solid.name)))
698 });
699 brep_kernel::ThreeMfSolid { name: solid.name.clone(), mesh, color, face_colors }
700 })
701 .collect();
702 brep_kernel::write_3mf(&solids, document_name).map(|(bytes, _report)| bytes)
703 }
704
705 /// The solids a 3D PDF shows ([`crate::sheets::pdf3d::Body`]): every
706 /// visible, non-sketch solid with triangles, UN-POSED (an explode the
707 /// active PMI view applies to the viewport is that view's, not the
708 /// model's), coloured by the GLB lane's rule — a face's persisted colour,
709 /// else its body's, else the colour the viewport shows the body in — with
710 /// its real edges (not the auxiliary or centre-line display edges).
711 pub fn pdf3d_bodies(&self) -> Vec<crate::sheets::pdf3d::Body> {
712 let colors: std::collections::BTreeMap<String, [u8; 3]> =
713 self.persisted_export_colors().into_iter().collect();
714 self.scene
715 .solids()
716 .iter()
717 .map(|shown| self.pmi_explode_originals.get(&shown.name).unwrap_or(shown))
718 .filter(|solid| solid.visible && !solid.is_sketch && solid.mesh.indices.len() >= 3)
719 .map(|solid| {
720 let body = colors.get(&solid.name).copied().unwrap_or_else(|| self.display_body_color(&solid.name));
721 let face_colors: Vec<[u8; 3]> = solid
722 .faces
723 .iter()
724 .map(|face| colors.get(&face.name).copied().unwrap_or(body))
725 .collect();
726 crate::sheets::pdf3d::Body {
727 name: solid.name.clone(),
728 positions: solid.mesh.positions.clone(),
729 normals: solid.mesh.normals.clone(),
730 indices: solid.mesh.indices.clone(),
731 triangle_colors: solid
732 .mesh
733 .face_ids
734 .iter()
735 .map(|face| face_colors.get(*face as usize).copied().unwrap_or(body))
736 .collect(),
737 edges: solid
738 .edges
739 .iter()
740 .filter(|edge| !edge.aux && !edge.centerline && edge.polyline.len() >= 2)
741 .map(|edge| edge.polyline.clone())
742 .collect(),
743 }
744 })
745 .collect()
746 }
747}
748
749/// The model's unit expressed in glTF's. Every export lane writes millimetres
750/// (the STEP writer's `MM`) and glTF's own linear unit is the METRE, so the GLB
751/// root node carries this as its scale rather than the vertices being rewritten.
752const METRES_PER_MILLIMETRE: f64 = 0.001;
753
754/// Unit (or zero, for a degenerate triangle) geometric normal of triangle
755/// `(a, b, c)` — the per-facet normal an ASCII STL record carries.
756fn triangle_normal(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 3] {
757 let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
758 let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
759 let n = [
760 u[1] * v[2] - u[2] * v[1],
761 u[2] * v[0] - u[0] * v[2],
762 u[0] * v[1] - u[1] * v[0],
763 ];
764 let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
765 if len > 0.0 {
766 [n[0] / len, n[1] / len, n[2] / len]
767 } else {
768 [0.0, 0.0, 0.0]
769 }
770}
771
772// ===========================================================================
773// STRUCTURED STEP import — the assembly lane.
774//
775// The flat lane above (`import_step_feature`) appends ONE IMPORT3D holding the
776// raw Part-21 text and lets the kernel bake every occurrence's world transform
777// into its own body: N bodies, no parts, no tree. This lane keeps the structure
778// instead — each unique geometry-bearing PRODUCT_DEFINITION becomes ONE
779// parts-library entry holding a NATIVE payload (`nativeBrep`, no STEP text
780// anywhere past this door), and each occurrence of it becomes an ACOMP instance
781// carrying the composed world pose. Six bolts are then one entry × six
782// instances, which is what makes the BOM, the structure tree, per-component
783// selection and constraints work on imported geometry.
784//
785// # FLAT or NESTED — the user's choice, both correct
786//
787// [`StepAssemblyImport::nested`] picks between two shapes of the same
788// geometry:
789//
790// - **Flat** flattens the occurrence tree to its geometry-bearing leaves: one
791// ACOMP per leaf occurrence, each carrying the COMPOSED world pose. Every
792// part is stored once for the whole document.
793// - **Nested** keeps the tree: each assembly-node product becomes a part
794// document that itself carries `{partsLibrary, features: [ACOMP…,
795// IMPORT3D…]}`, built bottom-up by the same recursive builder, and the
796// parent gets ONE ACOMP per sub-assembly occurrence.
797//
798// Neither is the deprecated one. Nested shows the real tree; flat is the right
799// answer for a deep or pathological file, and it stores a part reused at two
800// levels ONCE, where nesting stores it once PER LEVEL. For a depth-1 tree the
801// two lanes produce byte-identical documents — the cheapest correctness check
802// there is, and `nested_matches_flat_for_a_depth_one_tree` asserts exactly it.
803//
804// # PROBE then CONSUME — because the parse is the expensive half
805//
806// The app must know the counts BEFORE it can offer the choice ("7 parts, 23
807// instances — import as assembly or as bodies?"), and re-reading multi-MB
808// Part-21 text after the user clicks would pay the file's single most expensive
809// cost twice. So [`EngineState::probe_step_assembly`] performs the ONE parse and
810// stashes the [`brep_kernel::StepAssembly`] in
811// [`EngineState::pending_step_assembly`];
812// [`EngineState::import_probed_step_assembly`] TAKES it. Cancel
813// ([`EngineState::discard_probed_step_assembly`]), a second probe, and a
814// document switch all drop it, so a user who cancels three imports is holding
815// zero parsed assemblies — a real consideration, since the stash keeps every
816// product's solids resident for as long as the dialog is open.
817//
818// # ONE rebuild for the whole import
819//
820// `add_feature` re-runs the entire history per call, so appending N instances
821// through it is O(N²). This lane appends them all through
822// [`EngineState::add_features`] — one push batch, one rebuild, one undo step.
823// (Not `set_history_json`: that is the document-SWITCH path, which clears the
824// kernel history cache and resets the runner's delta baseline.)
825//
826// # Fallback, never a silent zero
827//
828// No structure at all, or every geometry-bearing product failing to encode, both
829// end at today's flat lane. "A successful import that produces zero components"
830// is a failure wearing a result's clothes, so the zero-component case is an
831// `Err` for the dialog-driven entry point (the app owns the file text and re-runs
832// the flat import) and an automatic fall-back for the text-taking convenience.
833// ===========================================================================
834
835/// What the import dialog needs to describe a STEP file's structure — counts
836/// only, so the probe can answer without building anything.
837#[derive(Debug, Clone, Copy, PartialEq, Eq)]
838pub struct StepAssemblyProbe {
839 /// Unique geometry-bearing products → parts-library entries. The floor, not
840 /// the final count: a non-rigid occurrence bakes its own extra entry (§3.4).
841 pub parts: usize,
842 /// Geometry-bearing occurrences → ACOMP instance features.
843 pub instances: usize,
844 /// Longest root→node chain of occurrences. `1` is a flat assembly; `> 1`
845 /// means sub-assemblies exist, so [`StepAssemblyImport::nested`] changes
846 /// the shape of the result and the dialog's choice is worth offering.
847 pub nested_depth: usize,
848}
849
850/// The choices the import dialog collects.
851#[derive(Debug, Clone, Copy, Default)]
852pub struct StepAssemblyImport {
853 /// Build nested rigid sub-assembly documents instead of flattening the
854 /// tree to its leaf occurrences.
855 ///
856 /// `false` (the `Default`) is the flat lane, byte-for-byte unchanged. On a
857 /// depth-1 tree the two produce the same document, so this flag only ever
858 /// matters for a file that really has sub-assemblies.
859 pub nested: bool,
860}
861
862/// What an import did — the numbers the status line and notice report.
863#[derive(Debug, Clone, Default, PartialEq, Eq)]
864pub struct StepAssemblyReport {
865 /// Parts-library entries this import added or reused — the entries of the
866 /// USER'S document. On a nested import that is the top level only: a
867 /// sub-assembly's own entries live in ITS document's library, which the
868 /// parent never sees.
869 pub parts: usize,
870 /// ACOMP instance features appended to the user's document. Nested: one per
871 /// ROOT-level occurrence (a sub-assembly is one component), not one per
872 /// leaf body.
873 pub instances: usize,
874 /// Occurrences whose non-rigid factor was baked into a distinct part
875 /// (§3.4), summed over every level a nested import built.
876 pub baked_nonrigid: usize,
877 /// Products (or baked non-rigid variants of one) that did not encode to a
878 /// payload — skipped and counted, never fatal: the importer's
879 /// graceful-degradation contract, carried up to this altitude. Summed over
880 /// every level a nested import built.
881 pub failed_products: usize,
882 /// The first thing that went wrong, from the kernel's body-build errors or
883 /// this lane's own encode failures.
884 pub first_error: Option<String>,
885 /// The structured lane did not run: the file carries no usable structure, or
886 /// nothing in it encoded, so the bodies were imported through the flat lane
887 /// exactly as before. Only ever `true` from [`EngineState::import_step_assembly`],
888 /// which holds the text; the dialog-driven entry point returns `Err` instead
889 /// and lets its caller re-run the flat import it already has the text for.
890 pub flat_fallback: bool,
891}
892
893/// The outcome of consuming a parsed assembly, before it is shaped into either
894/// an `Err` (dialog lane) or a flat fallback (text lane) — so neither has to
895/// recognise "nothing imported" by matching an error string.
896enum Consumed {
897 Imported(StepAssemblyReport),
898 /// Every geometry-bearing product failed to encode: no components, so this
899 /// is not an import.
900 NoComponents {
901 failed_products: usize,
902 first_error: Option<String>,
903 },
904}
905
906/// A row-major 4×4 affine, the shape `StepOccurrence::placement` and
907/// `AffineTransform` both use.
908type Mat4 = [f64; 16];
909
910/// One node of the composed occurrence tree — a product at a world pose.
911struct PlacedProduct {
912 /// Index into `StepAssembly::products`.
913 product: usize,
914 /// Composed child-local → world transform.
915 world: Mat4,
916 /// Occurrence edges between a root and this node (`0` at a root).
917 depth: usize,
918 /// Every edge on the path here was rigid, so `world` IS a component pose.
919 /// False means the non-rigid factor must be baked into the part (§3.4).
920 rigid_path: bool,
921 /// The STEP occurrence edges walked to get here, root first — the chain a
922 /// lifted OCCURRENCE-scoped annotation names its geometry through
923 /// (`brep_kernel::rewrite_occurrence_refs`). Empty at a root.
924 chain: Vec<usize>,
925}
926
927/// A parts-library entry this import needs: a product, plus the bits of the
928/// non-rigid factor baked into it (all-zero linear block ⇒ none). Two
929/// occurrences of one product under DIFFERENT non-rigid factors are different
930/// parts — never a wrong-handed reuse.
931type PartKey = (usize, [u64; 9]);
932
933/// The `PartKey` factor slot for a plain rigid instance.
934const NO_FACTOR: [u64; 9] = [0; 9];
935
936impl EngineState {
937 /// Read a STEP file's product structure — THE parse of a structured import.
938 /// Stashes the parsed assembly (with every product's solids) for
939 /// [`Self::import_probed_step_assembly`] and returns the dialog's counts.
940 ///
941 /// `Ok(None)` = no usable structure (no NAUO edges, or none reaching built
942 /// geometry): the caller imports through the flat
943 /// [`Self::import_step_feature`] lane with the text it already holds, which
944 /// is byte-for-byte today's behaviour. `Err` only for text that is not a
945 /// Part 21 file at all — a BROKEN assembly degrades, it does not fail.
946 ///
947 /// Replaces any previously stashed assembly on EVERY outcome, `Ok(None)`
948 /// included: a stale stash surviving a probe of a different file is how a
949 /// consume silently imports the wrong one.
950 pub fn probe_step_assembly(
951 &mut self,
952 step_text: &str,
953 ) -> Result<Option<StepAssemblyProbe>, String> {
954 let id = self.submit_step_probe(step_text);
955 // Inline answers inside `submit`'s own pump; a background runner has
956 // not answered yet and this call must not pretend it has.
957 match self.take_step_probe() {
958 Some((answered, outcome)) if answered == id => match outcome {
959 super::StepProbeOutcome::Structure(probe) => Ok(Some(probe)),
960 super::StepProbeOutcome::Flat => Ok(None),
961 super::StepProbeOutcome::Failed(error) => Err(error),
962 },
963 _ => Err(
964 "the STEP probe is still running on the background runner — use \
965 submit_step_probe / take_step_probe"
966 .into(),
967 ),
968 }
969 }
970
971 /// SUBMIT a STEP text to be probed for product structure on the runner
972 /// (the parse builds every product's bodies: seconds for a real assembly,
973 /// which is why it leaves the UI thread). The answer arrives through
974 /// [`Self::take_step_probe`] under the returned id, after a later `pump`;
975 /// a found structure is stashed for [`Self::import_probed_step_assembly`].
976 /// Any earlier stash is dropped now — the probe REPLACES it on every
977 /// outcome, so a stale parse can never be consumed for the wrong file.
978 ///
979 /// The structure test the parse would make is "any NEXT_ASSEMBLY_USAGE_
980 /// OCCURRENCE entity" (`assembly_edges`), so a text with none cannot have
981 /// structure and is answered `Flat` without a trip to the runner: a part
982 /// file — the common upload — no longer pays a full parse only to be told
983 /// to take the flat lane, where the worker parses it anyway. (The text
984 /// test is a superset of the entity test: a stray mention in a comment
985 /// merely runs the parse.)
986 pub fn submit_step_probe(&mut self, step_text: &str) -> u64 {
987 self.pending_step_assembly = None;
988 let id = self.next_step_probe_id;
989 self.next_step_probe_id = self.next_step_probe_id.wrapping_add(1);
990 if !step_text.contains("NEXT_ASSEMBLY_USAGE_OCCURRENCE") {
991 self.step_probe_results
992 .push_back((id, super::StepProbeOutcome::Flat));
993 return id;
994 }
995 self.pending_step_probes.insert(id);
996 self.runner.submit_step_probe(crate::runner::StepProbeRequest {
997 id,
998 text: step_text.to_string(),
999 });
1000 self.pump();
1001 id
1002 }
1003
1004 /// The oldest answered probe, if any: its submission id and what it found.
1005 pub fn take_step_probe(&mut self) -> Option<(u64, super::StepProbeOutcome)> {
1006 self.step_probe_results.pop_front()
1007 }
1008
1009 /// Whether a submitted probe has not been answered yet — the app keeps the
1010 /// frame loop alive (and the panel its "reading…" status) while it is.
1011 pub fn step_probes_pending(&self) -> bool {
1012 !self.pending_step_probes.is_empty()
1013 }
1014
1015 /// Import the assembly [`Self::probe_step_assembly`] stashed: one
1016 /// parts-library entry per unique product, one ACOMP instance per
1017 /// occurrence, ONE rebuild. TAKES the stash, so a double-import is an error
1018 /// rather than a double-insert.
1019 ///
1020 /// `doc_name` names products the file left unnamed (`{doc_name}-part-{id}`).
1021 /// `opts.nested` chooses between the flat and nested shapes — see
1022 /// [`StepAssemblyImport::nested`]. Errs when nothing is stashed, and when
1023 /// every product failed to encode — the latter being the caller's cue to
1024 /// re-run the flat import with the file text it holds.
1025 /// `sink` receives every unique part document so the app can write it to
1026 /// the model store and hand back a real `sourceKey`; pass [`EmbeddedOnly`]
1027 /// to keep the parts embedded (what a caller with no store does).
1028 pub fn import_probed_step_assembly(
1029 &mut self,
1030 doc_name: &str,
1031 opts: StepAssemblyImport,
1032 sink: &mut dyn PartSink,
1033 ) -> Result<StepAssemblyReport, String> {
1034 let assembly = self.pending_step_assembly.take().ok_or_else(|| {
1035 "import STEP assembly: nothing probed (call probe_step_assembly first)".to_string()
1036 })?;
1037 match self.consume_step_assembly(assembly, doc_name, opts.nested, sink) {
1038 Consumed::Imported(report) => Ok(report),
1039 Consumed::NoComponents { first_error, .. } => Err(format!(
1040 "import STEP assembly: no part of the assembly could be built{}",
1041 first_error
1042 .map(|error| format!(" ({error})"))
1043 .unwrap_or_default()
1044 )),
1045 }
1046 }
1047
1048 /// Drop a probed assembly and the solids it holds resident — the dialog's
1049 /// Cancel. Idempotent.
1050 pub fn discard_probed_step_assembly(&mut self) {
1051 self.pending_step_assembly = None;
1052 }
1053
1054 /// Probe + consume in one call, falling back to the flat lane by itself —
1055 /// the HEADLESS/test entry point. The app uses the probe/consume pair
1056 /// instead, because it has a dialog between the two halves.
1057 ///
1058 /// Still exactly one parse: this is `probe_step_assembly` followed by the
1059 /// consume of what it stashed.
1060 ///
1061 /// Parts stay EMBEDDED here ([`EmbeddedOnly`]): this entry point has no
1062 /// store handle and no way to ask for a destination. The app uses the
1063 /// probe/consume pair with a real sink.
1064 pub fn import_step_assembly(
1065 &mut self,
1066 step_text: &str,
1067 doc_name: &str,
1068 opts: StepAssemblyImport,
1069 ) -> Result<StepAssemblyReport, String> {
1070 let structured = self.probe_step_assembly(step_text)?.is_some();
1071 let outcome = structured.then(|| {
1072 let assembly = self
1073 .pending_step_assembly
1074 .take()
1075 .expect("a Some probe stashed the assembly it counted");
1076 self.consume_step_assembly(assembly, doc_name, opts.nested, &mut EmbeddedOnly)
1077 });
1078 match outcome {
1079 Some(Consumed::Imported(report)) => Ok(report),
1080 // No structure, or a structure nothing built out of: import the
1081 // bodies exactly as the pre-assembly lane did.
1082 Some(Consumed::NoComponents {
1083 failed_products,
1084 first_error,
1085 }) => {
1086 self.import_step_feature(step_text)?;
1087 Ok(StepAssemblyReport {
1088 failed_products,
1089 first_error,
1090 flat_fallback: true,
1091 ..StepAssemblyReport::default()
1092 })
1093 }
1094 None => {
1095 self.import_step_feature(step_text)?;
1096 Ok(StepAssemblyReport {
1097 flat_fallback: true,
1098 ..StepAssemblyReport::default()
1099 })
1100 }
1101 }
1102 }
1103
1104 /// The import itself, shared by both entry points so neither has to
1105 /// recognise "nothing imported" from an error string.
1106 fn consume_step_assembly(
1107 &mut self,
1108 assembly: brep_kernel::StepAssembly,
1109 doc_name: &str,
1110 nested: bool,
1111 sink: &mut dyn PartSink,
1112 ) -> Consumed {
1113 let mut first_error = assembly.first_error.clone();
1114 // ONE writer for the whole import, so identical content is written to
1115 // the store exactly once however many products or LEVELS share it.
1116 let mut writer = PartWriter::new(sink);
1117
1118 // --- what to build ------------------------------------------------
1119 // One row per component the USER'S document gets, each naming the
1120 // library entry it needs. Flat walks the whole tree to its leaves;
1121 // nested stops at the root's own children and folds everything below
1122 // each of them into that child's part document.
1123 let plan = if nested {
1124 plan_nested(&assembly, doc_name, &mut first_error, &mut writer)
1125 } else {
1126 plan_flat(&assembly, &mut first_error)
1127 };
1128 let Plan {
1129 wanted,
1130 factors,
1131 documents,
1132 mut failed_products,
1133 baked_below_root,
1134 } = plan;
1135
1136 // --- build the library entries -------------------------------------
1137 // In (pd_ref, factor) order so an import is deterministic regardless of
1138 // the tree's emit order, and ONCE per key however many instances use it.
1139 let mut keys: Vec<PartKey> = wanted.iter().map(|(key, _, _)| *key).collect();
1140 keys.sort_unstable();
1141 keys.dedup();
1142 let mut entry_names: std::collections::HashMap<PartKey, String> =
1143 std::collections::HashMap::new();
1144 {
1145 // THE metadata bracket. `native_import_payload` seals whatever record
1146 // this thread's scene-metadata store holds for each name it stamps —
1147 // right for a snapshot of the live scene, catastrophic here: a new
1148 // part whose stamped face names collide with names already in THIS
1149 // document would silently carry the current document's metadata.
1150 // Scoped to the encode alone; the rebuild below stamps records the
1151 // document must keep, and this guard's drop would discard them.
1152 //
1153 // The nested lane's payloads are encoded inside `plan_nested`,
1154 // which holds a bracket of its own for exactly the same reason.
1155 let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
1156 for key in &keys {
1157 // Nested pre-built the whole document (a sub-assembly's is a
1158 // recursive `{partsLibrary, features}`); flat builds the §3.2
1159 // native part document right here.
1160 let built = match documents.get(key) {
1161 Some((name, document)) => install_part(name, document, &mut writer),
1162 None => {
1163 let product = assembly
1164 .products
1165 .iter()
1166 .find(|product| product.pd_ref == key.0)
1167 .expect("every key names a product of this assembly");
1168 build_library_entry(product, factors.get(key), doc_name, &mut writer)
1169 }
1170 };
1171 match built {
1172 Ok(name) => {
1173 entry_names.insert(*key, name);
1174 }
1175 Err(error) => {
1176 failed_products += 1;
1177 note(&mut first_error, error);
1178 }
1179 }
1180 }
1181 }
1182 if entry_names.is_empty() {
1183 return Consumed::NoComponents {
1184 failed_products,
1185 first_error,
1186 };
1187 }
1188
1189 // --- append every instance in ONE history mutation -----------------
1190 // `insert_component`'s rule, verbatim: ground the FIRST component only
1191 // when the document has none yet. Grounding a second one over-constrains
1192 // the next solve.
1193 let mut ground_next = !(0..self.history.len()).any(|index| {
1194 matches!(
1195 self.history.feature_type(index).as_deref(),
1196 Some("ACOMP") | Some("ASSEMBLY COMPONENT")
1197 )
1198 });
1199 let mut features: Vec<serde_json::Value> = Vec::with_capacity(wanted.len());
1200 let mut baked_nonrigid = 0usize;
1201 // Which component carries the geometry a STEP occurrence chain names —
1202 // the map the file's occurrence-scoped PMI is rewritten through, built
1203 // while the ids are minted because that is the only moment both halves
1204 // exist.
1205 let mut namespaces: std::collections::HashMap<Vec<usize>, String> =
1206 std::collections::HashMap::new();
1207 for (key, pose, chain) in &wanted {
1208 let Some(part_name) = entry_names.get(key) else {
1209 continue; // this product failed to encode; counted above
1210 };
1211 let transform = match brep_kernel::AffineTransform::new(*pose) {
1212 Ok(transform) => transform,
1213 Err(error) => {
1214 note(&mut first_error, format!("occurrence pose: {error}"));
1215 continue;
1216 }
1217 };
1218 if key.1 != NO_FACTOR {
1219 baked_nonrigid += 1;
1220 }
1221 let id = self.history.next_feature_id("ACOMP");
1222 namespaces
1223 .entry(chain.clone())
1224 .or_insert_with(|| format!("{id}:"));
1225 features.push(serde_json::json!({
1226 "type": "ACOMP",
1227 "inputParams": {
1228 "id": id,
1229 "partName": part_name,
1230 "transform": brep_kernel::transform_to_pose_params(&transform),
1231 "isFixed": ground_next,
1232 },
1233 "persistentData": {}
1234 }));
1235 ground_next = false;
1236 }
1237 if features.is_empty() {
1238 return Consumed::NoComponents {
1239 failed_products,
1240 first_error,
1241 };
1242 }
1243
1244 // The library block must ride the request so the display runner ingests
1245 // the new entries on the very next run (as `insert_component` does).
1246 // Written only now that there are components to reference them, so an
1247 // import that produced nothing leaves the document untouched.
1248 if let Ok(library) =
1249 serde_json::from_str::<serde_json::Value>(&brep_kernel::parts_library_json())
1250 {
1251 self.history.set_parts_library(library);
1252 }
1253 // Frame the assembly once the (possibly async) run lands — see
1254 // [`EngineState::pending_fit`], same reasoning as `import_step_feature`.
1255 self.pending_fit = true;
1256 let instances = features.len();
1257 let baked_nonrigid = baked_nonrigid + baked_below_root;
1258 self.add_features(&features);
1259
1260 // The file's ASSEMBLY-level PMI — annotations it pinned to an
1261 // occurrence, annotations spanning two parts, free notes — merged into
1262 // the document's own block with its references rewritten into THIS
1263 // import's component namespaces.
1264 //
1265 // AFTER the features, and with no checkpoint of its own, for the
1266 // reason `import_step_feature` reads its PMI BEFORE its `add_feature`:
1267 // `push_features` checkpoints at its START, so a block written first
1268 // is inside the snapshot undo restores — one undo would take the
1269 // components away and leave the annotations behind, every one of them
1270 // naming a component that no longer exists. Both writes have to fall
1271 // after the one checkpoint.
1272 //
1273 // It costs a second rebuild, which is what the flat lane already pays,
1274 // and only on a file that carries assembly-level PMI at all.
1275 //
1276 // A part's OWN PMI is not here: it rode into that part's document in
1277 // `native_part_document`, once for the part however many instances
1278 // place it — the exporter's rule, which is what makes the round trip
1279 // land the same annotations on the same parts.
1280 let pmi_unplaced = self.merge_assembly_pmi(&assembly, &namespaces);
1281 for line in &assembly.pmi_diagnostics {
1282 note(&mut first_error, line.clone());
1283 }
1284 if pmi_unplaced > 0 {
1285 note(
1286 &mut first_error,
1287 format!(
1288 "{pmi_unplaced} PMI reference(s) name an occurrence this import placed no \
1289 component for; the annotations are kept unresolved"
1290 ),
1291 );
1292 }
1293 Consumed::Imported(StepAssemblyReport {
1294 // DISTINCT entries, not distinct keys: `add_part_to_library` reuses
1295 // an entry whose content already matches, so two products that are
1296 // the same geometry collapse to one part (§3.5's free content dedup).
1297 parts: entry_names
1298 .values()
1299 .collect::<std::collections::HashSet<_>>()
1300 .len(),
1301 instances,
1302 baked_nonrigid,
1303 failed_products,
1304 first_error,
1305 flat_fallback: false,
1306 })
1307 }
1308}
1309
1310impl EngineState {
1311 /// Merge a structured import's ASSEMBLY-level PMI into the open document's
1312 /// block, rewriting every occurrence-scoped reference into the component
1313 /// namespace this import minted for that STEP occurrence chain.
1314 ///
1315 /// Returns how many references named a chain with no component — a NESTED
1316 /// import folds everything below a root child into that child's own
1317 /// document, so an annotation the file pinned three levels down has no
1318 /// top-level component to name. Those references keep the chain they came
1319 /// with, so the row reports itself in the panel instead of silently
1320 /// resolving to some other instance.
1321 ///
1322 /// No rerun and no undo checkpoint of its own: the caller writes this
1323 /// before `add_features`, whose single rebuild resolves it.
1324 fn merge_assembly_pmi(
1325 &mut self,
1326 assembly: &brep_kernel::StepAssembly,
1327 namespaces: &std::collections::HashMap<Vec<usize>, String>,
1328 ) -> usize {
1329 let Some(lifted) = assembly.pmi.clone() else {
1330 return 0;
1331 };
1332 let mut unplaced = 0usize;
1333 let mut state = self.pmi_state();
1334 for view in lifted.views {
1335 let id = state.next_id("VIEW");
1336 let mut annotations = Vec::with_capacity(view.annotations.len());
1337 for mut annotation in view.annotations {
1338 unplaced += brep_kernel::rewrite_occurrence_refs(&mut annotation.params, |chain| {
1339 namespaces.get(chain).cloned()
1340 });
1341 let prefix = brep_kernel::pmi_type(&annotation.kind)
1342 .map(|def| def.short_name)
1343 .unwrap_or("PMI");
1344 let fresh = state.next_id(prefix);
1345 if let Some(object) = annotation.params.as_object_mut() {
1346 object.insert("id".into(), serde_json::Value::String(fresh));
1347 }
1348 annotations.push(annotation);
1349 }
1350 state.views.push(brep_kernel::PmiView {
1351 id,
1352 name: view.name,
1353 camera: view.camera,
1354 display: view.display,
1355 annotations,
1356 });
1357 }
1358 let block = serde_json::to_value(&state).ok();
1359 self.history.set_pmi_block_no_undo(block);
1360 // The tail has to re-resolve the merged block against the components
1361 // the run above created; nothing else in this lane reruns after them.
1362 self.rerun_history();
1363 unplaced
1364 }
1365}
1366
1367/// What one import decided to build, before any of it is installed: the rows
1368/// the user's document gets, and whatever each lane needed to work out on the
1369/// way there.
1370#[derive(Default)]
1371struct Plan {
1372 /// One row per component of the USER'S document, in emit order: the
1373 /// library entry it needs, its pose, and the STEP occurrence chain it
1374 /// stands for — which is how a lifted occurrence-scoped annotation finds
1375 /// the component that carries its geometry.
1376 wanted: Vec<(PartKey, Mat4, Vec<usize>)>,
1377 /// FLAT only: the non-rigid factor a key's part must bake (§3.4). The
1378 /// nested lane bakes inside its own builder and hands the finished document
1379 /// over in `documents` instead.
1380 factors: std::collections::HashMap<PartKey, Mat4>,
1381 /// NESTED only: `(entry name, part document)` per key, already built — a
1382 /// leaf's §3.2 native document, or a sub-assembly's recursive
1383 /// `{partsLibrary, features}`.
1384 documents: std::collections::HashMap<PartKey, (String, serde_json::Value)>,
1385 /// Products that did not encode while planning (nested builds payloads
1386 /// during the plan; flat builds them during the install).
1387 failed_products: usize,
1388 /// Non-rigid occurrences baked BELOW the root — nested only, since the flat
1389 /// lane has no below-the-root and counts its bakes at install time.
1390 baked_below_root: usize,
1391}
1392
1393/// **FLAT**: flatten the occurrence tree to its geometry-bearing nodes, each
1394/// carrying the COMPOSED world pose. Byte-for-byte the lane A6 shipped.
1395fn plan_flat(assembly: &brep_kernel::StepAssembly, first_error: &mut Option<String>) -> Plan {
1396 let mut plan = Plan::default();
1397 for placed in &compose_world_occurrences(assembly) {
1398 let product = &assembly.products[placed.product];
1399 if product.bodies.is_empty() {
1400 continue; // a pure assembly node contributes structure, not a component
1401 }
1402 let (key, pose) = if placed.rigid_path {
1403 ((product.pd_ref, NO_FACTOR), placed.world)
1404 } else {
1405 // §3.4: world = rigid · factor. Bake `factor` into a distinct part
1406 // and give the instance the rigid residue, so a mirrored instance
1407 // never lands on its unmirrored twin.
1408 match split_rigid(&placed.world) {
1409 // Non-rigid edges that cancel out along the path leave an
1410 // identity factor: that is an ordinary instance of the ordinary
1411 // part, not a bake.
1412 Ok((rigid, factor)) if is_identity(&factor) => {
1413 ((product.pd_ref, NO_FACTOR), rigid)
1414 }
1415 Ok((rigid, factor)) => {
1416 let key = (product.pd_ref, factor_key(&factor));
1417 plan.factors.insert(key, factor);
1418 (key, rigid)
1419 }
1420 Err(error) => {
1421 note(first_error, error);
1422 continue;
1423 }
1424 }
1425 };
1426 plan.wanted.push((key, pose, placed.chain.clone()));
1427 }
1428 plan
1429}
1430
1431/// **NESTED**: the live document plays the ROOT, so it gets one component per
1432/// root-level row and nothing deeper —
1433///
1434/// - a root's OWN bodies become a leaf part at identity (exactly the flat
1435/// lane's treatment of interior geometry at the root), and
1436/// - each root-child occurrence becomes ONE component: a leaf part when the
1437/// child has no children of its own, else a rigid sub-assembly whose part
1438/// document carries its own `partsLibrary` and its own ACOMPs.
1439///
1440/// Emit order matches [`plan_flat`]'s DFS pre-order — root before its children,
1441/// children by ascending `edge_ref` — which is what makes the two lanes produce
1442/// the SAME document for a depth-1 tree.
1443fn plan_nested(
1444 assembly: &brep_kernel::StepAssembly,
1445 doc_name: &str,
1446 first_error: &mut Option<String>,
1447 writer: &mut PartWriter<'_>,
1448) -> Plan {
1449 // The same bracket the install loop holds, for the same reason: every
1450 // payload this builder encodes (at every level) must see an empty ambient
1451 // scene-metadata store, or a nested leaf whose stamped face names collide
1452 // with the live document's silently inherits the live document's records.
1453 let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
1454 let mut build = NestedBuild {
1455 assembly,
1456 doc_name,
1457 writer,
1458 memo: std::collections::HashMap::new(),
1459 factors: std::collections::HashMap::new(),
1460 entries: 0,
1461 bytes: 0,
1462 failed_products: 0,
1463 baked_nonrigid: 0,
1464 first_error: None,
1465 };
1466 let mut plan = Plan::default();
1467 for &root in &assembly.roots {
1468 let mut rows: Vec<(DocKey, Mat4, Vec<usize>)> = Vec::new();
1469 // The root's OWN bodies become a leaf part at identity — exactly the
1470 // flat lane's treatment, and the reason a depth-1 tree comes out the
1471 // same either way.
1472 if !assembly.products[root].bodies.is_empty() {
1473 rows.push((
1474 DocKey::Leaf((assembly.products[root].pd_ref, NO_FACTOR)),
1475 MAT4_IDENTITY,
1476 Vec::new(),
1477 ));
1478 }
1479 // Root-level bakes are counted by the install loop's own pass over
1480 // `wanted` (they are ordinary top-level rows); only bakes BELOW the root
1481 // — which never become rows of the user's document — are counted here.
1482 let mut root_level_bakes = 0usize;
1483 build.place_children(root, &[root], &mut rows, &mut root_level_bakes);
1484 for (key, pose, chain) in rows {
1485 let part = match build.document(key, &mut vec![root]) {
1486 Ok(Some(document)) => document,
1487 // A subtree with no geometry anywhere places nothing — the flat
1488 // lane says the same thing by emitting no component for it.
1489 Ok(None) => continue,
1490 Err(error) => {
1491 build.failed_products += 1;
1492 note(&mut build.first_error, error);
1493 continue;
1494 }
1495 };
1496 let part_key = key.part_key(assembly);
1497 plan.documents.insert(part_key, part);
1498 plan.wanted.push((part_key, pose, chain));
1499 }
1500 }
1501 plan.failed_products = build.failed_products;
1502 plan.baked_below_root = build.baked_nonrigid;
1503 if let Some(error) = build.first_error {
1504 note(first_error, error);
1505 }
1506 plan
1507}
1508
1509/// How deep the recursive builder will go before it refuses. `read_step_assembly`
1510/// guards cycles inside its own walk and [`NestedBuild::document`] guards them
1511/// again along the recursion path, so this is the SECOND line: a malformed file
1512/// that is merely pathologically deep (rather than cyclic) must not run the
1513/// native stack out. Sixty-four levels of embedded documents is already far past
1514/// anything a real CAD assembly carries — and each level embeds the whole
1515/// subtree below it, so the document would be unusable long before then.
1516const MAX_NESTED_DEPTH: usize = 64;
1517
1518/// How many DISTINCT part documents a nested import may build. Bounds the
1519/// builder's work; it does NOT bound the result's size — see
1520/// [`MAX_NESTED_BYTES`], which is the guard that matters.
1521const MAX_NESTED_ENTRIES: usize = 10_000;
1522
1523/// How many bytes of part document a nested import may EMBED, summed over every
1524/// `partsLibrary` entry it writes at every level.
1525///
1526/// This is the guard neither the depth cap nor the entry count provides. A
1527/// product reachable at many different depths is stored once PER LEVEL — the
1528/// memo builds its document once, but each parent embeds a COPY, so a
1529/// diamond-shaped structure well inside the depth cap can still multiply out
1530/// geometrically. Charging the embedded bytes is the only place that
1531/// multiplication is visible, so it is charged where it happens.
1532const MAX_NESTED_BYTES: usize = 256 * 1024 * 1024;
1533
1534/// What a nested part document is memoised under. A product is either a leaf
1535/// (no occurrence children) or an assembly node, never both, so the two
1536/// variants can never name the same product — except at a ROOT, whose own
1537/// bodies become a leaf part while the root itself is an assembly node. That
1538/// case is exactly why this is an enum and not a bare [`PartKey`].
1539#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1540enum DocKey {
1541 /// A geometry-bearing product placed as a part: `(pd_ref, baked factor)`.
1542 Leaf(PartKey),
1543 /// A product placed as a rigid sub-assembly, by index into `products`.
1544 Assembly(usize),
1545}
1546
1547impl DocKey {
1548 /// The parts-library identity this document is stored under. Always keyed on
1549 /// the `pd_ref` (never the product INDEX, which lives in a different number
1550 /// space and would collide with some other product's `pd_ref`). An assembly
1551 /// node never carries a baked factor — a non-rigid edge into one is skipped,
1552 /// see [`NestedBuild::place_children`] — so `NO_FACTOR` is exact.
1553 fn part_key(self, assembly: &brep_kernel::StepAssembly) -> PartKey {
1554 match self {
1555 DocKey::Leaf(key) => key,
1556 DocKey::Assembly(product) => (assembly.products[product].pd_ref, NO_FACTOR),
1557 }
1558 }
1559}
1560
1561/// The recursive builder behind [`plan_nested`]: turns one product into the part
1562/// document that represents it, bottom-up, memoised so a product reached from
1563/// several parents is built ONCE however many places embed it.
1564struct NestedBuild<'a, 'w> {
1565 assembly: &'a brep_kernel::StepAssembly,
1566 doc_name: &'a str,
1567 /// Where a CHILD library entry's document is written, shared with the
1568 /// top-level install loop so one part is one file at every level.
1569 writer: &'a mut PartWriter<'w>,
1570 /// `None` = this subtree carries no geometry at all, so nothing places it.
1571 memo: std::collections::HashMap<DocKey, Option<(String, serde_json::Value)>>,
1572 /// The non-rigid factor behind every baked [`DocKey::Leaf`] key, so the
1573 /// builder never has to reconstruct a matrix out of its own hash key.
1574 factors: std::collections::HashMap<PartKey, Mat4>,
1575 entries: usize,
1576 /// Bytes of part document embedded so far — the [`MAX_NESTED_BYTES`] charge.
1577 bytes: usize,
1578 failed_products: usize,
1579 baked_nonrigid: usize,
1580 first_error: Option<String>,
1581}
1582
1583impl NestedBuild<'_, '_> {
1584 /// The part document for `key`, built once and reused. `ancestors` is the
1585 /// recursion path — the cycle guard, and the depth the cap is measured on.
1586 ///
1587 /// A cyclic file gets ONE deterministic truncation: the memo keeps whichever
1588 /// path reached a node first, and that path's skipped back-edge is the one
1589 /// every embedding sees. Deterministic and finite is the whole contract for
1590 /// input that is malformed by construction.
1591 fn document(
1592 &mut self,
1593 key: DocKey,
1594 ancestors: &mut Vec<usize>,
1595 ) -> Result<Option<(String, serde_json::Value)>, String> {
1596 if let Some(hit) = self.memo.get(&key) {
1597 return Ok(hit.clone());
1598 }
1599 if ancestors.len() >= MAX_NESTED_DEPTH {
1600 return Err(format!(
1601 "nested import: sub-assembly nesting deeper than {MAX_NESTED_DEPTH} levels \
1602 (import as bodies, or import flat)"
1603 ));
1604 }
1605 let built = match key {
1606 DocKey::Leaf(part) => self.leaf_document(part),
1607 DocKey::Assembly(product) => {
1608 ancestors.push(product);
1609 let built = self.assembly_document(product, ancestors);
1610 ancestors.pop();
1611 built
1612 }
1613 }?;
1614 self.memo.insert(key, built.clone());
1615 Ok(built)
1616 }
1617
1618 /// A geometry-bearing product as the §3.2 part document — the same one the
1619 /// flat lane installs, built by the same helper, so a depth-1 nested import
1620 /// and a flat one store byte-identical entries.
1621 fn leaf_document(
1622 &mut self,
1623 key: PartKey,
1624 ) -> Result<Option<(String, serde_json::Value)>, String> {
1625 let product = self
1626 .assembly
1627 .products
1628 .iter()
1629 .find(|product| product.pd_ref == key.0)
1630 .expect("every key names a product of this assembly");
1631 if product.bodies.is_empty() {
1632 return Ok(None);
1633 }
1634 let factor = self.factors.get(&key).copied();
1635 self.spend_entry()?;
1636 native_part_document(product, factor.as_ref(), self.doc_name).map(Some)
1637 }
1638
1639 /// An assembly-node product as a rigid sub-assembly document: its OWN bodies
1640 /// as plain native IMPORT3D features (the interior-node geometry Phase 1
1641 /// could only make a SIBLING of its own children), one ACOMP per child
1642 /// occurrence, and the children's documents in this level's own
1643 /// `partsLibrary`.
1644 ///
1645 /// The entries carry NO snapshot. An entry with an unreadable snapshot heals
1646 /// from its embedded document (`assembly_component.rs`'s SELF-HEAL lane),
1647 /// and for a native part that heal is a decode + re-encode — so the level
1648 /// above bakes this whole subtree into ITS snapshot on insert, and these
1649 /// inner caches would only ever be rebuilt to be thrown away.
1650 fn assembly_document(
1651 &mut self,
1652 product: usize,
1653 ancestors: &mut Vec<usize>,
1654 ) -> Result<Option<(String, serde_json::Value)>, String> {
1655 let node = &self.assembly.products[product];
1656 let mut library = serde_json::Map::new();
1657 let mut features: Vec<serde_json::Value> = Vec::new();
1658
1659 // The node's own bodies first, matching the flat lane's "a node before
1660 // its children" emit order.
1661 if !node.bodies.is_empty() {
1662 let payload = brep_kernel::native_import_payload_with_appearance(
1663 "IMPORT3D1",
1664 &node.bodies,
1665 &node.appearances,
1666 )
1667 .map_err(|error| format!("part '{}': {error}", part_name(node, self.doc_name)))?;
1668 features.push(serde_json::json!({
1669 "type": "IMPORT3D",
1670 "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
1671 "persistentData": {},
1672 }));
1673 }
1674
1675 // One ACOMP per child occurrence, children by ascending `edge_ref`.
1676 let mut rows: Vec<(DocKey, Mat4, Vec<usize>)> = Vec::new();
1677 let mut bakes = 0usize;
1678 self.place_children(product, ancestors, &mut rows, &mut bakes);
1679 self.baked_nonrigid += bakes;
1680 let mut names: std::collections::HashMap<DocKey, String> =
1681 std::collections::HashMap::new();
1682 // `add_part_to_library`'s content reuse, applied to this level's block:
1683 // two products that are the SAME geometry collapse to one entry (§3.5's
1684 // free dedup), and every instance of either references it.
1685 let mut by_signature: std::collections::HashMap<String, String> =
1686 std::collections::HashMap::new();
1687 let mut components = 0usize;
1688 // The occurrence chain is not needed at this level: a sub-assembly's
1689 // own ACOMPs live in ITS document, which the open document's PMI never
1690 // names (an annotation pinned below a root child has no top-level
1691 // component — `merge_assembly_pmi` reports it).
1692 for (key, pose, _chain) in rows {
1693 let name = match names.get(&key) {
1694 Some(name) => name.clone(),
1695 None => {
1696 let built = match self.document(key, ancestors) {
1697 Ok(Some(built)) => built,
1698 Ok(None) => continue,
1699 Err(error) => {
1700 self.failed_products += 1;
1701 note(&mut self.first_error, error);
1702 continue;
1703 }
1704 };
1705 let serialized = built.1.to_string();
1706 let signature = document_signature(&serialized);
1707 let name = match by_signature.get(&signature) {
1708 Some(name) => name.clone(),
1709 None => {
1710 // Charged HERE, at the embedding, because that is
1711 // where a product stored once per level multiplies.
1712 self.spend_bytes(serialized.len())?;
1713 // Unique WITHIN this level's library — parent and
1714 // child libraries are independent, so a name
1715 // taken upstairs is free down here.
1716 let name = unique_entry_name(&library, &built.0);
1717 // A nested child is a part like any other: it gets
1718 // its own store document and a REAL sourceKey, so
1719 // Open Part and update-components work the same way
1720 // however deep it sits.
1721 let source_key =
1722 self.writer.key_for(&name, &serialized, &signature);
1723 library.insert(
1724 name.clone(),
1725 serde_json::json!({
1726 "sourceKey": source_key,
1727 "sourceSignature": signature.clone(),
1728 "document": built.1,
1729 "snapshot": "",
1730 }),
1731 );
1732 by_signature.insert(signature, name.clone());
1733 name
1734 }
1735 };
1736 names.insert(key, name.clone());
1737 name
1738 }
1739 };
1740 let Ok(transform) = brep_kernel::AffineTransform::new(pose) else {
1741 note(
1742 &mut self.first_error,
1743 format!("sub-assembly '{name}': occurrence pose is not an affine"),
1744 );
1745 continue;
1746 };
1747 components += 1;
1748 features.push(serde_json::json!({
1749 "type": "ACOMP",
1750 "inputParams": {
1751 // Its OWN counter, so the ids read `ACOMP1..n` whether or
1752 // not this node also owns bodies. (The id must match
1753 // `ACOMP<digits>`: it IS the namespace prefix.)
1754 "id": format!("ACOMP{components}"),
1755 "partName": name,
1756 "transform": brep_kernel::transform_to_pose_params(&transform),
1757 // Written EXPLICITLY rather than left to the kernel's
1758 // auto-ground rule, which keys on ABSENCE: the first
1759 // component of an assembly is grounded, and every other one
1760 // must not be, or the next solve is over-constrained.
1761 "isFixed": components == 1,
1762 },
1763 "persistentData": {},
1764 }));
1765 }
1766
1767 // A node whose whole subtree failed to produce geometry places nothing.
1768 // Returning `None` rather than a feature-less document matters: an empty
1769 // document is a hard error inside `add_part_to_library`, which would turn
1770 // "there was nothing here" into "the import failed".
1771 if features.is_empty() {
1772 return Ok(None);
1773 }
1774 self.spend_entry()?;
1775 let mut document =
1776 serde_json::json!({ "partsLibrary": library, "features": features });
1777 // A sub-assembly is a part too: its own `PRODUCT.id` is the part number
1778 // the level above exports it under, and its own PMI — the annotations
1779 // on the bodies IT owns, not its children's — is its document's.
1780 if let Some(attributes) = part_attributes(node) {
1781 document[PART_ATTRIBUTES] = attributes;
1782 }
1783 if let Some(pmi) = &node.pmi {
1784 if let Ok(block) = serde_json::to_value(pmi) {
1785 document["pmi"] = block;
1786 }
1787 }
1788 Ok(Some((part_name(node, self.doc_name), document)))
1789 }
1790
1791 /// The child occurrences of `product`, as `(document key, pose, occurrence
1792 /// chain)` rows in the kernel walk's order — ascending `edge_ref`, with the
1793 /// same ancestor cycle guard. The pose is the occurrence's own child→parent
1794 /// placement: nesting is precisely what stops it having to be composed.
1795 ///
1796 /// The chain is one edge long here by construction: a nested import's rows
1797 /// are the ROOT's own children, and everything below one of them is folded
1798 /// into that child's document.
1799 fn place_children(
1800 &mut self,
1801 product: usize,
1802 ancestors: &[usize],
1803 rows: &mut Vec<(DocKey, Mat4, Vec<usize>)>,
1804 bakes: &mut usize,
1805 ) {
1806 let mut children: Vec<&brep_kernel::StepOccurrence> = self
1807 .assembly
1808 .occurrences
1809 .iter()
1810 .filter(|occurrence| occurrence.parent == product)
1811 .collect();
1812 children.sort_by_key(|occurrence| occurrence.edge_ref);
1813 for occurrence in children {
1814 if ancestors.contains(&occurrence.child) {
1815 note(
1816 &mut self.first_error,
1817 format!(
1818 "occurrence #{} closes a cycle in the product structure and was skipped",
1819 occurrence.edge_ref
1820 ),
1821 );
1822 continue;
1823 }
1824 let child = &self.assembly.products[occurrence.child];
1825 let is_assembly = self
1826 .assembly
1827 .occurrences
1828 .iter()
1829 .any(|edge| edge.parent == occurrence.child);
1830 if occurrence.rigid {
1831 let key = if is_assembly {
1832 DocKey::Assembly(occurrence.child)
1833 } else {
1834 DocKey::Leaf((child.pd_ref, NO_FACTOR))
1835 };
1836 rows.push((key, occurrence.placement, vec![occurrence.edge_ref]));
1837 continue;
1838 }
1839 // §3.4 on a single edge: a leaf bakes its non-rigid factor into its
1840 // own part, exactly as the flat lane does with the composed pose.
1841 match split_rigid(&occurrence.placement) {
1842 Ok((rigid, factor)) if is_identity(&factor) => {
1843 let key = if is_assembly {
1844 DocKey::Assembly(occurrence.child)
1845 } else {
1846 DocKey::Leaf((child.pd_ref, NO_FACTOR))
1847 };
1848 rows.push((key, rigid, vec![occurrence.edge_ref]));
1849 }
1850 // A mirrored/scaled SUB-ASSEMBLY would have to push its factor
1851 // down through a whole document tree, rewriting every level's
1852 // poses. Nothing in the corpus does it, and a wrong answer here
1853 // would be a silently mis-handed assembly: skip and say so, so
1854 // the user can re-import flat (which bakes it correctly).
1855 Ok(_) if is_assembly => {
1856 note(
1857 &mut self.first_error,
1858 format!(
1859 "occurrence #{} places sub-assembly '{}' with a non-rigid transform, \
1860 which a nested import cannot represent — import flat instead",
1861 occurrence.edge_ref,
1862 part_name(child, self.doc_name)
1863 ),
1864 );
1865 }
1866 Ok((rigid, factor)) => {
1867 *bakes += 1;
1868 let key = (child.pd_ref, factor_key(&factor));
1869 self.factors.insert(key, factor);
1870 rows.push((DocKey::Leaf(key), rigid, vec![occurrence.edge_ref]));
1871 }
1872 Err(error) => note(&mut self.first_error, error),
1873 }
1874 }
1875 }
1876
1877 /// Charge one built part document against [`MAX_NESTED_ENTRIES`].
1878 fn spend_entry(&mut self) -> Result<(), String> {
1879 self.entries += 1;
1880 if self.entries > MAX_NESTED_ENTRIES {
1881 return Err(format!(
1882 "nested import: more than {MAX_NESTED_ENTRIES} distinct parts \
1883 (import as bodies, or import flat)"
1884 ));
1885 }
1886 Ok(())
1887 }
1888
1889 /// Charge one embedded part document against [`MAX_NESTED_BYTES`].
1890 fn spend_bytes(&mut self, bytes: usize) -> Result<(), String> {
1891 self.bytes = self.bytes.saturating_add(bytes);
1892 if self.bytes > MAX_NESTED_BYTES {
1893 return Err(format!(
1894 "nested import: the embedded sub-assembly documents exceed \
1895 {} MB (import as bodies, or import flat)",
1896 MAX_NESTED_BYTES / (1024 * 1024)
1897 ));
1898 }
1899 Ok(())
1900 }
1901}
1902
1903/// A part name not yet used in THIS level's library: `requested`, else
1904/// `requested-2`, `requested-3`, … — the kernel `parts_library::unique_name`
1905/// convention, applied to an embedded block the kernel never sees inserted.
1906fn unique_entry_name(library: &serde_json::Map<String, serde_json::Value>, requested: &str) -> String {
1907 if !library.contains_key(requested) {
1908 return requested.to_string();
1909 }
1910 (2..)
1911 .map(|counter| format!("{requested}-{counter}"))
1912 .find(|candidate| !library.contains_key(candidate))
1913 .expect("the counter loop is unbounded")
1914}
1915
1916/// Keep the FIRST thing that went wrong (the report carries one, and the first
1917/// is the one that explains the rest).
1918fn note(slot: &mut Option<String>, error: String) {
1919 if slot.is_none() {
1920 *slot = Some(error);
1921 }
1922}
1923
1924/// Encode one product as a parts-library entry and return the EFFECTIVE entry
1925/// name the instances must reference (`add_part_to_library` disambiguates a name
1926/// clash and REUSES an entry with identical content, which is where cross-import
1927/// dedup comes from).
1928///
1929/// `factor`, when present, is the non-rigid part of an occurrence's placement:
1930/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
1931fn build_library_entry(
1932 product: &brep_kernel::StepProduct,
1933 factor: Option<&Mat4>,
1934 doc_name: &str,
1935 writer: &mut PartWriter<'_>,
1936) -> Result<String, String> {
1937 let (name, document) = native_part_document(product, factor, doc_name)?;
1938 install_part(&name, &document, writer)
1939}
1940
1941/// The §3.2 part document for one product's OWN bodies: ONE IMPORT3D whose only
1942/// input is the native payload, plus the library name it wants. No STEP text is
1943/// stored anywhere — a rebuild of this part is a base64 decode, not a re-parse.
1944///
1945/// `factor`, when present, is the non-rigid part of an occurrence's placement:
1946/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
1947///
1948/// Split out from [`build_library_entry`] because the nested lane needs the
1949/// DOCUMENT before it installs anything — a leaf's document is embedded in its
1950/// parent's `partsLibrary`, where there is no `add_part_to_library` to call.
1951/// One producer, so a leaf part is byte-identical however deep it lands.
1952fn native_part_document(
1953 product: &brep_kernel::StepProduct,
1954 factor: Option<&Mat4>,
1955 doc_name: &str,
1956) -> Result<(String, serde_json::Value), String> {
1957 let mut name = part_name(product, doc_name);
1958 let bodies = match factor {
1959 None => product.bodies.clone(),
1960 Some(factor) => {
1961 let transform = brep_kernel::AffineTransform::new(*factor)
1962 .map_err(|error| format!("part '{name}': non-rigid factor: {error}"))?;
1963 let mirrored = transform.determinant3() < 0.0;
1964 name.push_str(if mirrored { " (mirrored)" } else { " (scaled)" });
1965 product
1966 .bodies
1967 .iter()
1968 .map(|body| {
1969 // A mirror MUST reverse orientation or `transform_brep`
1970 // refuses it (an unreversed reflection inverts the solid).
1971 brep_kernel::transform_brep(body, transform, mirrored)
1972 .map_err(|error| format!("part '{name}': {error}"))
1973 })
1974 .collect::<Result<Vec<_>, _>>()?
1975 }
1976 };
1977 // The product's STEP colours ride into the payload with the geometry (the
1978 // snapshot captures the records the stamp writes), so a coloured part keeps
1979 // its colour through the parts library and every reload.
1980 let payload = brep_kernel::native_import_payload_with_appearance(
1981 "IMPORT3D1",
1982 &bodies,
1983 &product.appearances,
1984 )
1985 .map_err(|error| format!("part '{name}': {error}"))?;
1986 let mut document = serde_json::json!({
1987 "features": [{
1988 "type": "IMPORT3D",
1989 "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
1990 "persistentData": {},
1991 }]
1992 });
1993 if let Some(attributes) = part_attributes(product) {
1994 document[PART_ATTRIBUTES] = attributes;
1995 }
1996 // The part's own PMI, lifted once for the PART (`assembly_pmi.rs`). Its
1997 // references already name what the `IMPORT3D1` feature above stamps, and a
1998 // baked factor transforms the bodies without reordering their faces, so a
1999 // mirrored variant's names hold too.
2000 if let Some(pmi) = &product.pmi {
2001 if let Ok(block) = serde_json::to_value(pmi) {
2002 document["pmi"] = block;
2003 }
2004 }
2005 Ok((name, document))
2006}
2007
2008/// The BOM attribute record an imported product's document carries: its STEP
2009/// `PRODUCT.id` as `Part_Number`, or `None` when the file gave it none.
2010///
2011/// This is the OTHER half of `io/step/export_tree.rs`, which writes a part's
2012/// `partAttributes.Part_Number` back out as `PRODUCT.id` — the identity a
2013/// downstream PDM keys on. Without it an imported id died at the import: the
2014/// document had no part number, so a re-export fell back to the library entry's
2015/// `sourceKey` and the vendor's own part numbers were replaced by our file
2016/// names on the first round trip.
2017///
2018/// It is only ever set on a document being MINTED here (a fresh part document
2019/// for one product), so it cannot overwrite a part number a user typed: a part
2020/// document that already exists is reused by
2021/// [`add_part_to_library`](brep_kernel::add_part_to_library)'s content match and
2022/// never rebuilt through this path.
2023///
2024/// Trimmed and blank-filtered to match the reader's own `part_number`, so a
2025/// `PRODUCT(' ','bolt',…)` does not mint a whitespace part number that would
2026/// then export as one.
2027fn part_attributes(product: &brep_kernel::StepProduct) -> Option<serde_json::Value> {
2028 let number = product.id.trim();
2029 if number.is_empty() {
2030 return None;
2031 }
2032 Some(serde_json::json!({ brep_kernel::PART_NUMBER: number }))
2033}
2034
2035/// Install a part document as a parts-library entry of the OPEN document and
2036/// return the EFFECTIVE entry name the instances must reference
2037/// (`add_part_to_library` disambiguates a name clash and REUSES an entry with
2038/// identical content, which is where cross-import dedup comes from).
2039///
2040/// The `sourceKey` comes from the [`PartSink`]: an imported part is written to
2041/// the store as its own document and carries a REAL key, exactly like a part
2042/// inserted from the parts library, so there is no second kind of part. A sink
2043/// that declines (no store, or a failed write) yields `""` — the embedded-only
2044/// entry this lane used to produce unconditionally, and the case
2045/// `UpdateComponents` already skips.
2046fn install_part(
2047 name: &str,
2048 document: &serde_json::Value,
2049 writer: &mut PartWriter<'_>,
2050) -> Result<String, String> {
2051 let document = document.to_string();
2052 let signature = document_signature(&document);
2053 let source_key = writer.key_for(name, &document, &signature);
2054 brep_kernel::add_part_to_library_impl(name, &source_key, &signature, &document)
2055 .map_err(|error| format!("part '{name}': {error}"))
2056}
2057
2058/// Where an imported assembly's unique parts are written, so each becomes a
2059/// document in its own right rather than a payload embedded in one assembly.
2060///
2061/// A trait, and not a `&dyn ModelStore`, because the store lives in `BREP_app`
2062/// and this crate is BELOW it — `BREP_app` depends on `BREP_render`, so naming
2063/// the store here would be a dependency cycle. The import therefore asks for a
2064/// key and the app answers with one, which is also what keeps the destination
2065/// (and any prompt for it) entirely the app's business.
2066pub trait PartSink {
2067 /// Store `document_json` under a name derived from `part_name` and return
2068 /// the stable key it can be read back by. `None` declines — no store, or a
2069 /// write that failed — and the entry stays embedded-only.
2070 fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String>;
2071}
2072
2073/// The sink that stores nothing: every entry stays embedded-only. The default
2074/// for headless callers and tests, which have no store to write to.
2075pub struct EmbeddedOnly;
2076
2077impl PartSink for EmbeddedOnly {
2078 fn store_part(&mut self, _part_name: &str, _document_json: &str) -> Option<String> {
2079 None
2080 }
2081}
2082
2083/// A [`PartSink`] plus the CONTENT DEDUP that must ride with it.
2084///
2085/// `add_part_to_library` reuses an entry whose `(sourceKey, sourceSignature)`
2086/// both match, which is where §3.5's free dedup came from while every imported
2087/// part carried the same empty key. Give each part its own key and that reuse
2088/// stops: the same product under two `PRODUCT_DEFINITION`s would become two
2089/// entries AND two identical files.
2090///
2091/// So the dedup moves in front of the write, keyed on the document signature
2092/// alone. Identical content is written ONCE and every occurrence of it gets the
2093/// SAME key — which then makes `add_part_to_library`'s own `(key, signature)`
2094/// reuse fire exactly as before. Dedup ACROSS imports keeps working for the
2095/// same reason: a re-import derives the same file name, so the same key and
2096/// signature come back and the resident entry is reused.
2097struct PartWriter<'a> {
2098 sink: &'a mut dyn PartSink,
2099 by_signature: std::collections::HashMap<String, String>,
2100}
2101
2102impl<'a> PartWriter<'a> {
2103 fn new(sink: &'a mut dyn PartSink) -> Self {
2104 Self {
2105 sink,
2106 by_signature: std::collections::HashMap::new(),
2107 }
2108 }
2109
2110 /// The `sourceKey` for a part with this content — writing it exactly once
2111 /// however many products share it.
2112 fn key_for(&mut self, name: &str, document_json: &str, signature: &str) -> String {
2113 if let Some(key) = self.by_signature.get(signature) {
2114 return key.clone();
2115 }
2116 let key = self
2117 .sink
2118 .store_part(name, document_json)
2119 .unwrap_or_default();
2120 self.by_signature.insert(signature.to_string(), key.clone());
2121 key
2122 }
2123}
2124
2125/// An sRGB triple in 0..=1 as the 8-bit channels `#RRGGBB` holds — the form
2126/// [`brep_kernel::StepColors`] takes, and the same `round(c * 255)` conversion
2127/// `brep_kernel::ImportedColor::to_hex` uses, so a colour written to a STEP file
2128/// is the colour the metadata record spells.
2129fn srgb_bytes(rgb: [f64; 3]) -> [u8; 3] {
2130 rgb.map(|channel| (channel.clamp(0.0, 1.0) * 255.0).round() as u8)
2131}
2132
2133/// The library name for a product: its `PRODUCT.name`, else a stem built from
2134/// the imported document's name so an unnamed product is still identifiable.
2135fn part_name(product: &brep_kernel::StepProduct, doc_name: &str) -> String {
2136 let named = product.name.trim();
2137 if !named.is_empty() {
2138 return named.to_string();
2139 }
2140 match doc_name.trim() {
2141 "" => format!("part-{}", product.pd_ref),
2142 stem => format!("{stem}-part-{}", product.pd_ref),
2143 }
2144}
2145
2146/// The dialog's counts, taken from the SAME walk the import runs, so the numbers
2147/// the user was shown are the numbers they get (bar an encode failure, and bar
2148/// the extra entry a non-rigid occurrence bakes).
2149pub(super) fn probe_counts(assembly: &brep_kernel::StepAssembly) -> StepAssemblyProbe {
2150 let mut parts = std::collections::HashSet::new();
2151 let mut instances = 0usize;
2152 let mut nested_depth = 0usize;
2153 for placed in compose_world_occurrences(assembly) {
2154 let product = &assembly.products[placed.product];
2155 if product.bodies.is_empty() {
2156 continue;
2157 }
2158 parts.insert(product.pd_ref);
2159 instances += 1;
2160 nested_depth = nested_depth.max(placed.depth);
2161 }
2162 StepAssemblyProbe {
2163 parts: parts.len(),
2164 instances,
2165 nested_depth,
2166 }
2167}
2168
2169/// Depth-first from the roots, composing each occurrence's child→parent
2170/// placement into a world transform — the consumer half of `read_step_assembly`,
2171/// which deliberately transforms nothing.
2172///
2173/// Emit order, child ordering (by `edge_ref`) and the ancestor cycle guard mirror
2174/// the kernel's own `walk_occurrences`, which is what makes the components this
2175/// lane produces the same solids, in the same order, as the flat lane's — the
2176/// kernel asserts that equivalence BIT-for-bit
2177/// (`step_import/tests/assembly_structure.rs`), and
2178/// `structured_import_matches_the_flat_lane_geometry` below re-asserts it from
2179/// this side, where a divergence would actually land.
2180fn compose_world_occurrences(assembly: &brep_kernel::StepAssembly) -> Vec<PlacedProduct> {
2181 struct Node {
2182 placed: PlacedProduct,
2183 ancestors: Vec<usize>,
2184 }
2185 let mut out = Vec::new();
2186 let mut stack: Vec<Node> = assembly
2187 .roots
2188 .iter()
2189 .rev()
2190 .map(|&product| Node {
2191 placed: PlacedProduct {
2192 product,
2193 world: MAT4_IDENTITY,
2194 depth: 0,
2195 rigid_path: true,
2196 chain: Vec::new(),
2197 },
2198 ancestors: vec![product],
2199 })
2200 .collect();
2201 while let Some(node) = stack.pop() {
2202 let (product, world, depth, rigid_path, chain) = (
2203 node.placed.product,
2204 node.placed.world,
2205 node.placed.depth,
2206 node.placed.rigid_path,
2207 node.placed.chain.clone(),
2208 );
2209 out.push(node.placed);
2210 let mut children: Vec<&brep_kernel::StepOccurrence> = assembly
2211 .occurrences
2212 .iter()
2213 .filter(|occurrence| occurrence.parent == product)
2214 .collect();
2215 children.sort_by_key(|occurrence| occurrence.edge_ref);
2216 for occurrence in children.into_iter().rev() {
2217 if node.ancestors.contains(&occurrence.child) {
2218 continue; // the cycle guard the kernel's walk applies
2219 }
2220 let mut ancestors = node.ancestors.clone();
2221 ancestors.push(occurrence.child);
2222 let mut child_chain = chain.clone();
2223 child_chain.push(occurrence.edge_ref);
2224 stack.push(Node {
2225 placed: PlacedProduct {
2226 product: occurrence.child,
2227 world: mat4_mul(&world, &occurrence.placement),
2228 depth: depth + 1,
2229 // The kernel's per-edge rigidity flag, carried down the path:
2230 // a composed pose is a component pose only when every edge
2231 // on the way to it was one.
2232 rigid_path: rigid_path && occurrence.rigid,
2233 chain: child_chain,
2234 },
2235 ancestors,
2236 });
2237 }
2238 }
2239 out
2240}
2241
2242const MAT4_IDENTITY: Mat4 = [
2243 1.0, 0.0, 0.0, 0.0, //
2244 0.0, 1.0, 0.0, 0.0, //
2245 0.0, 0.0, 1.0, 0.0, //
2246 0.0, 0.0, 0.0, 1.0,
2247];
2248
2249/// Row-major 4×4 product `a · b`.
2250use crate::geometry3d::mat4_mul_row_major as mat4_mul;
2251
2252/// Split a non-rigid world placement into `world = rigid · factor`, where
2253/// `rigid` is a component pose (rotation + translation, det +1) and `factor` is
2254/// a purely linear residue carrying the mirror/scale/shear.
2255///
2256/// Gram-Schmidt on the linear block's columns gives `A = Q·U` with `U` upper
2257/// triangular and positively-diagonalled; when `Q` came out left-handed the pair
2258/// is re-signed through `D = diag(-1, 1, 1)` (`Q' = Q·D`, `U' = D·U`, still
2259/// `Q'U' = A`) so the ROTATION is a rotation and the reflection rides in the
2260/// factor. A mirror composed with a rotation therefore yields the same factor
2261/// whatever the rotation, which keeps every such instance on ONE baked part.
2262fn split_rigid(world: &Mat4) -> Result<(Mat4, Mat4), String> {
2263 let column = |index: usize| [world[index], world[4 + index], world[8 + index]];
2264 let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
2265 let axpy = |a: [f64; 3], scale: f64, b: [f64; 3]| {
2266 [a[0] - scale * b[0], a[1] - scale * b[1], a[2] - scale * b[2]]
2267 };
2268 let (a1, a2, a3) = (column(0), column(1), column(2));
2269
2270 let r11 = dot(a1, a1).sqrt();
2271 let mut q1 = normalize(a1, r11)?;
2272 let r12 = dot(q1, a2);
2273 let v2 = axpy(a2, r12, q1);
2274 let r22 = dot(v2, v2).sqrt();
2275 let q2 = normalize(v2, r22)?;
2276 let r13 = dot(q1, a3);
2277 let r23 = dot(q2, a3);
2278 let v3 = axpy(axpy(a3, r13, q1), r23, q2);
2279 let r33 = dot(v3, v3).sqrt();
2280 let q3 = normalize(v3, r33)?;
2281
2282 // det Q = q1 · (q2 × q3); -1 means Q is a reflection, not a rotation.
2283 let cross = [
2284 q2[1] * q3[2] - q2[2] * q3[1],
2285 q2[2] * q3[0] - q2[0] * q3[2],
2286 q2[0] * q3[1] - q2[1] * q3[0],
2287 ];
2288 let (mut r11, mut r12, mut r13) = (r11, r12, r13);
2289 if dot(q1, cross) < 0.0 {
2290 q1 = [-q1[0], -q1[1], -q1[2]];
2291 r11 = -r11;
2292 r12 = -r12;
2293 r13 = -r13;
2294 }
2295 let rigid = [
2296 q1[0], q2[0], q3[0], world[3], //
2297 q1[1], q2[1], q3[1], world[7], //
2298 q1[2], q2[2], q3[2], world[11], //
2299 0.0, 0.0, 0.0, 1.0,
2300 ];
2301 let factor = [
2302 r11, r12, r13, 0.0, //
2303 0.0, r22, r23, 0.0, //
2304 0.0, 0.0, r33, 0.0, //
2305 0.0, 0.0, 0.0, 1.0,
2306 ];
2307 Ok((rigid, factor))
2308}
2309
2310/// Unit vector, or a clear error for the degenerate column a near-singular
2311/// placement produces (skipped and counted, never fatal).
2312fn normalize(vector: [f64; 3], length: f64) -> Result<[f64; 3], String> {
2313 if !(length > 1e-12) || !length.is_finite() {
2314 return Err("occurrence placement is singular (a degenerate axis)".into());
2315 }
2316 Ok([vector[0] / length, vector[1] / length, vector[2] / length])
2317}
2318
2319/// Is this affine the identity to 1e-9 — the tolerance the kernel's own
2320/// rigidity gate uses?
2321fn is_identity(matrix: &Mat4) -> bool {
2322 matrix
2323 .iter()
2324 .zip(MAT4_IDENTITY.iter())
2325 .all(|(value, want)| (value - want).abs() <= 1e-9)
2326}
2327
2328/// The linear block of a baked factor as an exact bit key — two occurrences
2329/// share a baked part only when their factor is bit-identical, so a wrong-handed
2330/// reuse is not reachable through rounding.
2331fn factor_key(factor: &Mat4) -> [u64; 9] {
2332 let mut key = [0u64; 9];
2333 for (slot, index) in key.iter_mut().zip([0, 1, 2, 4, 5, 6, 8, 9, 10]) {
2334 *slot = factor[index].to_bits();
2335 }
2336 key
2337}
2338
2339/// The product, and the placement of it, that holds a board document's board
2340/// in a STRUCTURED export. The board's bodies keep their own names inside it
2341/// (`PCB_Board`, `PCB_F.Cu/GND#3`). A component's reference designator is
2342/// never taken for an occurrence label when it is this word.
2343const BOARD_OCCURRENCE: &str = "PCB";
2344
2345/// A `PRODUCT.id` a receiving system can use. A library part with no BOM part
2346/// number is identified by the `sourceKey` it was imported from, which is an
2347/// ABSOLUTE path on the exporting machine (`/tmp/…/kicad/symbols/lm358.nbrep`):
2348/// meaningless anywhere else, and a leak of the user's directory layout into
2349/// every file they send. Such an id becomes the file's stem (`lm358`), or the
2350/// product's name when the path has no usable stem. An id with no path
2351/// separator — a real part number — is kept as it is.
2352fn portable_product_id(id: &str, name: &str) -> String {
2353 const SEPARATORS: [char; 2] = ['/', '\\'];
2354 if !id.contains(SEPARATORS) {
2355 return id.to_string();
2356 }
2357 let file = id.rsplit(SEPARATORS).next().unwrap_or_default();
2358 let stem = file.rsplit_once('.').map_or(file, |(stem, _)| stem);
2359 if stem.is_empty() {
2360 name.to_string()
2361 } else {
2362 stem.to_string()
2363 }
2364}
2365