Skip to main content

cadmpeg_codec_sldprt/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2#![cfg_attr(test, allow(clippy::unwrap_used))]
3//! Read and write `SolidWorks` `.sldprt` part documents, and read the
4//! component structure of `.sldasm` assembly documents.
5//!
6//! [`SldprtCodec`] decodes B-rep topology, analytic and NURBS geometry,
7//! tessellation, appearances, selected document attributes, feature history,
8//! and feature-input records into [`cadmpeg_ir::CadIr`]. It preserves source
9//! blocks and records provenance so supported edits can retain native data.
10//!
11//! <!-- generated: capability sldprt -->
12//! Support: L3 ([ladder](https://github.com/cadmpeg/cadmpeg/blob/main/docs/format-support.md#solidworks-sldprt)).
13//! <!-- /generated: capability sldprt -->
14//!
15//! # Decode
16//!
17//! ```
18//! use std::io::Cursor;
19//!
20//! use cadmpeg_codec_sldprt::SldprtCodec;
21//! use cadmpeg_ir::{Codec, DecodeOptions};
22//!
23//! # fn decode(bytes: Vec<u8>) -> Result<(), cadmpeg_ir::DecodeFailure> {
24//! let decoded = SldprtCodec.decode(
25//!     &mut Cursor::new(bytes),
26//!     &DecodeOptions::default(),
27//! )?;
28//! println!("{} faces", decoded.ir().model.faces.len());
29//! for loss in &decoded.report().losses {
30//!     eprintln!("{:?}: {}", loss.severity, loss.message);
31//! }
32//! # Ok(())
33//! # }
34//! ```
35//!
36//! Decode reports can accompany a usable model. Untyped support carriers become
37//! opaque geometry linked to retained bytes, while their resolvable topology
38//! remains in the IR. No usable geometry yields metadata with diagnostics.
39//! Set [`DecodeOptions::depth`] to [`DecodeDepth::Container`] to omit geometry
40//! decoding explicitly.
41//! Semantic Parasolid graph errors propagate as decode errors.
42//!
43//! [`Codec::inspect`] inventories the outer blocks, section directory, cache
44//! cells, payload families, and Parasolid schemas. It does not build model
45//! geometry.
46//!
47//! # Format and units
48//!
49//! The outer container uses an 8-byte header, CRC-validated raw-DEFLATE blocks,
50//! a fixed-cell section index, and a tail directory. Embedded Parasolid
51//! `partition` and `deltas` streams supply the B-rep record graph. The decoder
52//! groups related body streams by site and selects the resolved active site.
53//! Without a resolved active site, the first site is a deterministic merge
54//! accumulator. Alternate sites become configuration-specific bodies. Parasolid
55//! lengths are metres; decoded `CadIr` coordinates are millimetres. Directions,
56//! normals, and ratios remain dimensionless.
57//!
58//! # Encode
59//!
60//! ```no_run
61//! use std::fs::File;
62//!
63//! use cadmpeg_codec_sldprt::SldprtCodec;
64//! use cadmpeg_ir::codec::write::target::TargetRequest;
65//! use cadmpeg_ir::codec::write::Encoder;
66//! use cadmpeg_ir::{Codec, DecodeOptions};
67//!
68//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
69//! let mut input = File::open("part.sldprt")?;
70//! let decoded = SldprtCodec.decode(&mut input, &DecodeOptions::default())?;
71//! let (ir, _report, fidelity) = decoded.into_parts();
72//! let mut output = File::create("part-edited.sldprt")?;
73//! SldprtCodec
74//!     .plan(
75//!         cadmpeg_ir::codec::write::EncodeInput::new(&ir, Some(&fidelity)),
76//!         TargetRequest::Inherit,
77//!     )?
78//!     .write_to(&mut output)?;
79//! # Ok(())
80//! # }
81//! ```
82//!
83//! [`SldprtCodec`] implements [`cadmpeg_ir::codec::write::Encoder`] through
84//! `plan` → `write_to`. Encoding
85//! with the retained `source_fidelity` sidecar replays or patches the source
86//! image. Omitting `fidelity` regenerates the supported source-less profile.
87//! Supported geometry edits can patch the native partition when the entity
88//! graph and provenance remain stable. Retained writing synchronizes supported
89//! feature, sketch, parameter, configuration, and PMI edits. Semantic writing
90//! returns [`CodecError::NotImplemented`] when the requested IR shape cannot be
91//! represented.
92//!
93//! The semantic writer supports solid bodies with at most five regions and at
94//! most six shells per solid region, sheet bodies with one shell per region,
95//! analytic and non-periodic NURBS carriers, selected metadata and feature
96//! records, base colors, and sequential triangle-strip tessellation. It bakes
97//! right-handed rigid body transforms into geometry.
98//!
99//! [`Codec::inspect`]: cadmpeg_ir::Codec::inspect
100//! [`CodecError::NotImplemented`]: cadmpeg_core::CodecError::NotImplemented
101//! [`DecodeOptions::depth`]: cadmpeg_ir::DecodeOptions::depth
102//! [`DecodeDepth::Container`]: cadmpeg_core::decode::DecodeDepth::Container
103
104mod annotations;
105mod appearance;
106mod archive;
107mod assembly;
108mod brep;
109mod carchive;
110mod classification;
111mod container;
112mod decode;
113mod dialect;
114pub mod exact_ledger;
115mod feature_schema;
116mod framed_string;
117#[doc(hidden)]
118pub mod fuzz;
119mod history;
120mod lane_refusal;
121/// Byte-offset constants generated from `docs/layouts/sldprt.toml`.
122mod layout;
123mod loss;
124mod metadata;
125mod native;
126mod parasolid;
127mod pmi;
128mod records;
129mod resolved_features;
130mod swift;
131mod tessellation;
132mod writer;
133mod writer_patch;
134mod writer_transform;
135
136use cadmpeg_core::decode::{DecodeContext, DecodeDepth, View};
137use cadmpeg_core::dialect::DialectId;
138use cadmpeg_core::CodecError;
139use cadmpeg_ir::ContainerSummary;
140use std::io::Write;
141
142use cadmpeg_ir::codec::write::{
143    target::{Catalog, ResolvedWrite},
144    ArenaCoverage, ArenaDispositions, Consumption, DepthNeed, EncodeInput, EncoderBackend,
145    ExportBody, PatchConsumption, WritePath,
146};
147use cadmpeg_ir::codec::{CodecBackend, Confidence, Decoded, FormatId};
148use cadmpeg_ir::document::CadIr;
149use cadmpeg_ir::hash::DOCUMENT_LOCAL_DIGEST_ATTRIBUTE;
150use cadmpeg_ir::ids::UnknownId;
151use cadmpeg_ir::{report::check::Finding, Annotations, SourceFidelity};
152
153/// Retained-record id of the whole source part, the byte-replay baseline.
154const SOURCE_IMAGE_ID: &str = "sldprt:file:source-image#0";
155
156/// The identity of the retained source image, composed from its literal parts.
157fn source_image_id() -> UnknownId {
158    UnknownId::compose(
159        &cadmpeg_ir::identity_namespace!("sldprt", "file", "source-image"),
160        cadmpeg_ir::identity_key!("0"),
161    )
162}
163
164/// Codec for `SolidWorks` `.sldprt` part documents.
165#[derive(Debug, Default, Clone, Copy)]
166pub struct SldprtCodec;
167
168/// A joined native-record reference whose retained payload stays owned by the
169/// source-fidelity sidecar throughout export.
170struct SourceRecord<'a> {
171    id: UnknownId,
172    data: Option<&'a [u8]>,
173}
174
175impl SldprtCodec {
176    /// Replay the retained source image when the document is untouched since the
177    /// decode that recorded its baseline, and write it semantically otherwise.
178    ///
179    /// The `document_local_sha256` baseline answers only "was this edited since
180    /// it was decoded?", bitwise and on this machine; see
181    /// [`decode::document_local_sha256`]. An absent baseline means the question
182    /// cannot be answered, so the document takes the semantic write path — the
183    /// conservative branch, which reproduces the document from the IR instead of
184    /// replaying bytes that may no longer describe it.
185    ///
186    /// The returned [`WritePath`] is the branch this function took, not a
187    /// judgement made about its output afterwards. The semantic writer can
188    /// reproduce the input byte for byte when nothing it rewrites has moved, so
189    /// the output cannot say which branch ran and only this value can.
190    fn write_preserved_with_annotations(
191        ir: &CadIr,
192        annotations: &Annotations,
193        records: &[SourceRecord<'_>],
194        writer: &mut dyn Write,
195    ) -> Result<Written, CodecError> {
196        let expected = ir
197            .source
198            .as_ref()
199            .and_then(|source| source.attributes.get(DOCUMENT_LOCAL_DIGEST_ATTRIBUTE));
200        let Some(expected) = expected else {
201            return Self::write_semantic(
202                ir,
203                annotations,
204                records,
205                SemanticFidelity::ReplaySkipped(ReplaySkipped::BaselineMissing),
206                writer,
207            );
208        };
209        if decode::document_local_sha256(ir)? != *expected {
210            return Self::write_semantic(
211                ir,
212                annotations,
213                records,
214                SemanticFidelity::ReplaySkipped(ReplaySkipped::DigestMismatch),
215                writer,
216            );
217        }
218        let Some(record) = records
219            .iter()
220            .find(|record| record.id.as_str() == SOURCE_IMAGE_ID)
221        else {
222            return Self::write_semantic(
223                ir,
224                annotations,
225                records,
226                SemanticFidelity::ReplaySkipped(ReplaySkipped::ImageMissing),
227                writer,
228            );
229        };
230        let Some(data) = record.data.as_ref() else {
231            return Self::write_semantic(
232                ir,
233                annotations,
234                records,
235                SemanticFidelity::ReplaySkipped(ReplaySkipped::ImageMissing),
236                writer,
237            );
238        };
239        writer.write_all(data)?;
240        Ok(Written::Replayed)
241    }
242
243    /// Runs the semantic writer and names the path it stands for: `Patched` when
244    /// retained source records fed the write, `Synthesized` when the document was
245    /// built from the neutral IR alone.
246    fn write_semantic(
247        ir: &CadIr,
248        annotations: &Annotations,
249        records: &[SourceRecord<'_>],
250        fidelity: SemanticFidelity,
251        writer: &mut dyn Write,
252    ) -> Result<Written, CodecError> {
253        let writer::SemanticOutput {
254            dialect,
255            coverage,
256            omitted_envelope_bytes,
257        } = writer::write_semantic_with_records(ir, annotations, records, writer)?;
258        let native = ir
259            .native
260            .namespace("sldprt")
261            .map(|namespace| native::SldprtNative::load(namespace).map_err(CodecError::from))
262            .transpose()?;
263        let source_arena = cadmpeg_core::decode::DecodeArena::new();
264        let source_context = records
265            .iter()
266            .find(|record| record.id.as_str() == SOURCE_IMAGE_ID)
267            .and_then(|record| record.data)
268            .map(|bytes| {
269                cadmpeg_core::decode::DecodeContext::from_root_bytes(
270                    bytes,
271                    &source_arena,
272                    &cadmpeg_core::decode::DecodePolicy::desktop(),
273                )
274            })
275            .transpose()?;
276        let source_scan = source_context
277            .as_ref()
278            .map(|(ctx, root)| container::scan(ctx, *root))
279            .transpose()?;
280        history::write::brep_agreement::validate(ir, native.as_ref(), source_scan.as_ref())?;
281        Ok(Written::Semantic {
282            path: if records.is_empty() {
283                SemanticPath::Synthesized
284            } else {
285                SemanticPath::Patched
286            },
287            dialect,
288            fidelity,
289            coverage,
290            omitted_envelope_bytes,
291        })
292    }
293}
294
295/// Why an eligible retained-image replay took the semantic path instead.
296#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297enum ReplaySkipped {
298    BaselineMissing,
299    DigestMismatch,
300    ImageMissing,
301}
302
303impl ReplaySkipped {
304    fn consumption(self) -> Consumption {
305        Consumption::Degraded {
306            reason: match self {
307                Self::BaselineMissing => "preserved SLDPRT source digest baseline is unavailable",
308                Self::DigestMismatch => {
309                    "decoded model no longer matches the preserved SLDPRT source digest"
310                }
311                Self::ImageMissing => "preserved SLDPRT source image is unavailable",
312            }
313            .into(),
314        }
315    }
316}
317
318/// How a semantic write consumed the fidelity it was given. A replay skip
319/// carries the sole typed reason from which both the consumption and any
320/// applicable loss are derived.
321enum SemanticFidelity {
322    NotConsumed,
323    ReplaySkipped(ReplaySkipped),
324}
325
326impl SemanticFidelity {
327    fn consumption(&self) -> Consumption {
328        match self {
329            Self::NotConsumed => Consumption::NotConsumed,
330            Self::ReplaySkipped(reason) => reason.consumption(),
331        }
332    }
333}
334
335/// The two ways the semantic writer can produce a document. A verbatim replay
336/// is not one of them, so a replay can never carry a semantic skip reason.
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338enum SemanticPath {
339    /// Retained source records fed the write.
340    Patched,
341    /// The document was built from the neutral IR alone.
342    Synthesized,
343}
344
345impl SemanticPath {
346    fn write_path(self, consumption: Consumption) -> WritePath {
347        match self {
348            Self::Patched => WritePath::Patched {
349                consumption: PatchConsumption::Independent(consumption),
350            },
351            Self::Synthesized => WritePath::Synthesized { consumption },
352        }
353    }
354}
355
356/// One completed write.
357enum Written {
358    /// The retained source image, byte for byte. The dialect is the source's
359    /// own, which this write neither chooses nor needs to name.
360    Replayed,
361    /// A semantic write, in the dialect the emitted `swSolidWorks` envelope
362    /// declares.
363    Semantic {
364        path: SemanticPath,
365        dialect: DialectId,
366        fidelity: SemanticFidelity,
367        coverage: ArenaDispositions,
368        omitted_envelope_bytes: usize,
369    },
370}
371
372impl Written {
373    /// Which branch ran. The semantic writer can reproduce its input byte for
374    /// byte, so the output cannot say and only this value can.
375    fn path(&self) -> WritePath {
376        match self {
377            Self::Replayed => WritePath::VerbatimReplay,
378            Self::Semantic { path, fidelity, .. } => path.write_path(fidelity.consumption()),
379        }
380    }
381
382    /// Which model arenas the output carries. A replay runs only while the
383    /// document digest matches its decode baseline, so it carries every arena.
384    fn coverage(&self) -> ArenaCoverage {
385        match self {
386            Self::Replayed => ArenaCoverage::Complete,
387            Self::Semantic { coverage, .. } => ArenaCoverage::Declared(*coverage),
388        }
389    }
390
391    /// The semantic path that ran instead of an eligible replay, with why.
392    fn replay_skipped(&self) -> Option<(SemanticPath, ReplaySkipped)> {
393        match self {
394            Self::Semantic {
395                path,
396                fidelity: SemanticFidelity::ReplaySkipped(reason),
397                ..
398            } => Some((*path, *reason)),
399            _ => None,
400        }
401    }
402}
403
404impl CodecBackend for SldprtCodec {
405    const FORMAT: FormatId = FormatId::new(dialect::FORMAT);
406
407    fn validate_native(
408        ctx: &DecodeContext<'_>,
409        ir: &CadIr,
410        _source: Option<&cadmpeg_ir::SourceFidelity>,
411    ) -> Result<Vec<Finding>, CodecError> {
412        resolved_features::validate::validate_native(ctx, ir)
413    }
414
415    fn detect_impl(
416        &self,
417        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
418        prefix: cadmpeg_core::decode::View<'_>,
419    ) -> Result<Confidence, cadmpeg_core::CodecError> {
420        let prefix = prefix.window();
421        if container::looks_like_sldprt(ctx, prefix)? {
422            Ok(Confidence::High)
423        } else {
424            Ok(Confidence::No)
425        }
426    }
427
428    fn inspect_impl(
429        &self,
430        ctx: &DecodeContext<'_>,
431        root: View<'_>,
432    ) -> Result<ContainerSummary, CodecError> {
433        let scan = container::scan(ctx, root)?;
434        let classification = dialect::classify_layers(&scan)?;
435        let mut summary = container::summarize(&scan, classification.layers().clone());
436        classification.append_losses(&mut summary.losses);
437        Ok(summary)
438    }
439
440    fn decode_impl(&self, ctx: &DecodeContext<'_>, root: View<'_>) -> Result<Decoded, CodecError> {
441        decode::decode(ctx, root)
442    }
443}
444
445impl EncoderBackend for SldprtCodec {
446    const FORMAT: FormatId = <Self as CodecBackend>::FORMAT;
447    /// Patches the retained source, so the design records it rewrites must be
448    /// present.
449    const NEEDS: DepthNeed = DepthNeed::AtLeast(DecodeDepth::Full);
450    type Target = Catalog;
451    const TARGET: Catalog = Catalog::new(dialect::TARGETS, Some(0));
452
453    fn plan_resolved(
454        &self,
455        input: EncodeInput<'_>,
456        target: ResolvedWrite<'_>,
457    ) -> Result<ExportBody, CodecError> {
458        writer::target::plan(input, &target)
459    }
460}
461
462fn source_records<'a>(
463    ir: &CadIr,
464    source_fidelity: &'a SourceFidelity,
465) -> Result<Vec<SourceRecord<'a>>, CodecError> {
466    let mut records = ir
467        .native_unknowns_iter("sldprt")
468        .map(|reference| {
469            let reference = reference?;
470            let retained = source_fidelity
471                .retained_record(reference.id.as_str())
472                .ok_or_else(|| {
473                    cadmpeg_ir::native::NativeConvertError::MissingRetainedSourceRecord(
474                        reference.id.as_str().to_owned(),
475                    )
476                })?;
477            Ok(SourceRecord {
478                id: reference.id,
479                data: retained.data(),
480            })
481        })
482        .collect::<Result<Vec<_>, cadmpeg_ir::native::NativeConvertError>>()?;
483    if let Some(source) = source_fidelity.retained_record(SOURCE_IMAGE_ID) {
484        records.push(SourceRecord {
485            id: source_image_id(),
486            data: source.data(),
487        });
488    }
489    Ok(records)
490}
491
492#[cfg(test)]
493mod golden_tests;
494#[cfg(test)]
495mod integration_tests;
496#[cfg(test)]
497mod test_support;
498
499#[cfg(test)]
500mod tests {
501    use super::SOURCE_IMAGE_ID;
502
503    #[test]
504    fn source_record_join_borrows_the_retained_source_image() {
505        let payload = vec![0x5a; 4096];
506        let payload_ptr = payload.as_ptr();
507        let mut fidelity = cadmpeg_ir::SourceFidelity::default();
508        let id: cadmpeg_ir::ids::UnknownId = SOURCE_IMAGE_ID
509            .to_owned()
510            .try_into()
511            .expect("source image identity");
512        let record = cadmpeg_ir::source_fidelity::RetainedSourceRecord::from_bytes(
513            "source",
514            0,
515            cadmpeg_ir::source_fidelity::RetainedBytes::Inline { data: payload },
516        )
517        .expect("source image extent");
518        fidelity
519            .insert_retained_record(id, record)
520            .expect("source image identity is unique");
521
522        let records = crate::source_records(
523            &cadmpeg_ir::examples::unit_cube().expect("unit cube fixture is admitted"),
524            &fidelity,
525        )
526        .unwrap();
527        let retained = records[0].data.expect("retained source bytes");
528        assert_eq!(retained.as_ptr(), payload_ptr);
529    }
530}