BREP_kernel 0.5.0

A boundary representation (BREP) geometry kernel for building CAD applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! STRUCTURED STEP export: write a product structure, not just bodies.
//!
//! The flat writer ([`super::export_step_report_named`]) puts every body of the
//! document into ONE `PRODUCT`. That is the right answer for a part, and the
//! wrong one for an assembly: a nested assembly came out as a bag of bodies at
//! their world positions, with the parts library, the instance count and the
//! hierarchy all discarded.
//!
//! This module is the other answer. It takes a [`StepAssemblyExport`] — one
//! [`StepExportProduct`] per distinct part holding that part's bodies IN ITS OWN
//! LOCAL FRAME, plus one [`StepExportOccurrence`] per placement — and writes the
//! AP242 graph the importer (`io/step_import/`) reads back:
//!
//! ```text
//!   PRODUCT -> PRODUCT_DEFINITION_FORMATION -> PRODUCT_DEFINITION
//!       -> PRODUCT_DEFINITION_SHAPE -> SHAPE_DEFINITION_REPRESENTATION
//!       -> ADVANCED_BREP_SHAPE_REPRESENTATION (the part's own bodies)
//!
//!   NEXT_ASSEMBLY_USAGE_OCCURRENCE(parent_pd, child_pd)
//!       <- PRODUCT_DEFINITION_SHAPE('NAUO PRDDFN')
//!       <- CONTEXT_DEPENDENT_SHAPE_REPRESENTATION
//!       -> ( REPRESENTATION_RELATIONSHIP(child_rep, parent_rep)
//!            REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(
//!              ITEM_DEFINED_TRANSFORMATION(identity_axis, placement_axis) )
//!            SHAPE_REPRESENTATION_RELATIONSHIP() )
//! ```
//!
//! # The placement convention, and why it is copied rather than chosen
//!
//! A reader composes `T = M(item_2) · M(item_1)⁻¹` to map `rep_1` into `rep_2`.
//! With `rep_1` the CHILD and `item_1` the identity axis, `T` is simply
//! `M(item_2)` — the child's frame expressed in the parent. That ordering is
//! taken from the `as1-ug-214` vendor fixture
//! (`REPRESENTATION_RELATIONSHIP(' ',' ',#213 /* rod */,#219 /* rod_assem */)`
//! with `ITEM_DEFINED_TRANSFORMATION(' ',' ',#1041 /* identity */,#1109)`), NOT
//! from our own importer: `resolve_rep_rel_transform` reorients using the
//! child's known root representation, so a self round-trip would have passed
//! with the ordering reversed and told us nothing.
//!
//! For the same reason `item_1`/`item_2` are ITEMS of the reps they belong to —
//! the identity axis is the first item of every representation this writer
//! emits, and each occurrence's placement axis is pushed into its PARENT's item
//! list. A conformance checker requires exactly that.
//!
//! # Naming, and what PMI resolves against
//!
//! A part's bodies, faces and edges keep the part's OWN names — `Extrude1_top`,
//! not `ACOMP3:Extrude1_top` — because they are written into the part's product,
//! where the component namespace does not apply. The document still refers to
//! them by the namespaced name, so [`occurrence_paths`] walks the graph and
//! registers every entity under EVERY chained occurrence path that reaches it
//! (`ACOMP3:`, `ACOMP5:ACOMP1:`), with the vertex points moved into root space
//! so a `{body}@x,y,z` reference still matches. Two instances of one part share
//! the part's entities, so `ACOMP3:top` and `ACOMP4:top` resolve to the SAME
//! `ADVANCED_FACE`: an annotation on one instance is an annotation on the part.

use super::{
    finish_step_file, id_list, mat4_mul, pmi, step_string, write_file_contexts, write_product,
    write_product_geometry, Mat4, StepExportReport, StepItemOwner, StepNameMaps, StepPmi,
    StepWriter, MAT4_IDENTITY,
};
use crate::{BrepSolid, Vec3};

/// One product of an exported structure: a part, a sub-assembly, or the root
/// document. `bodies` are in the product's OWN local frame — never posed.
#[derive(Clone, Debug, Default)]
pub struct StepExportProduct {
    /// `PRODUCT.name` — the parts-library entry name, or the document name.
    pub name: String,
    /// `PRODUCT.id` — the vendor part number. The name is used when empty.
    pub id: String,
    /// This product's own solids and their part-local scene names. Empty for a
    /// pure assembly node, which is then written as a bare `SHAPE_REPRESENTATION`.
    pub bodies: Vec<(String, BrepSolid)>,
}

