brep_kernel/io/step_import/assembly.rs
1//! STRUCTURED STEP import: read the product structure and keep it.
2//!
3//! [`collect_step_solids`] resolves a STEP assembly graph and then throws the
4//! structure away — it composes each occurrence's world transform, bakes it
5//! into a copy of the part, and returns a flat `Vec<BrepSolid>`. That is the
6//! right answer for "import these bodies", and it stays exactly as it is.
7//!
8//! This module is the other answer. It reads the SAME graph in the SAME single
9//! parse and returns it: one [`StepProduct`] per structure node holding that
10//! node's own bodies IN ITS OWN LOCAL FRAME, and one [`StepOccurrence`] per
11//! structure EDGE — a NEXT_ASSEMBLY_USAGE_OCCURRENCE or a MAPPED_ITEM
12//! (`mapped.rs`) — carrying the child→parent placement.
13//! **Nothing here is transformed.** Composing the tree — and so choosing what a
14//! "component" is — belongs to the caller, which maps products onto parts-library
15//! entries and occurrences onto assembly-component instances.
16//!
17//! Two invariants make that safe:
18//!
19//! - **ONE parse, each body built ONCE.** The parse is shared with nothing (the
20//! caller passes the text once), and inside it every distinct [`StepBody`] is
21//! reconstructed a single time and cloned into its product, exactly as
22//! `resolve_assembly` caches per body.
23//! - **The same walk.** Tree shape, visit order, transform composition and the
24//! cycle guard all come from [`walk_occurrences`], which the flat lane also
25//! uses, so the two lanes cannot drift apart. The kernel test suite asserts
26//! the strong form of this: replaying this module's output through the flat
27//! lane's own `transform_brep` call reproduces `resolve_assembly`'s solids
28//! BIT-for-bit on every assembly fixture, the mixed-unit one included.
29//!
30//! **Units are resolved PER PRODUCT**, in both lanes, not once per file.
31//! `derive_length_scale_mm` picks one global scale out of `HashMap` iteration
32//! order, which a mixed-unit assembly — each product representation carrying
33//! its own `GLOBAL_UNIT_ASSIGNED_CONTEXT` — makes both wrong and
34//! nondeterministic. See [`ProductScales`].
35
36use super::*;
37use crate::feature_pipeline::pmi::PmiState;
38
39/// One node of the file's product structure: a PRODUCT_DEFINITION, or a
40/// representation that a MAPPED_ITEM instantiates and no product definition owns
41/// (`bodies::representation_owner_index`).
42#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
43pub struct StepProduct {
44 /// The node's entity id — a PRODUCT_DEFINITION, or the representation that
45 /// stands in for one. The stable identity and dedup key either way, because
46 /// Part 21 ids are unique within a file.
47 pub pd_ref: usize,
48 /// `PRODUCT.name`, the representation's name for a node that is one, or
49 /// `pd#<id>` when the file carries neither.
50 pub name: String,
51 /// `PRODUCT.id` — the vendor part number, for the BOM. May be empty.
52 ///
53 /// The CONSUMER is what makes this durable: the app's assembly intake
54 /// records it as `partAttributes.Part_Number` on the part document it mints
55 /// (`BREP_render`'s `model_io.rs::part_attributes`), which is the record
56 /// `io/step/export_tree.rs` reads back out as `PRODUCT.id`. An intake that
57 /// dropped it would silently replace a vendor's part numbers with our own
58 /// file names on the first export -> import -> export.
59 pub id: String,
60 /// This product's OWN solids, in its OWN local frame and at its OWN unit
61 /// scale. Empty ⇒ a pure assembly node (structure, no geometry).
62 pub bodies: Vec<BrepSolid>,
63 /// The styled colour of each entry of `bodies`, PARALLEL to it (index `i`
64 /// is body `i`). Default-filled when the file carries no presentation
65 /// entities, so it is always the same length as `bodies` and a caller can
66 /// `zip` without a length check.
67 pub appearances: Vec<BodyAppearance>,
68 /// Bodies of this product that did not reconstruct. Graceful degradation:
69 /// counted, never fatal, and never a reason to reject the file.
70 pub failed_bodies: usize,
71 /// The file's PMI that annotates THIS product's own geometry, with
72 /// references naming the faces / edges / vertices the part document's
73 /// `IMPORT3D1` feature will stamp (`assembly_pmi.rs`).
74 ///
75 /// ONE lift per PART, however many occurrences place it — an annotation on
76 /// a part's face IS an annotation on every instance of that part, which is
77 /// the exporter's rule read backwards (`io/step/assembly.rs`: two
78 /// instances of one part share the part's `ADVANCED_FACE`s). PMI the file
79 /// pinned to a particular INSTANCE is not here; it rides
80 /// [`StepAssembly::pmi`].
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub pmi: Option<PmiState>,
83}
84
85/// One occurrence: a placement of `child` inside `parent`, from a NAUO edge or a
86/// mapped item.
87#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
88pub struct StepOccurrence {
89 /// The entity that IS this occurrence: a NEXT_ASSEMBLY_USAGE_OCCURRENCE, or
90 /// the MAPPED_ITEM that placed a shared representation (`mapped.rs`). Part 21
91 /// ids are unique per file, so this identifies the occurrence either way, and
92 /// consumers order sibling occurrences by it for determinism.
93 pub edge_ref: usize,
94 /// Index into [`StepAssembly::products`].
95 pub parent: usize,
96 /// Index into [`StepAssembly::products`].
97 pub child: usize,
98 /// The instance label ("bolt-3") — see `edge_designator` for which of a
99 /// NAUO's several label attributes wins, and what a mapped item contributes.
100 pub designator: String,
101 /// child-local → parent-local, row-major affine, translations in MILLIMETRES
102 /// (scaled by the PARENT representation's unit, which is the frame the
103 /// placement is expressed in). NOT a world transform: the caller composes
104 /// these down from [`StepAssembly::roots`].
105 pub placement: [f64; 16],
106 /// RᵀR = I and det R = +1 within 1e-9 — i.e. the placement is a pure
107 /// rotation + translation, representable as a translate/rotate component
108 /// pose. A mirrored or scaled occurrence has no such representation and its
109 /// non-rigid factor must be baked into a distinct part by the caller, which
110 /// is what `BREP_render`'s assembly intake does. A MAPPED_ITEM through a
111 /// CARTESIAN_TRANSFORMATION_OPERATOR_3D is the placement that makes this
112 /// `false` today (`mapped.rs`).
113 pub rigid: bool,
114 /// This instance's own colour, where the file styles the occurrence apart
115 /// from its part (a STEP `CONTEXT_DEPENDENT_OVER_RIDING_STYLED_ITEM` in the
116 /// occurrence's context or a style on its MAPPED_ITEM, an IGES 408's
117 /// colour). It colours every body the instance places, over the part's own
118 /// body colour; `None` leaves the part's colours as they are.
119 #[serde(default)]
120 pub color: Option<crate::ImportedColor>,
121 /// The colour this instance gives each of its child's OWN bodies, parallel
122 /// to that product's `bodies`, where the file styles them in this
123 /// occurrence's context (`None` for a body it leaves as the part has it).
124 /// Empty when it styles none of them.
125 #[serde(default)]
126 pub body_colors: Vec<Option<crate::ImportedColor>>,
127}
128
129/// A STEP file's product structure, with geometry, and without a single
130/// transform applied to it.
131#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
132pub struct StepAssembly {
133 /// Every product the structure mentions, ordered by ascending `pd_ref`.
134 pub products: Vec<StepProduct>,
135 /// One entry per structure edge, ordered by ascending `edge_ref`.
136 pub occurrences: Vec<StepOccurrence>,
137 /// Indices of the products that are never an occurrence child — where a
138 /// consumer starts composing world transforms.
139 pub roots: Vec<usize>,
140 /// The first thing that did not come in: a body that failed to reconstruct,
141 /// or a mapping that was refused (`StepMappedItemError`). A refused mapping
142 /// is NOT counted in any product's `failed_bodies`, which counts bodies that
143 /// failed to BUILD — a placement we cannot express is a different thing, and
144 /// the geometry under it built perfectly well.
145 pub first_error: Option<String>,
146 /// The file's ASSEMBLY-level PMI: annotations the file pinned to an
147 /// OCCURRENCE rather than a part, annotations spanning two parts, and
148 /// annotations with no geometry of their own (a free note, a saved view).
149 ///
150 /// References to a component's geometry carry the STEP occurrence chain
151 /// they resolve through (`OCCURRENCE_REF_PREFIX`): the kernel cannot know
152 /// what the consumer will call its components, so the consumer rewrites
153 /// them with `rewrite_occurrence_refs`.
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub pmi: Option<PmiState>,
156 /// What the PMI lift could not do cleanly — a reference naming geometry
157 /// this import did not build, an occurrence chain nothing placed. Every
158 /// one of these describes a KEPT annotation: PMI is never dropped for want
159 /// of a reference, it arrives as a row that reports itself.
160 #[serde(default, skip_serializing_if = "Vec::is_empty")]
161 pub pmi_diagnostics: Vec<String>,
162 /// Open `SHELL_BASED_SURFACE_MODEL` sheets this lane skipped, summed over
163 /// every product's bodies: not solids, so in no product's `failed_bodies`,
164 /// and uncounted before 2026-10-12 (`SHEETS_SKIPPED` on the flat lane).
165 #[serde(default)]
166 pub sheets_skipped: usize,
167}
168
169/// What [`read_step_assembly_outline`] reads: the counts an import dialog shows,
170/// from the product structure alone, before a single body is built.
171#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
172pub struct StepAssemblyOutline {
173 /// Distinct products the walk reaches that list at least one body.
174 pub parts: usize,
175 /// Occurrences (root included) of those products: one per placed instance.
176 pub instances: usize,
177 /// Longest root-to-instance chain of occurrence edges; `1` is a flat
178 /// assembly, `> 1` means sub-assemblies exist.
179 pub nested_depth: usize,
180}
181
182/// Read a STEP file's product structure WITHOUT building any geometry: the
183/// parse, the structure edges and the walk of [`read_step_assembly`], stopping
184/// before its body builds (the seconds of a real import). It answers whether a
185/// file is an assembly, and roughly how big, while the user can still decide
186/// what to do with it.
187///
188/// The counts are what the file DECLARES: a body that later fails to build, or
189/// an open sheet the import skips, is still counted here. `Ok(None)` on the
190/// same structural grounds `read_step_assembly` gives it (no edges, every edge
191/// refused, no reached product lists a body); `Err` for text that is not Part 21.
192pub fn read_step_assembly_outline(text: &str) -> Result<Option<StepAssemblyOutline>, String> {
193 if !text.contains("ISO-10303-21") {
194 return Err("step_import: not an ISO-10303-21 Part 21 file".into());
195 }
196 let entities = parse_data_section(text)?;
197 let global_scale = derive_length_scale_mm(&entities);
198 let edges = structure_edges(&entities, &Resolver::new(&entities, global_scale));
199 if edges.is_empty() {
200 return Ok(None);
201 }
202 let structure = StructureIndex::new(&entities);
203 let mut scales = ProductScales::new(&structure, global_scale);
204 let ResolvedEdges { edges, transforms, .. } =
205 resolve_structure_edges(&structure, &edges, |node| scales.get(node));
206 if edges.is_empty() {
207 return Ok(None);
208 }
209 let mut has_bodies: HashMap<usize, bool> = HashMap::default();
210 let resolver = Resolver::new(&entities, global_scale);
211 let mut parts: HashSet<usize> = HashSet::default();
212 let mut instances = 0usize;
213 let mut nested_depth = 0usize;
214 walk_occurrences(&resolver, &edges, &transforms, |node| {
215 let bodied = *has_bodies.entry(node.pd).or_insert_with(|| {
216 let product_resolver = Resolver::new(&entities, scales.get(node.pd));
217 !pd_step_bodies(&structure, &product_resolver, node.pd).is_empty()
218 });
219 if bodied {
220 parts.insert(node.pd);
221 instances += 1;
222 nested_depth = nested_depth.max(node.path.len());
223 }
224 });
225 if instances == 0 {
226 return Ok(None);
227 }
228 Ok(Some(StepAssemblyOutline {
229 parts: parts.len(),
230 instances,
231 nested_depth,
232 }))
233}
234
235/// Read a STEP file's product structure AND build each product's own bodies, in
236/// ONE parse, with each distinct body built ONCE.
237///
238/// `Ok(None)` when the file carries no assembly structure worth using — no
239/// structure edges at all (neither NAUO nor mapped item), or none that the walk
240/// reaches a built body through. That is the same condition on which
241/// `collect_step_solids` abandons the assembly branch, so a caller can treat
242/// `None` as "fall back to the flat lane" and get exactly today's behaviour.
243///
244/// `Err` only for a file that is not Part 21 or does not parse — a broken
245/// *assembly* degrades, it does not fail.
246pub fn read_step_assembly(text: &str) -> Result<Option<StepAssembly>, String> {
247 if !text.contains("ISO-10303-21") {
248 return Err("step_import: not an ISO-10303-21 Part 21 file".into());
249 }
250 let debug_timing = std::env::var("BREP_DEBUG_STEP_LOOP").is_ok();
251 let parse_started = debug_timing.then(web_time::Instant::now);
252 let entities = parse_data_section(text)?;
253 if let Some(started) = parse_started {
254 eprintln!("PHASE parse: {:?} ({} entities)", started.elapsed(), entities.len());
255 }
256 let mut phase_clock = debug_timing.then(web_time::Instant::now);
257 let mut phase = |name: &str| {
258 if let Some(started) = phase_clock.as_mut() {
259 eprintln!("PHASE assembly {name}: {:?}", started.elapsed());
260 *started = web_time::Instant::now();
261 }
262 };
263 let global_scale = derive_length_scale_mm(&entities);
264 let edges = structure_edges(&entities, &Resolver::new(&entities, global_scale));
265 phase("structure edges");
266 if edges.is_empty() {
267 return Ok(None); // no product structure: the flat lane is the answer
268 }
269
270 let structure = StructureIndex::new(&entities);
271 phase("structure index");
272 let mut scales = ProductScales::new(&structure, global_scale);
273
274 // Each edge's placement, read at the scale of the representation each of its
275 // frames is an item of (§3.6.2): an ITEM_DEFINED_TRANSFORMATION has
276 // `transform_item_1` in rep_1 and `transform_item_2` in rep_2, and a mapped
277 // item's `mapping_origin` is an item of the CHILD representation, its target
278 // of the PARENT's (`mapped.rs`). The rotation blocks are dimensionless and
279 // unaffected.
280 //
281 // A mapping we cannot express as a rigid placement is REFUSED here: its edge
282 // is dropped, so nothing under it is instantiated, and the refusal is
283 // reported through `first_error`.
284 let ResolvedEdges {
285 edges,
286 transforms,
287 refusals,
288 } = resolve_structure_edges(&structure, &edges, |node| scales.get(node));
289 phase("resolve edges");
290 let mut first_error: Option<String> = refusals.first().map(ToString::to_string);
291 let mut sheets_skipped = 0usize;
292 if edges.is_empty() {
293 return Ok(None); // every edge refused: nothing to build a structure from
294 }
295
296 // Every structure node the surviving edges mention, by ascending entity id.
297 let mut pd_refs: Vec<usize> = edges
298 .iter()
299 .flat_map(|edge| [edge.parent_pd, edge.child_pd])
300 .collect();
301 pd_refs.sort_unstable();
302 pd_refs.dedup();
303 let product_index: HashMap<usize, usize> = pd_refs
304 .iter()
305 .enumerate()
306 .map(|(index, &pd)| (pd, index))
307 .collect();
308
309 // Each body built at the unit of the representation that lists it, else
310 // its product's (`body_scale`). The cache is keyed by (body, scale) rather
311 // than by body alone, as in the flat lane, so a body reached at two units
312 // gets a build for each.
313 // The file's presentation entities, read ONCE for the whole document.
314 let styles = StyleTable::read(&entities);
315 // Every per-body resolver derives from this one, so they share its lazily
316 // derived angle unit instead of each sweeping the file for it.
317 let base = Resolver::new(&entities, global_scale).without_trim_readings();
318 let build_part = |(body, scale_key): (StepBody, u64)| {
319 // The readings are dropped below, so the build does not take them.
320 let resolver = base.with_length_scale(f64::from_bits(scale_key));
321 build_step_body(&resolver, body)
322 .map(|(solid, _readings)| {
323 let appearance = step_body_appearance(&resolver, &styles, body, &solid);
324 (solid, appearance)
325 })
326 .map_err(|error| format!("step_import: part body {body:?} failed to build: {error}"))
327 };
328 // Every distinct (body, scale) the product loop below asks for, in the
329 // order it asks, built up front -- in parallel under the `parallel`
330 // feature. The loop then only reads the cache.
331 let product_scales: Vec<f64> = pd_refs.iter().map(|&pd| scales.get(pd)).collect();
332 let mut part_keys: Vec<(StepBody, u64)> = Vec::new();
333 {
334 let mut seen: HashSet<(StepBody, u64)> = HashSet::default();
335 for (&pd, &scale) in pd_refs.iter().zip(&product_scales) {
336 let resolver = Resolver::new(&entities, scale);
337 let owners = node_representations(&structure, &resolver, pd);
338 for body in pd_step_bodies(&structure, &resolver, pd) {
339 let key = (body, body_scale(&structure.units, body, &owners, scale).to_bits());
340 if seen.insert(key) {
341 part_keys.push(key);
342 }
343 }
344 }
345 }
346 phase(&format!("body keys ({} distinct bodies)", part_keys.len()));
347 // Under the PHASE switch, each body's own build time too, slowest first:
348 // which parts an import is waiting on.
349 let body_times: std::sync::Mutex<Vec<(std::time::Duration, StepBody, Option<String>)>> = Default::default();
350 let timed_build = |key: (StepBody, u64)| {
351 let started = debug_timing.then(web_time::Instant::now);
352 let built = build_part(key);
353 if let Some(started) = started {
354 let error = built.as_ref().err().map(|error| error.chars().take(300).collect());
355 body_times.lock().expect("timing lock").push((started.elapsed(), key.0, error));
356 }
357 built
358 };
359 let mut solid_cache: HashMap<(StepBody, u64), Result<(BrepSolid, BodyAppearance), String>> =
360 build_distinct_bodies(
361 part_keys,
362 |(body, _)| step_body_face_count(&base, body),
363 &timed_build,
364 ).into_iter().collect();
365 phase("body builds");
366 if debug_timing {
367 let mut times = body_times.into_inner().expect("timing lock");
368 times.sort_by(|a, b| b.0.cmp(&a.0));
369 for (elapsed, body, error) in times.iter().take(15) {
370 let outcome = if error.is_some() { " (failed)" } else { "" };
371 eprintln!("PHASE assembly slow body {body:?}: {elapsed:?}{outcome}");
372 }
373 let failed: Vec<_> = times.iter().filter(|(_, _, error)| error.is_some()).collect();
374 let failed_time: std::time::Duration = failed.iter().map(|(elapsed, _, _)| *elapsed).sum();
375 eprintln!("PHASE assembly {} failed bodies took {failed_time:?} in all", failed.len());
376 for (elapsed, body, error) in failed {
377 eprintln!("PHASE assembly failed body {body:?} after {elapsed:?}: {}", error.as_deref().unwrap_or(""));
378 }
379 }
380 let mut products: Vec<StepProduct> = Vec::with_capacity(pd_refs.len());
381 // The face refs of every body that built, in `bodies` order — the pairing
382 // an annotation's `ADVANCED_FACE` is mapped to `IMPORT3D1_Face_i` through
383 // (`assembly_pmi.rs`). Collected only when the file mentions PMI at all,
384 // so a plain assembly pays nothing for it.
385 let wants_pmi = super::pmi::file_mentions_pmi(text);
386 let mut face_refs: super::assembly_pmi::ProductFaceRefs = Vec::with_capacity(pd_refs.len());
387 // Each product's built bodies as the entities a style can name them by,
388 // parallel to its `bodies`: what an occurrence's own colours are read
389 // against.
390 let mut body_items: Vec<Vec<Vec<usize>>> = Vec::with_capacity(pd_refs.len());
391 for (&pd, &scale) in pd_refs.iter().zip(&product_scales) {
392 let resolver = Resolver::new(&entities, scale);
393 let mut bodies = Vec::new();
394 let mut appearances = Vec::new();
395 let mut product_face_refs = Vec::new();
396 let mut failed_bodies = 0usize;
397 let mut items = Vec::new();
398 let owners = node_representations(&structure, &resolver, pd);
399 for body in pd_step_bodies(&structure, &resolver, pd) {
400 let scale_key = body_scale(&structure.units, body, &owners, scale).to_bits();
401 let built = solid_cache
402 .entry((body, scale_key))
403 .or_insert_with(|| build_part((body, scale_key)));
404 match built {
405 // Pushed together, so `bodies` and `appearances` stay parallel
406 // through every skip arm below.
407 Ok((solid, appearance)) => {
408 if wants_pmi {
409 product_face_refs.push(super::pmi::body_face_refs(&resolver, body, solid));
410 }
411 bodies.push(solid.clone());
412 appearances.push(appearance.clone());
413 items.push(super::bodies::body_style_items(&resolver, body));
414 }
415 // An OPEN SHELL_BASED_SURFACE_MODEL sheet is not a solid body:
416 // skipped, never a failed body, exactly as both other lanes do;
417 // counted as a skipped sheet since 2026-10-12.
418 Err(_) if matches!(body, StepBody::SurfaceModelShell { .. }) => sheets_skipped += 1,
419 Err(error) => {
420 failed_bodies += 1;
421 if first_error.is_none() {
422 first_error = Some(error.clone());
423 }
424 }
425 }
426 }
427 face_refs.push(product_face_refs);
428 body_items.push(items);
429 products.push(StepProduct {
430 pd_ref: pd,
431 name: product_name(&resolver, pd),
432 id: product_id(&resolver, pd),
433 bodies,
434 appearances,
435 failed_bodies,
436 pmi: None,
437 });
438 }
439
440 // Which products the structure actually REACHES — through the flat lane's
441 // own walk, so the cycle guard and root set are identical. A graph that
442 // reaches no geometry is not a structure we can import, so the caller falls
443 // back to the flat lane, exactly as `collect_step_solids` does when
444 // `resolve_assembly` yields no solid.
445 //
446 // (One corner differs harmlessly: a body that builds but fails
447 // `transform_brep` yields no flat solid, yet counts as reached here.)
448 phase("products");
449 let mut reached: HashSet<usize> = HashSet::default();
450 {
451 let resolver = Resolver::new(&entities, global_scale);
452 walk_occurrences(&resolver, &edges, &transforms, |node| {
453 reached.insert(node.pd);
454 });
455 }
456 let reaches_geometry = products
457 .iter()
458 .any(|product| !product.bodies.is_empty() && reached.contains(&product.pd_ref));
459 if !reaches_geometry {
460 return Ok(None);
461 }
462
463 let label_resolver = Resolver::new(&entities, global_scale);
464 let occurrences: Vec<StepOccurrence> = edges
465 .iter()
466 .map(|edge| {
467 let placement = transforms
468 .get(&edge.edge_id)
469 .copied()
470 .unwrap_or_else(mat4_identity);
471 StepOccurrence {
472 edge_ref: edge.edge_id,
473 parent: product_index[&edge.parent_pd],
474 child: product_index[&edge.child_pd],
475 designator: edge_designator(&label_resolver, edge),
476 placement,
477 rigid: transform_is_rigid(&placement),
478 color: {
479 let leaf = !edges.iter().any(|other| other.parent_pd == edge.child_pd);
480 let bodies = &body_items[product_index[&edge.child_pd]];
481 styles.occurrence_color(edge.edge_id, leaf.then_some(bodies.as_slice()))
482 },
483 body_colors: {
484 let colors: Vec<Option<crate::ImportedColor>> = body_items[product_index[&edge.child_pd]]
485 .iter()
486 .map(|items| styles.occurrence_item_color(edge.edge_id, items))
487 .collect();
488 if colors.iter().any(Option::is_some) { colors } else { Vec::new() }
489 },
490 }
491 })
492 .collect();
493
494 let roots: Vec<usize> = assembly_roots(&edges)
495 .into_iter()
496 .map(|pd| product_index[&pd])
497 .collect();
498
499 // The file's PMI, split between the part documents this import will mint
500 // and the assembly document that places them (`assembly_pmi.rs`). Read
501 // here rather than by the consumer because this is where the file text,
502 // the parse and each product's own face pairing are all in hand at once —
503 // the same reason the geometry is built here.
504 phase("walk + occurrences");
505 let mut pmi = super::assembly_pmi::AssemblyPmi::default();
506 if wants_pmi {
507 pmi = super::assembly_pmi::lift(
508 text,
509 &entities,
510 &products,
511 &face_refs,
512 &occurrences,
513 &roots,
514 global_scale,
515 |pd| scales.get(pd),
516 );
517 for (product, state) in products.iter_mut().zip(pmi.per_product.drain(..)) {
518 product.pmi = state;
519 }
520 }
521
522 phase("pmi");
523 Ok(Some(StepAssembly {
524 products,
525 occurrences,
526 roots,
527 first_error,
528 pmi: pmi.assembly,
529 pmi_diagnostics: pmi.diagnostics,
530 sheets_skipped,
531 }))
532}
533
534/// Per-product length units, memoised: the fallback for a body or placement
535/// frame whose own representation's context names no unit
536/// (`RepresentationUnits` answers first, for mapped-item frames too).
537///
538/// A product's geometry is expressed in the REPRESENTATION_CONTEXT of the shape
539/// representation that defines it, and that context carries its own unit
540/// assignment. `Resolver` is only `{entities, length_scale}`, so building a
541/// product at its own scale costs one struct rebuild — which is the whole
542/// implementation of "per-product units".
543///
544/// Falls back to the file-global scale for a product with no resolvable context
545/// (a pure assembly node with no shape representation, typically), so a
546/// single-context file resolves to the identical scale everywhere. The flat
547/// lane (`resolve_assembly`) reads its scales through this same memo, so the
548/// two lanes agree on every file.
549pub(super) struct ProductScales<'a> {
550 structure: &'a StructureIndex<'a>,
551 global: f64,
552 cache: HashMap<usize, f64>,
553}
554
555impl<'a> ProductScales<'a> {
556 pub(super) fn new(structure: &'a StructureIndex<'a>, global: f64) -> Self {
557 Self {
558 structure,
559 global,
560 cache: HashMap::default(),
561 }
562 }
563
564 /// Millimetres per native length unit for `pd`'s own representation. The
565 /// candidate SRs come from `pd_root_srs`, which sorts and dedups, so a
566 /// product with several representations resolves deterministically (unlike
567 /// `derive_length_scale_mm`, which reads whatever the `HashMap` yields).
568 pub(super) fn get(&mut self, pd: usize) -> f64 {
569 if let Some(&scale) = self.cache.get(&pd) {
570 return scale;
571 }
572 let scale = pd_root_srs(self.structure, pd)
573 .into_iter()
574 .filter_map(|sr| self.structure.entities.get(&sr).and_then(representation_context))
575 .find_map(|context| context_length_scale_mm(self.structure.entities, context))
576 .unwrap_or(self.global);
577 self.cache.insert(pd, scale);
578 scale
579 }
580}
581
582/// Is this affine's linear block a pure rotation — RᵀR = I and det R = +1 to
583/// 1e-9? A mirrored (det = −1) or scaled occurrence is NOT representable as a
584/// component pose, and its caller must bake the non-rigid factor into a
585/// distinct part rather than silently reuse the unmirrored twin.
586///
587/// A NAUO placement cannot fail this: it is built from two AXIS2_PLACEMENT_3Ds,
588/// and `Resolver::placement` always returns an orthonormal right-handed frame. A
589/// MAPPED_ITEM's can, and does — its target may be a
590/// CARTESIAN_TRANSFORMATION_OPERATOR_3D with a left-handed triad or a `scale`
591/// (`mapped.rs`) — so this flag is now LIVE rather than carried for a future
592/// lane, and `mapped-item-mirrored.step` is the fixture that makes it false.
593///
594/// `false` is not a refusal. It is the statement that this placement is not a
595/// component pose, which the caller answers by splitting `world = rigid · factor`
596/// and baking `factor` into a distinct part — `BREP_render`'s `split_rigid` /
597/// `build_library_entry`, whose mirrored part is named `… (mirrored)` and counted
598/// in the import notice's "N mirrored instances baked". The flat import lane bakes
599/// the same reflection directly into the posed geometry it returns
600/// (`resolve_assembly`, through `transform_brep`'s orientation reversal), so the
601/// two lanes agree about what the file means.
602pub(super) fn transform_is_rigid(matrix: &Mat4) -> bool {
603 crate::AffineTransform { elements: *matrix }.is_rigid(crate::RIGID_TOL)
604}
605
606/// The instance label of one structure edge: a mapped item's own name
607/// (`mapped::mapped_item_designator`), or a NAUO's designator below.
608fn edge_designator(resolver: &Resolver, edge: &AssemblyEdge) -> String {
609 match edge.kind {
610 StructureEdgeKind::Nauo => nauo_designator(resolver, edge.edge_id),
611 StructureEdgeKind::Mapped => mapped_item_designator(resolver, edge.edge_id),
612 }
613}
614
615/// The instance label of a NAUO —
616/// `NEXT_ASSEMBLY_USAGE_OCCURRENCE(id, name, description, relating, related,
617/// reference_designator)`.
618///
619/// Producers disagree about which attribute carries it, so take the first
620/// NON-BLANK of `reference_designator` → `name` → `description` → `id`. The
621/// three assembly fixtures each land on a different one: AssemblyExample and
622/// io1-ac put it in `name`; as1-ug writes `name` as a single space and the real
623/// designator ('ROD', 'NUT1', …) in `description`; a producer that fills
624/// `reference_designator` is the standard-conforming case and wins outright.
625fn nauo_designator(resolver: &Resolver, nauo: usize) -> String {
626 let field = |args: &[Value], index: usize| match args.get(index) {
627 Some(Value::Str(text)) if !text.trim().is_empty() => Some(text.trim().to_string()),
628 _ => None,
629 };
630 (|| {
631 let args = resolver
632 .get(nauo)
633 .ok()?
634 .find("NEXT_ASSEMBLY_USAGE_OCCURRENCE")?;
635 field(args, 5)
636 .or_else(|| field(args, 1))
637 .or_else(|| field(args, 2))
638 .or_else(|| field(args, 0))
639 })()
640 .unwrap_or_else(|| format!("nauo#{nauo}"))
641}