cadmpeg 0.4.0

Inspect, decode, validate, compare, and convert CAD models.
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
// SPDX-License-Identifier: Apache-2.0
//! Cross-codec conformance contracts that drive the codec crates in-process.
//!
//! Both module trees here import the codec crates directly, so each one used to
//! be its own file under `tests/`. Every file in `tests/` is a separate harness
//! binary that links the whole codec graph again, and these two linked about
//! 350 MB between them to carry three test functions. They share one binary
//! because they share that link cost; tests that only spawn the CLI belong in
//! `cli.rs`, which links almost none of it.

/// Cross-codec resource-budget classification contracts.
mod budget {
    use std::io::Cursor;

    use cadmpeg_codec_catia::CatiaCodec;
    use cadmpeg_codec_creo::CreoCodec;
    use cadmpeg_codec_freecad::FcstdCodec;
    use cadmpeg_codec_nx::NxCodec;
    use cadmpeg_codec_sldprt::SldprtCodec;
    use cadmpeg_core::decode::{
        DecodeArena, DecodeContext, DecodePolicy, ResourceDimension, ResourceLimits,
    };
    use cadmpeg_core::CodecError;
    use cadmpeg_ir::codec::{CodecEntry, DecodeOptions};

    const CATIA: &[u8] = include_bytes!("../../cadmpeg-fuzz/seeds/catia_container/standard_nested");
    const CATIA_WORK: &[u8] = include_bytes!("fixtures/catia_tetrahedron_topology.CATPart");
    const CREO: &[u8] = include_bytes!("../../cadmpeg-fuzz/seeds/creo_container/with_surface_rows");
    const FREECAD: &[u8] =
        include_bytes!("../../cadmpeg-fuzz/seeds/fcstd_container/core_design_product.FCStd");
    const NX: &[u8] = include_bytes!("fixtures/nx_topology_part.prt");
    const SLDPRT: &[u8] = include_bytes!("fixtures/sldprt_triangle_body.sldprt");

    #[derive(Clone, Copy)]
    enum Starvation {
        Entities,
        CollectionItems,
        RecursionDepth,
        WorkUnits,
        DecompressedBytes,
        RetainedBytes,
    }

    impl Starvation {
        fn apply(self, limits: &mut ResourceLimits) {
            match self {
                Self::Entities => limits.max_entities = 0,
                Self::CollectionItems => limits.max_collection_items = 0,
                Self::RecursionDepth => limits.max_recursion_depth = 0,
                Self::WorkUnits => limits.max_work_units = 0,
                Self::DecompressedBytes => {
                    limits.max_decompressed_bytes_total = 0;
                    limits.max_decompressed_bytes_per_expand = 0;
                }
                Self::RetainedBytes => limits.max_retained_bytes = 0,
            }
        }

        const fn dimension(self) -> ResourceDimension {
            match self {
                Self::Entities => ResourceDimension::Entities,
                Self::CollectionItems => ResourceDimension::CollectionItems,
                Self::RecursionDepth => ResourceDimension::RecursionDepth,
                Self::WorkUnits => ResourceDimension::WorkUnits,
                Self::DecompressedBytes => ResourceDimension::DecompressedBytes,
                Self::RetainedBytes => ResourceDimension::RetainedBytes,
            }
        }
    }

    struct Case {
        name: &'static str,
        codec: &'static dyn CodecEntry,
        bytes: &'static [u8],
        starvation: Starvation,
    }

    static CATIA_CODEC: CatiaCodec = CatiaCodec;
    static CREO_CODEC: CreoCodec = CreoCodec;
    static FREECAD_CODEC: FcstdCodec = FcstdCodec;
    static NX_CODEC: NxCodec = NxCodec;
    static SLDPRT_CODEC: SldprtCodec = SldprtCodec;

    fn cases() -> [Case; 8] {
        [
            Case {
                name: "catia/entities",
                codec: &CATIA_CODEC,
                bytes: CATIA,
                starvation: Starvation::Entities,
            },
            Case {
                name: "catia/work_units",
                codec: &CATIA_CODEC,
                bytes: CATIA_WORK,
                starvation: Starvation::WorkUnits,
            },
            Case {
                name: "creo/entities",
                codec: &CREO_CODEC,
                bytes: CREO,
                starvation: Starvation::Entities,
            },
            Case {
                name: "freecad/collection_items",
                codec: &FREECAD_CODEC,
                bytes: FREECAD,
                starvation: Starvation::CollectionItems,
            },
            Case {
                name: "freecad/recursion_depth",
                codec: &FREECAD_CODEC,
                bytes: FREECAD,
                starvation: Starvation::RecursionDepth,
            },
            Case {
                name: "freecad/retained_bytes",
                codec: &FREECAD_CODEC,
                bytes: FREECAD,
                starvation: Starvation::RetainedBytes,
            },
            Case {
                name: "nx/decompressed_bytes",
                codec: &NX_CODEC,
                bytes: NX,
                starvation: Starvation::DecompressedBytes,
            },
            Case {
                name: "sldprt/entities",
                codec: &SLDPRT_CODEC,
                bytes: SLDPRT,
                starvation: Starvation::Entities,
            },
        ]
    }