/// One placement of `child` inside `parent` — a `NEXT_ASSEMBLY_USAGE_OCCURRENCE`.
#[derive(Clone, Debug)]
pub struct StepExportOccurrence {
    /// The instance label: the placing component's id (`ACOMP3`). Written into
    /// the NAUO's `reference_designator`, which is what the importer reads back
    /// first, so an instance keeps its identity through the round trip.
    pub designator: String,
    /// Index into [`StepAssemblyExport::products`].
    pub parent: usize,
    /// Index into [`StepAssemblyExport::products`].
    pub child: usize,
    /// child-local -> parent-local, row-major affine. Must be RIGID: a mirrored
    /// or scaled instance has no `AXIS2_PLACEMENT_3D` and is rejected rather
    /// than silently written as its rotation part.
    pub placement: Mat4,
}

/// A document's product structure, ready to write. Exactly one product must be
/// a root (never an occurrence child) — the document itself.
#[derive(Clone, Debug, Default)]
pub struct StepAssemblyExport {
    pub products: Vec<StepExportProduct>,
    pub occurrences: Vec<StepExportOccurrence>,
}

/// How many occurrence paths the PMI alias walk will register before it stops.
/// One path per instance is the honest count, and a real assembly has
/// thousands at most; the cap only bounds a pathological diamond graph, whose
/// path count is exponential in its depth.
const MAX_OCCURRENCE_PATHS: usize = 100_000;

impl StepAssemblyExport {
    /// The single root product's index, with the graph checked on the way: every
    /// occurrence in range, no self-placement, exactly one root, no cycle, every
    /// product reachable, every placement rigid.
    pub fn root(&self) -> Result<usize, String> {
        if self.products.is_empty() {
            return Err("export_step: an assembly needs at least one product".into());
        }
        let count = self.products.len();
        let mut is_child = vec![false; count];
        for occurrence in &self.occurrences {
            if occurrence.parent >= count || occurrence.child >= count {
                return Err(format!(
                    "export_step: occurrence '{}' names a product outside the structure",
                    occurrence.designator
                ));
            }
            if occurrence.parent == occurrence.child {
                return Err(format!(
                    "export_step: occurrence '{}' places a product inside itself",
                    occurrence.designator
                ));
            }
            rigid(&occurrence.placement).map_err(|error| {
                format!(
                    "export_step: occurrence '{}' placement: {error}",
                    occurrence.designator
                )
            })?;
            is_child[occurrence.child] = true;
        }
        let roots: Vec<usize> = (0..count).filter(|index| !is_child[*index]).collect();
        let [root] = roots.as_slice() else {
            return Err(format!(
                "export_step: an assembly needs exactly one root product, found {}",
                roots.len()
            ));
        };
        // Reachability doubles as the cycle check: a cycle makes every product
        // on it a child, so an unreached product is either orphaned or looping.
        let mut reached = vec![false; count];
        let mut stack = vec![*root];
        reached[*root] = true;
        while let Some(product) = stack.pop() {
            for occurrence in &self.occurrences {
                if occurrence.parent == product && !reached[occurrence.child] {
                    reached[occurrence.child] = true;
                    stack.push(occurrence.child);
                }
            }
        }
        if let Some(lost) = reached.iter().position(|hit| !hit) {
            return Err(format!(
                "export_step: product '{}' is not reachable from the root",
                self.products[lost].name
            ));
        }
        Ok(*root)
    }

    /// Every chained occurrence path that reaches each product: the component
    /// namespace prefix the DOCUMENT knows its entities by, and the transform
    /// into root space. The root itself gets one empty path at identity.
    ///
    /// Depth-first from the root, guarding the path's own ancestors, so a
    /// structure that somehow still carries a cycle terminates.
    fn occurrence_paths(&self, root: usize) -> Vec<Vec<(String, Mat4)>> {
        let mut paths: Vec<Vec<(String, Mat4)>> = vec![Vec::new(); self.products.len()];
        let mut total = 0usize;
        let mut stack: Vec<(usize, String, Mat4, Vec<usize>)> =
            vec![(root, String::new(), MAT4_IDENTITY, vec![root])];
        while let Some((product, prefix, world, ancestors)) = stack.pop() {
            if total >= MAX_OCCURRENCE_PATHS {
                break;
            }
            total += 1;
            paths[product].push((prefix.clone(), world));
            for occurrence in &self.occurrences {
                if occurrence.parent != product || ancestors.contains(&occurrence.child) {
                    continue;
                }
                let mut ancestors = ancestors.clone();
                ancestors.push(occurrence.child);
                stack.push((
                    occurrence.child,
                    format!("{prefix}{}:", occurrence.designator),
                    mat4_mul(&world, &occurrence.placement),
                    ancestors,
                ));
            }
        }
        paths
    }
}

