brep_kernel/io/step/assembly.rs
1//! STRUCTURED STEP export: write a product structure, not just bodies.
2//!
3//! The flat writer ([`super::export_step_report_named`]) puts every body of the
4//! document into ONE `PRODUCT`. That is the right answer for a part, and the
5//! wrong one for an assembly: a nested assembly came out as a bag of bodies at
6//! their world positions, with the parts library, the instance count and the
7//! hierarchy all discarded.
8//!
9//! This module is the other answer. It takes a [`StepAssemblyExport`] — one
10//! [`StepExportProduct`] per distinct part holding that part's bodies IN ITS OWN
11//! LOCAL FRAME, plus one [`StepExportOccurrence`] per placement — and writes the
12//! AP242 graph the importer (`io/step_import/`) reads back:
13//!
14//! ```text
15//! PRODUCT -> PRODUCT_DEFINITION_FORMATION -> PRODUCT_DEFINITION
16//! -> PRODUCT_DEFINITION_SHAPE -> SHAPE_DEFINITION_REPRESENTATION
17//! -> ADVANCED_BREP_SHAPE_REPRESENTATION (the part's own bodies)
18//!
19//! NEXT_ASSEMBLY_USAGE_OCCURRENCE(parent_pd, child_pd)
20//! <- PRODUCT_DEFINITION_SHAPE('NAUO PRDDFN')
21//! <- CONTEXT_DEPENDENT_SHAPE_REPRESENTATION
22//! -> ( REPRESENTATION_RELATIONSHIP(child_rep, parent_rep)
23//! REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(
24//! ITEM_DEFINED_TRANSFORMATION(identity_axis, placement_axis) )
25//! SHAPE_REPRESENTATION_RELATIONSHIP() )
26//! ```
27//!
28//! # The placement convention, and why it is copied rather than chosen
29//!
30//! A reader composes `T = M(item_2) · M(item_1)⁻¹` to map `rep_1` into `rep_2`.
31//! With `rep_1` the CHILD and `item_1` the identity axis, `T` is simply
32//! `M(item_2)` — the child's frame expressed in the parent. That ordering is
33//! taken from the `as1-ug-214` vendor fixture
34//! (`REPRESENTATION_RELATIONSHIP(' ',' ',#213 /* rod */,#219 /* rod_assem */)`
35//! with `ITEM_DEFINED_TRANSFORMATION(' ',' ',#1041 /* identity */,#1109)`), NOT
36//! from our own importer: `resolve_rep_rel_transform` reorients using the
37//! child's known root representation, so a self round-trip would have passed
38//! with the ordering reversed and told us nothing.
39//!
40//! For the same reason `item_1`/`item_2` are ITEMS of the reps they belong to —
41//! the identity axis is the first item of every representation this writer
42//! emits, and each occurrence's placement axis is pushed into its PARENT's item
43//! list. A conformance checker requires exactly that.
44//!
45//! # Naming, and what PMI resolves against
46//!
47//! A part's bodies, faces and edges keep the part's OWN names — `Extrude1_top`,
48//! not `ACOMP3:Extrude1_top` — because they are written into the part's product,
49//! where the component namespace does not apply. The document still refers to
50//! them by the namespaced name, so [`StepAssemblyExport::occurrence_paths`]
51//! walks the graph and registers every entity under EVERY chained occurrence
52//! path that reaches it (`ACOMP3:`, `ACOMP5:ACOMP1:`), with the vertex points
53//! moved into root space so a `{body}@x,y,z` reference still matches. Two
54//! instances of one part share the part's entities, so `ACOMP3:top` and
55//! `ACOMP4:top` resolve to the SAME `ADVANCED_FACE`.
56//!
57//! They are not the same ANNOTATION, though, and PMI is written accordingly:
58//!
59//! - a PART's own annotations ([`StepExportProduct::pmi`], from the part
60//! document's `pmi` block) are written into that part's product, with the
61//! part's own names and its own draughting model — once, however many
62//! instances place it;
63//! - the ROOT document's annotations are written through the occurrence paths,
64//! and a reference that reaches a part through an occurrence hangs its
65//! `SHAPE_ASPECT` off THAT occurrence's `PRODUCT_DEFINITION_SHAPE` (the
66//! `'NAUO PRDDFN'` one), not the part's. The `GEOMETRIC_ITEM_SPECIFIC_USAGE`
67//! still points at the part's face; only the owner says which instance is
68//! meant, and it is the only place that can say it.
69//!
70//! `io/step_import/assembly_pmi.rs` reads exactly that distinction back, which
71//! is what makes an assembly's PMI survive export → import unchanged.
72
73use super::{
74 finish_step_file, id_list, mat4_mul, pmi, step_string, styles, write_file_contexts,
75 write_product, write_product_geometry, Mat4, StepColors, StepExportReport, StepItemOwner,
76 StepNameMaps, StepPmi, StepWriter, MAT4_IDENTITY,
77};
78use crate::feature_pipeline::pmi::{PmiReport, PmiState};
79use crate::{BrepSolid, Vec3};
80
81/// One product of an exported structure: a part, a sub-assembly, or the root
82/// document. `bodies` are in the product's OWN local frame — never posed.
83#[derive(Clone, Debug, Default)]
84pub struct StepExportProduct {
85 /// `PRODUCT.name` — the parts-library entry name, or the document name.
86 pub name: String,
87 /// `PRODUCT.id` — the vendor part number: a library part's BOM
88 /// `Part_Number` attribute, else its `sourceKey` (`export_tree.rs`). The
89 /// name is used when empty.
90 pub id: String,
91 /// This product's own solids and their part-local scene names. Empty for a
92 /// pure assembly node, which is then written as a bare `SHAPE_REPRESENTATION`.
93 pub bodies: Vec<(String, BrepSolid)>,
94 /// This product's OWN PMI — the part document's `pmi` block, resolved
95 /// against the part's own geometry (`export_tree.rs` runs it). Written
96 /// into THIS product, with the part's own names and its own draughting
97 /// model, which is where a structured import reads it back from.
98 pub pmi: Option<(PmiState, PmiReport)>,
99}
100
101/// One placement of `child` inside `parent` — a `NEXT_ASSEMBLY_USAGE_OCCURRENCE`.
102#[derive(Clone, Debug)]
103pub struct StepExportOccurrence {
104 /// The instance label: the placing component's id (`ACOMP3`). Written into
105 /// the NAUO's `reference_designator`, which is what the importer reads back
106 /// first, so an instance keeps its identity through the round trip.
107 pub designator: String,
108 /// Index into [`StepAssemblyExport::products`].
109 pub parent: usize,
110 /// Index into [`StepAssemblyExport::products`].
111 pub child: usize,
112 /// child-local -> parent-local, row-major affine. Must be RIGID: a mirrored
113 /// or scaled instance has no `AXIS2_PLACEMENT_3D` and is rejected rather
114 /// than silently written as its rotation part.
115 pub placement: Mat4,
116}
117
118/// A document's product structure, ready to write. Exactly one product must be
119/// a root (never an occurrence child) — the document itself.
120#[derive(Clone, Debug, Default)]
121pub struct StepAssemblyExport {
122 pub products: Vec<StepExportProduct>,
123 pub occurrences: Vec<StepExportOccurrence>,
124}
125
126/// How many occurrence paths the PMI alias walk will register before it stops.
127/// One path per instance is the honest count, and a real assembly has
128/// thousands at most; the cap only bounds a pathological diamond graph, whose
129/// path count is exponential in its depth.
130const MAX_OCCURRENCE_PATHS: usize = 100_000;
131
132impl StepAssemblyExport {
133 /// The single root product's index, with the graph checked on the way: every
134 /// occurrence in range, no self-placement, exactly one root, no cycle, every
135 /// product reachable, every placement rigid.
136 pub fn root(&self) -> Result<usize, String> {
137 if self.products.is_empty() {
138 return Err("export_step: an assembly needs at least one product".into());
139 }
140 let count = self.products.len();
141 let mut is_child = vec![false; count];
142 for occurrence in &self.occurrences {
143 if occurrence.parent >= count || occurrence.child >= count {
144 return Err(format!(
145 "export_step: occurrence '{}' names a product outside the structure",
146 occurrence.designator
147 ));
148 }
149 if occurrence.parent == occurrence.child {
150 return Err(format!(
151 "export_step: occurrence '{}' places a product inside itself",
152 occurrence.designator
153 ));
154 }
155 rigid(&occurrence.placement).map_err(|error| {
156 format!(
157 "export_step: occurrence '{}' placement: {error}",
158 occurrence.designator
159 )
160 })?;
161 is_child[occurrence.child] = true;
162 }
163 let roots: Vec<usize> = (0..count).filter(|index| !is_child[*index]).collect();
164 let [root] = roots.as_slice() else {
165 return Err(format!(
166 "export_step: an assembly needs exactly one root product, found {}",
167 roots.len()
168 ));
169 };
170 // Reachability doubles as the cycle check: a cycle makes every product
171 // on it a child, so an unreached product is either orphaned or looping.
172 let mut reached = vec![false; count];
173 let mut stack = vec![*root];
174 reached[*root] = true;
175 while let Some(product) = stack.pop() {
176 for occurrence in &self.occurrences {
177 if occurrence.parent == product && !reached[occurrence.child] {
178 reached[occurrence.child] = true;
179 stack.push(occurrence.child);
180 }
181 }
182 }
183 if let Some(lost) = reached.iter().position(|hit| !hit) {
184 return Err(format!(
185 "export_step: product '{}' is not reachable from the root",
186 self.products[lost].name
187 ));
188 }
189 Ok(*root)
190 }
191
192 /// Each product's occurrence namespaces ("ACOMP3:", "ACOMP3:ACOMP1:", and
193 /// "" for the root), sorted: the prefixes its colours resolve through.
194 pub(crate) fn occurrence_prefixes(&self, root: usize) -> Vec<Vec<String>> {
195 self.occurrence_paths(root)
196 .into_iter()
197 .map(|paths| {
198 let mut prefixes: Vec<String> = paths.into_iter().map(|path| path.prefix).collect();
199 prefixes.sort();
200 prefixes
201 })
202 .collect()
203 }
204
205 /// Every chained occurrence path that reaches each product: the component
206 /// namespace prefix the DOCUMENT knows its entities by, and the transform
207 /// into root space. The root itself gets one empty path at identity.
208 ///
209 /// Depth-first from the root, guarding the path's own ancestors, so a
210 /// structure that somehow still carries a cycle terminates.
211 fn occurrence_paths(&self, root: usize) -> Vec<Vec<OccurrencePath>> {
212 let mut paths: Vec<Vec<OccurrencePath>> = vec![Vec::new(); self.products.len()];
213 let mut total = 0usize;
214 let mut stack: Vec<(usize, OccurrencePath, Vec<usize>)> = vec![(
215 root,
216 OccurrencePath {
217 prefix: String::new(),
218 world: MAT4_IDENTITY,
219 last: None,
220 },
221 vec![root],
222 )];
223 while let Some((product, path, ancestors)) = stack.pop() {
224 if total >= MAX_OCCURRENCE_PATHS {
225 break;
226 }
227 total += 1;
228 for (slot, occurrence) in self.occurrences.iter().enumerate() {
229 if occurrence.parent != product || ancestors.contains(&occurrence.child) {
230 continue;
231 }
232 let mut ancestors = ancestors.clone();
233 ancestors.push(occurrence.child);
234 stack.push((
235 occurrence.child,
236 OccurrencePath {
237 prefix: format!("{}{}:", path.prefix, occurrence.designator),
238 world: mat4_mul(&path.world, &occurrence.placement),
239 last: Some(slot),
240 },
241 ancestors,
242 ));
243 }
244 paths[product].push(path);
245 }
246 paths
247 }
248}
249
250/// One way the document's geometry reaches a product: the component namespace
251/// that names it (`ACOMP5:ACOMP1:`, `""` at the root), the transform into root
252/// space, and the LAST occurrence on the way — the instance an annotation
253/// written against this namespace is an annotation on.
254#[derive(Clone)]
255struct OccurrencePath {
256 prefix: String,
257 world: Mat4,
258 /// Index into [`StepAssemblyExport::occurrences`]; `None` at the root.
259 last: Option<usize>,
260}
261
262/// A placement is rigid when its linear block is orthonormal with a positive
263/// determinant — the only kind an `AXIS2_PLACEMENT_3D` can express.
264fn rigid(matrix: &Mat4) -> Result<(), String> {
265 if matrix.iter().any(|value| !value.is_finite()) {
266 return Err("matrix is not finite".into());
267 }
268 let transform = crate::AffineTransform { elements: *matrix };
269 if transform.is_rigid(crate::RIGID_TOL) { return Ok(()); }
270 if transform.determinant3() < 0.0 {
271 return Err("matrix is left-handed (a mirrored instance)".into());
272 }
273 Err("matrix is not a rotation (mirrored or scaled)".into())
274}
275
276/// The `AXIS2_PLACEMENT_3D` expressing a rigid placement's frame: the origin is
277/// its translation, the axis its third linear COLUMN and the reference direction
278/// its first — the exact inverse of the importer's `frame_matrix`.
279fn write_placement_axis(writer: &mut StepWriter, matrix: &Mat4) -> Result<usize, String> {
280 super::write_placement(
281 writer,
282 Vec3::new(matrix[3], matrix[7], matrix[11]),
283 Vec3::new(matrix[2], matrix[6], matrix[10]),
284 Vec3::new(matrix[0], matrix[4], matrix[8]),
285 )
286}
287
288/// [`export_step_assembly_report`] returning just the Part 21 text.
289pub fn export_step_assembly(
290 assembly: &StepAssemblyExport,
291 unit: &str,
292 timestamp: &str,
293) -> Result<String, String> {
294 export_step_assembly_report(assembly, unit, timestamp, None, None).map(|report| report.text)
295}
296
297/// Write a product structure as an AP242 Part 21 document: one product per
298/// distinct part, one `NEXT_ASSEMBLY_USAGE_OCCURRENCE` per placement, exact
299/// B-rep geometry in each part's own frame.
300///
301/// The file is named after the ROOT product, and the optional PMI block rides
302/// on the root exactly as it does in the flat lane — with each shape aspect
303/// attached to the product that actually OWNS the geometry it names.
304pub fn export_step_assembly_report(
305 assembly: &StepAssemblyExport,
306 unit: &str,
307 timestamp: &str,
308 pmi: Option<&StepPmi<'_>>,
309 colors: Option<&StepColors>,
310) -> Result<StepExportReport, String> {
311 let root = assembly.root()?;
312 if assembly
313 .products
314 .iter()
315 .all(|product| product.bodies.is_empty())
316 {
317 return Err("export_step: at least one solid is required".into());
318 }
319 let mut report = StepExportReport {
320 products: assembly.products.len(),
321 occurrences: assembly.occurrences.len(),
322 ..StepExportReport::default()
323 };
324 let mut writer = StepWriter::default();
325 let contexts = write_file_contexts(&mut writer, unit)?;
326
327 // 1 — every product's geometry, each in its own local frame. Written first
328 // because a representation's item list needs the solids it carries.
329 let mut geometries = Vec::with_capacity(assembly.products.len());
330 for product in &assembly.products {
331 let bodies: Vec<(String, &BrepSolid)> = product
332 .bodies
333 .iter()
334 .map(|(name, solid)| (name.clone(), solid))
335 .collect();
336 geometries.push(write_product_geometry(
337 &mut writer,
338 &contexts,
339 &bodies,
340 &mut report,
341 )?);
342 }
343
344 // 2 — each occurrence's placement frame. It is an ITEM of the parent
345 // representation, so it has to exist before that representation is written.
346 let mut placement_axes = Vec::with_capacity(assembly.occurrences.len());
347 for occurrence in &assembly.occurrences {
348 placement_axes.push(write_placement_axis(&mut writer, &occurrence.placement)?);
349 }
350
351 // 3 — the representations: identity axis, own solids, child placements.
352 let geometry_context = contexts.geometry_context;
353 let mut representations = Vec::with_capacity(assembly.products.len());
354 for (index, product) in assembly.products.iter().enumerate() {
355 let mut items = vec![contexts.axis];
356 items.extend(geometries[index].solids.iter().map(|(_, id)| *id));
357 for (slot, occurrence) in assembly.occurrences.iter().enumerate() {
358 if occurrence.parent == index {
359 items.push(placement_axes[slot]);
360 }
361 }
362 // A pure assembly node carries no bodies, and an ADVANCED_BREP shape
363 // representation with no solid in it is not one — say SHAPE_REPRESENTATION,
364 // which is what a vendor writes and what our importer reads for the
365 // structure-only levels of a tree.
366 let keyword = if geometries[index].solids.is_empty() {
367 "SHAPE_REPRESENTATION"
368 } else {
369 "ADVANCED_BREP_SHAPE_REPRESENTATION"
370 };
371 representations.push(writer.add(format!(
372 "{keyword}('{}',{},#{geometry_context})",
373 step_string(&product.name),
374 id_list(&items)
375 )));
376 }
377
378 // 4 — the product definition chains, bound to those representations.
379 let mut definitions = Vec::with_capacity(assembly.products.len());
380 for (index, product) in assembly.products.iter().enumerate() {
381 // 'assembly' vs 'part' is the distinction a receiving system builds its
382 // own structure tree from, so it follows the graph, not the geometry: a
383 // product that places others is an assembly even when it also carries
384 // bodies of its own.
385 let places_others = assembly
386 .occurrences
387 .iter()
388 .any(|occurrence| occurrence.parent == index);
389 let category = if places_others { "assembly" } else { "part" };
390 let ids = write_product(&mut writer, &contexts, &product.name, &product.id, category);
391 let (product_shape, representation) = (ids.product_shape, representations[index]);
392 writer.add(format!(
393 "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
394 ));
395 definitions.push(ids);
396 }
397
398 // 5 — the occurrences themselves. Each one's `PRODUCT_DEFINITION_SHAPE` is
399 // kept: it is what an OCCURRENCE-scoped annotation's shape aspect hangs
400 // off (step 7), and the entity a reader tells "this instance" from "this
401 // part" by.
402 let mut nauo_shapes: Vec<usize> = Vec::with_capacity(assembly.occurrences.len());
403 for (slot, occurrence) in assembly.occurrences.iter().enumerate() {
404 let parent = definitions[occurrence.parent].definition;
405 let child = definitions[occurrence.child].definition;
406 let label = step_string(&occurrence.designator);
407 let nauo = writer.add(format!(
408 "NEXT_ASSEMBLY_USAGE_OCCURRENCE('{label}','{label}','',#{parent},#{child},'{label}')"
409 ));
410 let nauo_shape =
411 writer.add(format!("PRODUCT_DEFINITION_SHAPE('','NAUO PRDDFN',#{nauo})"));
412 nauo_shapes.push(nauo_shape);
413 let identity = contexts.axis;
414 let placement = placement_axes[slot];
415 let transformation = writer.add(format!(
416 "ITEM_DEFINED_TRANSFORMATION('','',#{identity},#{placement})"
417 ));
418 let (child_rep, parent_rep) = (
419 representations[occurrence.child],
420 representations[occurrence.parent],
421 );
422 let relationship = writer.add(format!(
423 "(REPRESENTATION_RELATIONSHIP('','',#{child_rep},#{parent_rep})\
424 REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{transformation})\
425 SHAPE_REPRESENTATION_RELATIONSHIP())"
426 ));
427 writer.add(format!(
428 "CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{relationship},#{nauo_shape})"
429 ));
430 }
431
432 // 6 — geometry colour. A product's entities are known to the DOCUMENT under
433 // every occurrence namespace that reaches it, so the colour lookup resolves
434 // through the same paths the PMI references do — sorted, so which of a
435 // repeated part's namespaces supplies the colour does not depend on the
436 // walk's stack order.
437 // ONE walk for both consumers below — each product's occurrence namespaces —
438 // and only when one of them needs it: the walk is capped at
439 // `MAX_OCCURRENCE_PATHS`, so an export that carries neither colour nor PMI
440 // must not pay for it.
441 let colors = colors.filter(|colors| !colors.is_empty());
442 let paths = (pmi.is_some() || colors.is_some())
443 .then(|| assembly.occurrence_paths(root))
444 .unwrap_or_default();
445 if let Some(colors) = colors {
446 let mut items = Vec::new();
447 for (index, geometry) in geometries.iter().enumerate() {
448 let mut prefixes: Vec<String> =
449 paths[index].iter().map(|path| path.prefix.clone()).collect();
450 prefixes.sort();
451 items.extend(styles::styled_items(geometry, colors, &prefixes));
452 }
453 report.styled_items = styles::write_geometry_styles(&mut writer, geometry_context, &items)?;
454 }
455
456 // 7a — each PART's own PMI, written into that part's product with the
457 // part's own names. A part shared by six instances carries its annotations
458 // ONCE, which is the same rule the importer reads them back under.
459 for (index, geometry) in geometries.iter().enumerate() {
460 let Some((state, part_report)) = &assembly.products[index].pmi else {
461 continue;
462 };
463 let mut names = StepNameMaps::default();
464 names.register(
465 geometry,
466 StepItemOwner {
467 product_shape: definitions[index].product_shape,
468 representation: representations[index],
469 },
470 "",
471 &MAT4_IDENTITY,
472 );
473 let context = pmi::StepContext {
474 product_shape: definitions[index].product_shape,
475 representation: representations[index],
476 geometry_context,
477 length_unit: contexts.length_unit,
478 angle_unit: contexts.angle_unit,
479 faces: &names.faces,
480 edges: &names.edges,
481 vertices: &names.vertices,
482 };
483 report.pmi_unresolved_references += pmi::write_pmi(
484 &mut writer,
485 &context,
486 &StepPmi {
487 state,
488 report: part_report,
489 },
490 )?;
491 }
492
493 // 7b — PMI on the ROOT document, resolving through every occurrence path.
494 //
495 // A reference that reaches a part THROUGH an occurrence hangs its shape
496 // aspect off that occurrence's `PRODUCT_DEFINITION_SHAPE`, not the part's:
497 // `ACOMP3:top` and `ACOMP4:top` name the SAME `ADVANCED_FACE` (two
498 // instances share the part's geometry, and the `GEOMETRIC_ITEM_SPECIFIC_-
499 // USAGE` still points at it), but they are annotations on two different
500 // INSTANCES, and the owner is the only place that distinction can live.
501 // It is also what the importer reads the distinction back out of
502 // (`io/step_import/assembly_pmi.rs`), which is what closes the round trip.
503 if let Some(pmi) = pmi {
504 let mut names = StepNameMaps::default();
505 for (index, geometry) in geometries.iter().enumerate() {
506 for path in &paths[index] {
507 let owner = StepItemOwner {
508 product_shape: match path.last {
509 Some(slot) => nauo_shapes[slot],
510 None => definitions[index].product_shape,
511 },
512 representation: representations[index],
513 };
514 names.register(geometry, owner, &path.prefix, &path.world);
515 }
516 }
517 let context = pmi::StepContext {
518 product_shape: definitions[root].product_shape,
519 representation: representations[root],
520 geometry_context,
521 length_unit: contexts.length_unit,
522 angle_unit: contexts.angle_unit,
523 faces: &names.faces,
524 edges: &names.edges,
525 vertices: &names.vertices,
526 };
527 report.pmi_unresolved_references += pmi::write_pmi(&mut writer, &context, pmi)?;
528 }
529
530 finish_step_file(
531 writer,
532 &assembly.products[root].name,
533 timestamp,
534 &mut report,
535 )?;
536 Ok(report)
537}
538