    #[test]
    fn migrated_codec_paths_classify_starvation_identically_across_profiles() {
        for case in cases() {
            case.codec
                .decode(&mut Cursor::new(case.bytes), &DecodeOptions::default())
                .unwrap_or_else(|error| panic!("{} baseline failed: {error}", case.name));

            let mut observed = None;
            for mut policy in [DecodePolicy::desktop(), DecodePolicy::service()] {
                case.starvation.apply(&mut policy.limits);
                let error = case
                    .codec
                    .decode(
                        &mut Cursor::new(case.bytes),
                        &DecodeOptions {
                            container_only: false,
                            policy,
                        },
                    )
                    .expect_err("starved decode must fail");
                let CodecError::ResourceLimit(limit) = error else {
                    panic!(
                        "{} returned the wrong error classification: {error}",
                        case.name
                    );
                };
                assert_eq!(
                    limit.dimension,
                    case.starvation.dimension(),
                    "{}",
                    case.name
                );
                assert_eq!(observed.get_or_insert(limit.dimension), &limit.dimension);
            }
        }
    }

    #[test]
    fn a_refusal_permanently_fuses_the_decode_session() {
        for policy in [DecodePolicy::desktop(), DecodePolicy::service()] {
            let arena = DecodeArena::new();
            let (ctx, _) = DecodeContext::from_root_bytes(b"root", &arena, &policy)
                .expect("context construction");
            let requested = policy.limits.max_entities.saturating_add(1);
            assert!(matches!(
                ctx.charge_entities(requested, "force refusal"),
                Err(CodecError::ResourceLimit(limit))
                    if limit.dimension == ResourceDimension::Entities
            ));
            assert!(matches!(
                ctx.charge_entities(0, "post-refusal charge"),
                Err(CodecError::ResourceLimit(limit))
                    if limit.dimension == ResourceDimension::Entities
            ));
            assert!(matches!(
                ctx.finish_session(),
                Err(CodecError::ResourceLimit(limit))
                    if limit.dimension == ResourceDimension::Entities
            ));
        }
    }
}

/// Cross-codec product-structure regression tests.
mod product_roundtrip {
    #![allow(clippy::unwrap_used)]

    use std::collections::{BTreeMap, HashMap, HashSet};
    use std::io::Cursor;

    use cadmpeg_codec_freecad::FcstdCodec;
    use cadmpeg_codec_step::StepCodec;
    use cadmpeg_ir::codec::{CodecEntry, DecodeOptions, EncodeInput};
    use cadmpeg_ir::products::{AssemblyGraph, Occurrence, OccurrenceParent, PrototypeReference};
    use cadmpeg_ir::{CadIr, Encoder};