/// A placement is rigid when its linear block is orthonormal with a positive
/// determinant — the only kind an `AXIS2_PLACEMENT_3D` can express.
fn rigid(matrix: &Mat4) -> Result<(), String> {
    if matrix.iter().any(|value| !value.is_finite()) {
        return Err("matrix is not finite".into());
    }
    let column = |index: usize| {
        [
            matrix[index],
            matrix[4 + index],
            matrix[8 + index],
        ]
    };
    let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
    let (x, y, z) = (column(0), column(1), column(2));
    const TOLERANCE: f64 = 1e-9;
    for (a, b, expected) in [
        (x, x, 1.0),
        (y, y, 1.0),
        (z, z, 1.0),
        (x, y, 0.0),
        (x, z, 0.0),
        (y, z, 0.0),
    ] {
        if (dot(a, b) - expected).abs() > TOLERANCE {
            return Err("matrix is not a rotation (mirrored or scaled)".into());
        }
    }
    let cross = [
        x[1] * y[2] - x[2] * y[1],
        x[2] * y[0] - x[0] * y[2],
        x[0] * y[1] - x[1] * y[0],
    ];
    if (dot(cross, z) - 1.0).abs() > TOLERANCE {
        return Err("matrix is left-handed (a mirrored instance)".into());
    }
    Ok(())
}

/// The `AXIS2_PLACEMENT_3D` expressing a rigid placement's frame: the origin is
/// its translation, the axis its third linear COLUMN and the reference direction
/// its first — the exact inverse of the importer's `frame_matrix`.
fn write_placement_axis(writer: &mut StepWriter, matrix: &Mat4) -> Result<usize, String> {
    super::write_placement(
        writer,
        Vec3::new(matrix[3], matrix[7], matrix[11]),
        Vec3::new(matrix[2], matrix[6], matrix[10]),
        Vec3::new(matrix[0], matrix[4], matrix[8]),
    )
}

/// [`export_step_assembly_report`] returning just the Part 21 text.
pub fn export_step_assembly(
    assembly: &StepAssemblyExport,
    unit: &str,
    timestamp: &str,
) -> Result<String, String> {
    export_step_assembly_report(assembly, unit, timestamp, None).map(|report| report.text)
}