    const CORE_DESIGN_PRODUCT: &[u8] = include_bytes!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../corpus/freecad_fcstd/fixtures/core_design_product.FCStd"
    ));

    fn definition_names(ir: &CadIr) -> HashMap<&str, String> {
        ir.model
            .product_definitions
            .iter()
            .map(|definition| {
                (
                    definition.id.0.as_str(),
                    definition
                        .part_number
                        .as_ref()
                        .or(definition.source_name.as_ref())
                        .or(definition.label.as_ref())
                        .expect("definition has a stable product name")
                        .clone(),
                )
            })
            .collect()
    }

    fn occurrence_paths(ir: &CadIr) -> BTreeMap<String, [[f64; 4]; 4]> {
        fn path(
            occurrence: &Occurrence,
            occurrences: &HashMap<&str, &Occurrence>,
            definitions: &HashMap<&str, String>,
            memo: &mut HashMap<String, String>,
        ) -> String {
            if let Some(path) = memo.get(occurrence.id.0.as_str()) {
                return path.clone();
            }
            let definition = match &occurrence.prototype {
                PrototypeReference::Local { definition } => definitions
                    .get(definition.0.as_str())
                    .expect("local prototype resolves"),
                _ => panic!("round-trip fixture contains only local prototypes"),
            };
            let segment = format!("{}:{definition}", occurrence.ordinal);
            let resolved = match &occurrence.parent {
                OccurrenceParent::Root => segment,
                OccurrenceParent::Occurrence { occurrence: parent } => format!(
                    "{}/{}",
                    path(
                        occurrences
                            .get(parent.0.as_str())
                            .expect("parent occurrence resolves"),
                        occurrences,
                        definitions,
                        memo,
                    ),
                    segment
                ),
            };
            memo.insert(occurrence.id.0.clone(), resolved.clone());
            resolved
        }

        let definitions = definition_names(ir);
        let occurrences = ir
            .model
            .occurrences
            .iter()
            .map(|occurrence| (occurrence.id.0.as_str(), occurrence))
            .collect::<HashMap<_, _>>();
        let graph = AssemblyGraph::new(&ir.model.occurrences).expect("valid assembly graph");
        let mut memo = HashMap::new();
        ir.model
            .occurrences
            .iter()
            .map(|occurrence| {
                (
                    path(occurrence, &occurrences, &definitions, &mut memo),
                    graph
                        .resolved_transform(&occurrence.id)
                        .expect("resolved transform")
                        .rows,
                )
            })
            .collect()
    }

    #[test]
    fn fcstd_assembly_round_trips_through_step_without_losing_its_tree() {
        let mut source = FcstdCodec
            .decode(
                &mut Cursor::new(CORE_DESIGN_PRODUCT),
                &DecodeOptions::default(),
            )
            .expect("decode FCStd assembly")
            .ir;

        let assembly_root = source
            .model
            .occurrences
            .iter()
            .find(|occurrence| {
                matches!(occurrence.parent, OccurrenceParent::Root)
                    && matches!(
                        &occurrence.prototype,
                        PrototypeReference::Local { definition }
                            if source.model.product_definitions.iter().any(|candidate| {
                                candidate.id == *definition
                                    && candidate.source_name.as_deref() == Some("Product")
                            })
                    )
            })
            .expect("Product assembly root")
            .id
            .clone();
        let mut retained = HashSet::from([assembly_root.clone()]);
        loop {
            let before = retained.len();
            for occurrence in &source.model.occurrences {
                if matches!(
                    &occurrence.parent,
                    OccurrenceParent::Occurrence { occurrence: parent }
                        if retained.contains(parent)
                ) {
                    retained.insert(occurrence.id.clone());
                }
            }
            if retained.len() == before {
                break;
            }
        }
        source
            .model
            .occurrences
            .retain(|occurrence| retained.contains(&occurrence.id));
        source
            .model
            .occurrences
            .iter_mut()
            .find(|occurrence| occurrence.id == assembly_root)
            .expect("retained root")
            .ordinal = 0;

        assert_eq!(
            source
                .model
                .product_definitions
                .iter()
                .map(|definition| definition.bodies.len())
                .sum::<usize>(),
            source.model.bodies.len(),
            "each FCStd body belongs to its source product definition"
        );
        let expected_definitions = definition_names(&source)
            .into_values()
            .collect::<HashSet<_>>();
        let expected_occurrences = occurrence_paths(&source);
        assert_eq!(expected_definitions.len(), 6);
        assert_eq!(expected_occurrences.len(), 6);

        let mut step = Vec::new();
        StepCodec::default()
            .plan(EncodeInput {
                ir: &source,
                fidelity: None,
            })
            .and_then(|plan| plan.write_to(&mut step))
            .expect("write STEP assembly");
        let decoded = StepCodec::default()
            .decode(&mut Cursor::new(step), &DecodeOptions::default())
            .expect("decode STEP assembly")
            .ir;

        assert_eq!(
            definition_names(&decoded)
                .into_values()
                .collect::<HashSet<_>>(),
            expected_definitions
        );
        let actual_occurrences = occurrence_paths(&decoded);
        assert_eq!(
            actual_occurrences.keys().collect::<Vec<_>>(),
            expected_occurrences.keys().collect::<Vec<_>>()
        );
        for (path, expected) in expected_occurrences {
            let actual = actual_occurrences.get(&path).expect("same occurrence path");
            for row in 0..4 {
                for column in 0..4 {
                    assert!(
                        (actual[row][column] - expected[row][column]).abs() <= 1.0e-9,
                        "resolved transform differs at {path}[{row}][{column}]: expected {}, got {}",
                        expected[row][column],
                        actual[row][column]
                    );
                }
            }
        }
    }
}