/// Write a product structure as an AP242 Part 21 document: one product per
/// distinct part, one `NEXT_ASSEMBLY_USAGE_OCCURRENCE` per placement, exact
/// B-rep geometry in each part's own frame.
///
/// The file is named after the ROOT product, and the optional PMI block rides
/// on the root exactly as it does in the flat lane — with each shape aspect
/// attached to the product that actually OWNS the geometry it names.
pub fn export_step_assembly_report(
    assembly: &StepAssemblyExport,
    unit: &str,
    timestamp: &str,
    pmi: Option<&StepPmi<'_>>,
) -> Result<StepExportReport, String> {
    let root = assembly.root()?;
    if assembly
        .products
        .iter()
        .all(|product| product.bodies.is_empty())
    {
        return Err("export_step: at least one solid is required".into());
    }
    let mut report = StepExportReport {
        products: assembly.products.len(),
        occurrences: assembly.occurrences.len(),
        ..StepExportReport::default()
    };
    let mut writer = StepWriter::default();
    let contexts = write_file_contexts(&mut writer, unit)?;

    // 1 — every product's geometry, each in its own local frame. Written first
    // because a representation's item list needs the solids it carries.
    let mut geometries = Vec::with_capacity(assembly.products.len());
    for product in &assembly.products {
        let bodies: Vec<(String, &BrepSolid)> = product
            .bodies
            .iter()
            .map(|(name, solid)| (name.clone(), solid))
            .collect();
        geometries.push(write_product_geometry(
            &mut writer,
            &contexts,
            &bodies,
            &mut report,
        )?);
    }

    // 2 — each occurrence's placement frame. It is an ITEM of the parent
    // representation, so it has to exist before that representation is written.
    let mut placement_axes = Vec::with_capacity(assembly.occurrences.len());
    for occurrence in &assembly.occurrences {
        placement_axes.push(write_placement_axis(&mut writer, &occurrence.placement)?);
    }

    // 3 — the representations: identity axis, own solids, child placements.
    let geometry_context = contexts.geometry_context;
    let mut representations = Vec::with_capacity(assembly.products.len());
    for (index, product) in assembly.products.iter().enumerate() {
        let mut items = vec![contexts.axis];
        items.extend(&geometries[index].solids);
        for (slot, occurrence) in assembly.occurrences.iter().enumerate() {
            if occurrence.parent == index {
                items.push(placement_axes[slot]);
            }
        }
        // A pure assembly node carries no bodies, and an ADVANCED_BREP shape
        // representation with no solid in it is not one — say SHAPE_REPRESENTATION,
        // which is what a vendor writes and what our importer reads for the
        // structure-only levels of a tree.
        let keyword = if geometries[index].solids.is_empty() {
            "SHAPE_REPRESENTATION"
        } else {
            "ADVANCED_BREP_SHAPE_REPRESENTATION"
        };
        representations.push(writer.add(format!(
            "{keyword}('{}',{},#{geometry_context})",
            step_string(&product.name),
            id_list(&items)
        )));
    }

    // 4 — the product definition chains, bound to those representations.
    let mut definitions = Vec::with_capacity(assembly.products.len());
    for (index, product) in assembly.products.iter().enumerate() {
        // 'assembly' vs 'part' is the distinction a receiving system builds its
        // own structure tree from, so it follows the graph, not the geometry: a
        // product that places others is an assembly even when it also carries
        // bodies of its own.
        let places_others = assembly
            .occurrences
            .iter()
            .any(|occurrence| occurrence.parent == index);
        let category = if places_others { "assembly" } else { "part" };
        let ids = write_product(&mut writer, &contexts, &product.name, &product.id, category);
        let (product_shape, representation) = (ids.product_shape, representations[index]);
        writer.add(format!(
            "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
        ));
        definitions.push(ids);
    }

    // 5 — the occurrences themselves.
    for (slot, occurrence) in assembly.occurrences.iter().enumerate() {
        let parent = definitions[occurrence.parent].definition;
        let child = definitions[occurrence.child].definition;
        let label = step_string(&occurrence.designator);
        let nauo = writer.add(format!(
            "NEXT_ASSEMBLY_USAGE_OCCURRENCE('{label}','{label}','',#{parent},#{child},'{label}')"
        ));
        let nauo_shape =
            writer.add(format!("PRODUCT_DEFINITION_SHAPE('','NAUO PRDDFN',#{nauo})"));
        let identity = contexts.axis;
        let placement = placement_axes[slot];
        let transformation = writer.add(format!(
            "ITEM_DEFINED_TRANSFORMATION('','',#{identity},#{placement})"
        ));
        let (child_rep, parent_rep) = (
            representations[occurrence.child],
            representations[occurrence.parent],
        );
        let relationship = writer.add(format!(
            "(REPRESENTATION_RELATIONSHIP('','',#{child_rep},#{parent_rep})\
             REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{transformation})\
             SHAPE_REPRESENTATION_RELATIONSHIP())"
        ));
        writer.add(format!(
            "CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{relationship},#{nauo_shape})"
        ));
    }

    // 6 — PMI on the root, resolving through every occurrence path.
    if let Some(pmi) = pmi {
        let paths = assembly.occurrence_paths(root);
        let mut names = StepNameMaps::default();
        for (index, geometry) in geometries.iter().enumerate() {
            let owner = StepItemOwner {
                product_shape: definitions[index].product_shape,
                representation: representations[index],
            };
            for (prefix, world) in &paths[index] {
                names.register(geometry, owner, prefix, world);
            }
        }
        let context = pmi::StepContext {
            product_shape: definitions[root].product_shape,
            representation: representations[root],
            geometry_context,
            length_unit: contexts.length_unit,
            angle_unit: contexts.angle_unit,
            faces: &names.faces,
            edges: &names.edges,
            vertices: &names.vertices,
        };
        report.pmi_unresolved_references = pmi::write_pmi(&mut writer, &context, pmi)?;
    }

    finish_step_file(
        writer,
        &assembly.products[root].name,
        timestamp,
        &mut report,
    )?;
    Ok(report)
}

// BREP private tests: f9fc1e069685c113